Compare commits

..

65 Commits

Author SHA1 Message Date
Kayne Ruse f667f503e7 Simple Multiplayer is working 2013-06-25 00:12:53 +10:00
Kayne Ruse 50bef9736c Deleting players on logout 2013-06-24 23:34:48 +10:00
Kayne Ruse 6d1ba24404 Simplified the packet system 2013-06-24 22:59:06 +10:00
Kayne Ruse ebd8c5e6fc Synchronization works 2013-06-24 21:46:11 +10:00
Kayne Ruse 42f9c5e1df Fixed for loops using the auto keyword 2013-06-24 16:31:38 +10:00
Kayne Ruse 3f2fcdf9e1 Players are being added in the client
The client sends a debug player to the server, with a constant movement to
show that the new client _is_ connecting. The next thing to add is the
sync system, so that the clients know what the server looks like when they
first join.
2013-06-24 16:15:48 +10:00
Kayne Ruse 2235f307e7 Added some multiplayer code to the server 2013-06-24 13:31:19 +10:00
Kayne Ruse 23782ff4e3 Removed maximum number of clients 2013-06-24 12:41:10 +10:00
Kayne Ruse 2a46f82f84 Updated README.md 2013-06-24 12:39:31 +10:00
Kayne Ruse 6a32599a69 Fixed a derp with the time 2013-06-24 12:18:36 +10:00
Kayne Ruse 0ca84a8653 Branch 'dev-map' is stable, merging into 'dev' 2013-06-24 10:45:51 +10:00
Kayne Ruse 66b2d6566c Branch 'dev-char' is stable, merging into 'dev' 2013-06-24 10:43:49 +10:00
Kayne Ruse 56375d64b6 Moved packets into their own namespace 2013-06-24 10:27:43 +10:00
Kayne Ruse 9608761cd5 Moved the entry structs into their own headers 2013-06-24 10:01:52 +10:00
Kayne Ruse c1d03d1cef Changed the name of the editor's main class 2013-06-24 09:26:25 +10:00
Kayne Ruse 09c88c7232 Merge branch 'dev' into dev-map 2013-06-24 09:23:12 +10:00
Kayne Ruse ddb93cfcf1 Changed the name of the client's main class 2013-06-24 09:22:43 +10:00
Kayne Ruse 42787dcb69 Explicitly deleted copy and move constructors 2013-06-24 09:13:27 +10:00
Kayne Ruse fcb17a8116 Merge branch 'dev' into dev-char 2013-06-24 09:02:36 +10:00
Kayne Ruse 2dc21f64fd Merge branch 'dev' into dev-map 2013-06-24 09:01:20 +10:00
Kayne Ruse f049c96df7 Switched from the service locator pattern to singleton pattern 2013-06-24 09:00:50 +10:00
Kayne Ruse d9ffa22b76 Created the editor shell 2013-06-23 16:19:41 +10:00
Kayne Ruse 24654d9e17 Merged the new frame rate system into dev-char 2013-06-23 15:11:24 +10:00
Kayne Ruse 7ad855348f Implemented a simpler frame rate system 2013-06-23 15:05:52 +10:00
Kayne Ruse d833b76856 PlayerCharacter is moving around smoothly 2013-06-23 13:53:55 +10:00
Kayne Ruse 3232925ccd Codebase update 2013-06-22 18:39:56 +10:00
Kayne Ruse e4ffba80aa Fixed incorrect preprocessor guard 2013-06-22 18:22:21 +10:00
Kayne Ruse a4d184ca75 Moved random code out of defines.* 2013-06-21 21:36:48 +10:00
Kayne Ruse 89179626be Improved Vector2 with floats & non-member operators 2013-06-21 15:23:07 +10:00
Kayne Ruse fc381348a5 Updated the game pitch 2013-06-21 14:50:59 +10:00
Kayne Ruse 5e99192fbf Lose focus on a server after a button is released 2013-06-18 19:38:08 +10:00
Kayne Ruse 33adb4b1a5 Put the license header into all source files 2013-06-18 16:40:51 +10:00
Kayne Ruse 33474cc6c0 Smooth connection and disconnection complete
The clients can connect and disconnect from the server with known no
issues. There is no way to shutdown the server yet, but it might be
possible to kick someone else from the server soon.
2013-06-18 16:21:42 +10:00
Kayne Ruse e833129983 Added guards incase of multiple calls 2013-06-18 14:06:57 +10:00
Kayne Ruse fd65fec5f7 The client is registering with the server 2013-06-17 19:53:22 +10:00
Kayne Ruse 69f03cd250 Working on connection systems 2013-06-17 19:04:05 +10:00
Kayne Ruse 27ed91688a Added the meta field to Packet to support Packet's metadata 2013-06-17 18:37:27 +10:00
Kayne Ruse 68ec7323a3 I can't progress until I add the address information to the Packet struct 2013-06-17 17:51:26 +10:00
Kayne Ruse 7b11bf22cb Specified a minimum Packet size for the DEBUG build 2013-06-17 17:14:10 +10:00
Kayne Ruse d83a536f35 Added debug output 2013-06-17 15:57:12 +10:00
Kayne Ruse ea761fb5bb Fixed the bug
running was false when it was checked in networkQueue(), so the thread was
ending early.
2013-06-17 15:49:57 +10:00
Kayne Ruse 685ca94335 This has the odd quirk related to networkQueue() 2013-06-17 15:15:27 +10:00
Kayne Ruse 5b2fd80a61 Fixed the Packet::type bug
In popNetworkPacket(), a second Packet p was being created, which was
destroyed when it went out of scope, and the original Packet p was being
returned.
2013-06-17 11:01:00 +10:00
Kayne Ruse d1aac9ffd8 Added peekNetworkPacket() 2013-06-17 10:12:20 +10:00
Kayne Ruse 3d92fb77b3 Server is multithreaded, but no connection is visible
UDPNetworkUtility and ConfigUtility are now using the ServiceLocator
pattern in the server, and networkQueue() is running in a separate thread
in the server. However, there seems to be a problem somewhere, since the
broadcast request & response are not producing any visible output.
2013-06-17 10:03:12 +10:00
Kayne Ruse 009e7b845b Fixed network error, leaving try block in place for the time being
It seems that the union type Packet didn't initialize Packet::type to
PacketType::NONE using in class initialization. I've fixed this by moving
the initialization of Packet::type to Packet::Packet().

This might actually be a compiler error, I might need to let someone know.
2013-06-17 09:09:04 +10:00
Kayne Ruse 752dcadfa1 Merge branch 'master' into dev 2013-06-17 08:32:02 +10:00
Kayne Ruse 9599d82db3 Added binary files, since git can't find .gitconfig on my brother's PC 2013-06-17 08:31:35 +10:00
Kayne Ruse 7fef2501a3 Glitch with threading 2013-06-17 07:24:16 +10:00
Kayne Ruse 419c9d8765 Moved the common directory into the libs directory 2013-06-16 13:59:11 +10:00
Kayne Ruse a0fa874a29 The server list is being populated from the network 2013-06-13 12:55:26 +10:00
Kayne Ruse 5110ebc1b2 Changed the escape key & quit event's function slightly 2013-06-13 12:31:29 +10:00
Kayne Ruse 843053d307 Implemented the server list box, still messy 2013-06-13 12:26:27 +10:00
Kayne Ruse 2148c1f13e Menu framework in place 2013-06-12 21:56:17 +10:00
Kayne Ruse f3ec4d4d8e Splash screen loads and displays correctly 2013-06-12 19:48:46 +10:00
Kayne Ruse cbd388f4ed Started using ServiceLocator, experimental 2013-06-12 06:35:43 +10:00
Kayne Ruse 37a9e4268b Imported the rsc directory from prototype-1 2013-06-12 05:23:06 +10:00
Kayne Ruse dfe0b4985a Modified build requirements
SDL_net needs to be _installed_ to the computer, rather than simply linked to.
This source distribution should be enough for that.
2013-06-12 04:37:01 +10:00
Kayne Ruse 7ca7f7f015 Added broadcast handling 2013-06-10 18:06:24 +10:00
Kayne Ruse c21a95f3e9 working on the server's skeleton, still slow going 2013-06-10 17:23:26 +10:00
Kayne Ruse 0a48131de4 Added common and test directories 2013-06-09 17:06:32 +10:00
Kayne Ruse 78326a3bbd Added a note about the project's development stage 2013-06-09 14:16:33 +10:00
Kayne Ruse 253e9ec8fc Created server shell 2013-06-08 01:52:19 +10:00
Kayne Ruse a1b248d1d7 Created the client program's framework
There are six scenes here, each of which representing roughly one part of
the final program's backbone.
2013-06-08 01:36:19 +10:00
Kayne Ruse 2757911399 Libraries are building correctly 2013-06-07 04:10:31 +10:00
92 changed files with 6184 additions and 674 deletions
+21
View File
@@ -0,0 +1,21 @@
#Editor generated files
#*.sln
#*.vcproj
*.suo
*.ncb
*.user
#Directories
Release/
Debug/
Out/
#Project generated files
*.db
*.o
*.a
*.exe
#Shell files
*.bat
*.sh
+31
View File
@@ -0,0 +1,31 @@
_This project is currently in it's early prototype stage. You can see other versions in various branches or tagged as prototype-X._
Tortuga is a 2D multiplayer role playing game set in a large archipelago occupied by warring pirate clans. The emphasis of this game is on multiplayer cooperation, competition, and server customization. The game runs on highly customizable server software that can support up to 150 simultaneous players or more. The player characters are tied to the server where they are created and are susceptible to permadeath: deletion of a character upon death.
## Libraries
* [SDL](http://www.libsdl.org/) - Simple DirectMedia Layer API
* [SDL_net](http://www.libsdl.org/projects/SDL_net/) - SDL's networking extension. This must be installed first.
* [Codebase](https://github.com/Ratstail91/Codebase) - generic reusable code modules
## Instructions
* This project uses C++11, which is available via GNU (or MinGW) 4.7, or Visual Studio 2012. Personally, I'm using MinGW 4.7.2.
* I'm trying to keep this as IDE agnostic as possible, so if you use an IDE, please add it's files to .gitignore.
* You can read more details on the Tortuga wiki [here](https://github.com/Ratstail91/Tortuga/wiki).
## Copyright
The current version of Tortuga is released under the [zlib license](http://en.wikipedia.org/wiki/Zlib_License).
Copyright (c) 2013 Kayne Ruse
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
+2 -2
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -34,7 +34,7 @@ SDL_Surface* BaseScene::screen = nullptr;
//-------------------------
BaseScene::BaseScene() {
//
nextScene = SceneList::CONTINUE;
}
BaseScene::~BaseScene() {
+6 -6
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -28,18 +28,18 @@
class BaseScene {
public:
//Public access members
/* Public access members */
BaseScene();
virtual ~BaseScene();
//Program control
/* Program control */
static SDL_Surface* SetScreen(int w, int h, int bpp = 0, Uint32 flags = SDL_HWSURFACE|SDL_DOUBLEBUF);
static SDL_Surface* GetScreen();
SceneList SetNextScene(SceneList sceneIndex);
SceneList GetNextScene() const;
//Frame loop
/* Frame loop */
virtual void RunFrame(double delta);
virtual void RenderFrame();
@@ -50,7 +50,7 @@ protected:
virtual void FrameEnd() {}
virtual void Render(SDL_Surface* const screen) {}
//Event handlers
/* Event handlers */
virtual void QuitEvent() { SetNextScene(SceneList::QUIT); }
virtual void MouseMotion(SDL_MouseMotionEvent const&) {}
virtual void MouseButtonDown(SDL_MouseButtonEvent const&) {}
@@ -68,7 +68,7 @@ protected:
private:
static SDL_Surface* screen;
SceneList nextScene = SceneList::CONTINUE;
SceneList nextScene;
};
#endif
+183
View File
@@ -0,0 +1,183 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "client_application.hpp"
#include <stdexcept>
#include <chrono>
//-------------------------
//Scene headers
//-------------------------
//Add the custom scene headers here
#include "in_combat.hpp"
#include "in_world.hpp"
#include "lobby.hpp"
#include "main_menu.hpp"
#include "option_screen.hpp"
#include "splash_screen.hpp"
//-------------------------
//Public access members
//-------------------------
ClientApplication::ClientApplication() {
//
}
ClientApplication::~ClientApplication() {
UnloadScene();
}
/* ClientApplication::Init()
* This function initializes the entire program. There are a number of things
* that could go wrong here, which is why there is such an unusual order of
* operations.
* Important things to note:
* The APIs are initiated here.
* The global objects are initialized here.
* The game's screen is created here, based on information loaded from the config file.
* The ConfigUtility's call to Load() also ensures that the "rsc\" folder is in the directory. It's easy to forget it.
*/
void ClientApplication::Init() {
//load the config file
try {
configUtil->Load("rsc/config.cfg");
}
catch(std::runtime_error& e) {
std::string s = e.what();
s += "; Ensure that the \"rsc\" directory is present";
throw(std::runtime_error(s));
}
//initialize the APIs
if (SDL_Init(SDL_INIT_VIDEO)) {
throw(std::runtime_error("Failed to initialize SDL"));
}
if (SDLNet_Init()) {
throw(std::runtime_error("Failed to initialize SDL_net"));
}
//create the screen
Uint32 flags = SDL_HWSURFACE | SDL_DOUBLEBUF;
flags |= configUtil->Bool("screen.f") ? SDL_FULLSCREEN : 0;
BaseScene::SetScreen(
configUtil->Int("screen.w"),
configUtil->Int("screen.h"),
SDL_GetVideoInfo()->vfmt->BitsPerPixel,
flags);
//initiate the remaining singletons
netUtil->Open(0, sizeof(Packet));
}
void ClientApplication::Proc() {
LoadScene(SceneList::FIRST);
//prepare the time system
typedef std::chrono::high_resolution_clock Clock;
Clock::duration delta(16 * Clock::duration::period::den / std::milli::den);
Clock::time_point simTime = Clock::now();
Clock::time_point realTime;
//The main loop
while(activeScene->GetNextScene() != SceneList::QUIT) {
//switch scenes when necessary
if (activeScene->GetNextScene() != SceneList::CONTINUE) {
LoadScene(activeScene->GetNextScene());
continue;
}
//update the current time
realTime = Clock::now();
//simulate game time
while (simTime < realTime) {
//call each user defined function
activeScene->RunFrame(double(delta.count()) / Clock::duration::period::den);
simTime += delta;
}
//draw the game to the screen
activeScene->RenderFrame();
//give the computer a break
SDL_Delay(10);
}
UnloadScene();
}
void ClientApplication::Quit() {
//clean up the singletons
netUtil->Close();
surfaceMgr->FreeAll();
//clean up the scene
UnloadScene();
//deinitialize the APIs
SDLNet_Quit();
SDL_Quit();
}
//-------------------------
//Private access members
//-------------------------
void ClientApplication::LoadScene(SceneList sceneIndex) {
UnloadScene();
switch(sceneIndex) {
//add scene creation calls here
case SceneList::INCOMBAT:
activeScene = new InCombat();
break;
case SceneList::INWORLD:
activeScene = new InWorld();
break;
case SceneList::LOBBY:
activeScene = new Lobby();
break;
case SceneList::MAINMENU:
activeScene = new MainMenu();
break;
case SceneList::OPTIONSCREEN:
activeScene = new OptionScreen();
break;
case SceneList::FIRST:
case SceneList::SPLASHSCREEN:
activeScene = new SplashScreen();
break;
default:
throw(std::logic_error("Failed to recognize the scene index"));
}
}
void ClientApplication::UnloadScene() {
delete activeScene;
activeScene = nullptr;
}
+62
View File
@@ -0,0 +1,62 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CLIENTAPPLICATION_HPP_
#define CLIENTAPPLICATION_HPP_
#include "scene_list.hpp"
#include "base_scene.hpp"
#include "singleton.hpp"
#include "packet.hpp"
#include "information_manager.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "udp_network_utility.hpp"
#include "SDL/SDL.h"
class ClientApplication {
public:
/* Public access members */
ClientApplication();
~ClientApplication();
void Init();
void Proc();
void Quit();
ClientApplication(ClientApplication const&) = delete;
ClientApplication(ClientApplication const&&) = delete;
private:
/* Private access members */
void LoadScene(SceneList sceneIndex);
void UnloadScene();
BaseScene* activeScene = nullptr;
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
InformationManager* infoMgr = Singleton<InformationManager>::Get();
};
#endif
+90
View File
@@ -0,0 +1,90 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "in_combat.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
InCombat::InCombat() {
#ifdef DEBUG
cout << "entering InCombat" << endl;
#endif
}
InCombat::~InCombat() {
#ifdef DEBUG
cout << "leaving InCombat" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void InCombat::FrameStart() {
//
}
void InCombat::Update(double delta) {
//
}
void InCombat::FrameEnd() {
//
}
void InCombat::Render(SDL_Surface* const screen) {
//
}
//-------------------------
//Event handlers
//-------------------------
void InCombat::MouseMotion(SDL_MouseMotionEvent const& motion) {
//
}
void InCombat::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//
}
void InCombat::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//
}
void InCombat::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
QuitEvent();
break;
}
}
void InCombat::KeyUp(SDL_KeyboardEvent const& key) {
//
}
+48
View File
@@ -0,0 +1,48 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef INCOMBAT_HPP_
#define INCOMBAT_HPP_
#include "base_scene.hpp"
class InCombat : public BaseScene {
public:
/* Public access members */
InCombat();
~InCombat();
protected:
/* Frame loop */
void FrameStart();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
/* Event handlers */
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
};
#endif
+314
View File
@@ -0,0 +1,314 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "in_world.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
InWorld::InWorld() {
#ifdef DEBUG
cout << "entering InWorld" << endl;
#endif
cout << "Client Index: " << infoMgr->GetClientIndex() << endl;
font.SetSurface(surfaceMgr->Get("font"));
//debugging
Packet p;
p.meta.type = Packet::Type::PLAYER_NEW;
p.meta.clientIndex = infoMgr->GetClientIndex();
snprintf(p.playerInfo.handle, PACKET_STRING_SIZE, "%s", configUtil->CString("handle"));
snprintf(p.playerInfo.avatar, PACKET_STRING_SIZE, "%s", configUtil->CString("avatar"));
p.playerInfo.position = {50, 50};
p.playerInfo.motion = {0, 0};
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
//request a sync
p.meta.type = Packet::Type::SYNCHRONIZE;
p.meta.clientIndex = infoMgr->GetClientIndex();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
}
InWorld::~InWorld() {
#ifdef DEBUG
cout << "leaving InWorld" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void InWorld::FrameStart() {
//
}
void InWorld::Update(double delta) {
while(HandlePacket(popNetworkPacket()));
for (auto& it : playerCharacters) {
it.second.Update(delta);
}
}
void InWorld::FrameEnd() {
//
}
void InWorld::Render(SDL_Surface* const screen) {
ClockFrameRate();
for (auto& it : playerCharacters) {
it.second.DrawTo(screen);
}
//since we're using this twice, make a tmp var
string fps = itos(GetFrameRate());
font.DrawStringTo(fps, screen, screen->w - fps.size() * font.GetCharW(), 0);
}
//-------------------------
//Event handlers
//-------------------------
void InWorld::QuitEvent() {
//ensure that the client is disconnected properly
ExitGame();
SetNextScene(SceneList::QUIT);
}
void InWorld::MouseMotion(SDL_MouseMotionEvent const& motion) {
//
}
void InWorld::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//
}
void InWorld::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//
}
void InWorld::KeyDown(SDL_KeyboardEvent const& key) {
//general
switch(key.keysym.sym) {
case SDLK_ESCAPE:
ExitGame();
break;
}
//player movement
if (infoMgr->GetPlayerIndex() == -1) {
return;
}
switch(key.keysym.sym) {
case SDLK_w:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::NORTH);
SendState();
break;
case SDLK_s:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::SOUTH);
SendState();
break;
case SDLK_a:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::WEST);
SendState();
break;
case SDLK_d:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::EAST);
SendState();
break;
}
}
void InWorld::KeyUp(SDL_KeyboardEvent const& key) {
//player movement reversed
switch(key.keysym.sym) {
case SDLK_w:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::SOUTH);
SendState();
break;
case SDLK_s:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::NORTH);
SendState();
break;
case SDLK_a:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::EAST);
SendState();
break;
case SDLK_d:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::WEST);
SendState();
break;
}
}
//-------------------------
//Utilities
//-------------------------
int InWorld::HandlePacket(Packet p) {
switch(p.meta.type) {
case Packet::Type::NONE:
//DO NOTHING
return 0;
break;
case Packet::Type::PING:
//quick pong
p.meta.type = Packet::Type::PONG;
p.meta.clientIndex = infoMgr->GetClientIndex();
netUtil->Send(&p.meta.address, &p, sizeof(Packet));
break;
case Packet::Type::PONG:
//
break;
// case Packet::Type::BROADCAST_REQUEST:
// //
// break;
// case Packet::Type::BROADCAST_RESPONSE:
// //
// break;
// case Packet::Type::JOIN_REQUEST:
// //
// break;
// case Packet::Type::JOIN_RESPONSE:
// //
// break;
case Packet::Type::DISCONNECT:
HandleDisconnection(p);
break;
// case Packet::Type::SYNCHRONIZE:
// //
// break;
case Packet::Type::PLAYER_NEW:
AddPlayer(p);
break;
case Packet::Type::PLAYER_DELETE:
RemovePlayer(p);
break;
case Packet::Type::PLAYER_UPDATE:
UpdatePlayer(p);
break;
default:
throw(runtime_error("Failed to recognize the packet type: " + itos(int(p.meta.type))));
}
return 1;
}
void InWorld::Disconnect() {
Packet p;
//delete the player
p.meta.type = Packet::Type::PLAYER_DELETE;
p.meta.clientIndex = infoMgr->GetClientIndex();
p.playerInfo.index = infoMgr->GetPlayerIndex();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
//disconnect
p.meta.type = Packet::Type::DISCONNECT;
p.meta.clientIndex = infoMgr->GetClientIndex();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
netUtil->Unbind(GAME_CHANNEL);
//reset the client
infoMgr->ResetClientIndex();
infoMgr->ResetPlayerIndex();
}
void InWorld::ExitGame() {
Disconnect();
SetNextScene(SceneList::MAINMENU);
endQueueThread();
cout << "The game session has ended" << endl;
}
void InWorld::HandleDisconnection(Packet& disconnect) {
Disconnect();
SetNextScene(SceneList::MAINMENU);
endQueueThread();
cout << "You have been disconnected" << endl;
}
void InWorld::AddPlayer(Packet& p) {
if (playerCharacters.find(p.playerInfo.index) != playerCharacters.end()) {
throw(runtime_error("Duplicate players detected"));
}
//position
playerCharacters[p.playerInfo.index].SetPosition(p.playerInfo.position);
playerCharacters[p.playerInfo.index].SetMotion(p.playerInfo.motion);
//sprite
playerCharacters[p.playerInfo.index].GetSprite()->SetSurface(surfaceMgr->Get(p.playerInfo.avatar), 32, 48);
playerCharacters[p.playerInfo.index].FaceDirection();
//is it this player?
if (p.meta.clientIndex == infoMgr->GetClientIndex()) {
infoMgr->SetPlayerIndex(p.playerInfo.index);
}
//debugging
cout << "New player, index " << p.playerInfo.index << endl;
}
void InWorld::RemovePlayer(Packet& p) {
if (playerCharacters.find(p.playerInfo.index) == playerCharacters.end()) {
throw(runtime_error("Player to delete not found"));
}
playerCharacters.erase(p.playerInfo.index);
}
void InWorld::UpdatePlayer(Packet& p) {
if (playerCharacters.find(p.playerInfo.index) == playerCharacters.end()) {
AddPlayer(p);
return;
}
playerCharacters[p.playerInfo.index].SetPosition(p.playerInfo.position);
playerCharacters[p.playerInfo.index].SetMotion(p.playerInfo.motion);
playerCharacters[p.playerInfo.index].FaceDirection();
}
void InWorld::SendState() {
//send the state of this player's character
if (infoMgr->GetPlayerIndex() == -1) {
return;
}
Packet p;
p.meta.type = Packet::Type::PLAYER_UPDATE;
p.meta.clientIndex = infoMgr->GetClientIndex();
p.playerInfo.index = infoMgr->GetPlayerIndex();
p.playerInfo.position = playerCharacters[infoMgr->GetPlayerIndex()].GetPosition();
p.playerInfo.motion = playerCharacters[infoMgr->GetPlayerIndex()].GetMotion();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
}
+89
View File
@@ -0,0 +1,89 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef INWORLD_HPP_
#define INWORLD_HPP_
#include "base_scene.hpp"
#include "utilities.hpp"
#include "defines.hpp"
#include "singleton.hpp"
#include "packet.hpp"
#include "network_queue.hpp"
#include "information_manager.hpp"
#include "player_character.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "udp_network_utility.hpp"
#include "button.hpp"
#include "raster_font.hpp"
#include "frame_rate.hpp"
#include <map>
class InWorld : public BaseScene {
public:
//Public access members
InWorld();
~InWorld();
protected:
//Frame loop
void FrameStart();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
//Event handlers
void QuitEvent();
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//Utilities
int HandlePacket(Packet);
void Disconnect();
void ExitGame();
void HandleDisconnection(Packet&);
void AddPlayer(Packet&);
void RemovePlayer(Packet&);
void UpdatePlayer(Packet&);
void SendState();
//services
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
InformationManager* infoMgr = Singleton<InformationManager>::Get();
//members
RasterFont font;
std::map<int, PlayerCharacter> playerCharacters;
};
#endif
+40
View File
@@ -0,0 +1,40 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef INFORMATIONMANAGER_HPP_
#define INFORMATIONMANAGER_HPP_
class InformationManager {
public:
int SetClientIndex(int i) { return clientIndex = i; }
int GetClientIndex() { return clientIndex; }
void ResetClientIndex() { clientIndex = -1; }
//one player at a time
int SetPlayerIndex(int i) { return playerIndex = i; }
int GetPlayerIndex() { return playerIndex; }
void ResetPlayerIndex() { playerIndex = -1; }
private:
int clientIndex = -1;
int playerIndex = -1;
};
#endif
+234
View File
@@ -0,0 +1,234 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "lobby.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
Lobby::Lobby() {
#ifdef DEBUG
cout << "entering Lobby" << endl;
#endif
refreshButton.Setup(50, 50, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Refresh");
joinButton.Setup(50, 100, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Join");
backButton.Setup(50, 150, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Back");
font.SetSurface(surfaceMgr->Get("font"));
listBox.x = 280;
listBox.y = 50;
listBox.w = GetScreen()->w - listBox.x - 50;
listBox.h = font.GetCharH();
serverList.push_back({"foo",{0,0}});
serverList.push_back({"bar",{0,0}});
serverList.push_back({"foobar",{0,0}});
flushNetworkQueue();
beginQueueThread();
BroadcastNetwork();
}
Lobby::~Lobby() {
#ifdef DEBUG
cout << "leaving Lobby" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void Lobby::FrameStart() {
//
}
void Lobby::Update(double delta) {
while(HandlePacket(popNetworkPacket()));
}
void Lobby::FrameEnd() {
//
}
void Lobby::Render(SDL_Surface* const screen) {
refreshButton.DrawTo(screen);
joinButton.DrawTo(screen);
backButton.DrawTo(screen);
for (int i = 0; i < serverList.size(); i++) {
if (selectedServer == &serverList[i]) {
//draw the highlight box
SDL_Rect r = listBox;
r.y += i * font.GetCharH();
SDL_FillRect(screen, &r, SDL_MapRGB(screen->format, 255, 127, 39));
}
font.DrawStringTo(serverList[i].name, screen, listBox.x, listBox.y + i * font.GetCharH());
}
}
//-------------------------
//Event handlers
//-------------------------
void Lobby::MouseMotion(SDL_MouseMotionEvent const& motion) {
refreshButton.MouseMotion(motion);
joinButton.MouseMotion(motion);
backButton.MouseMotion(motion);
}
void Lobby::MouseButtonDown(SDL_MouseButtonEvent const& button) {
refreshButton.MouseButtonDown(button);
joinButton.MouseButtonDown(button);
backButton.MouseButtonDown(button);
}
void Lobby::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (refreshButton.MouseButtonUp(button) == Button::State::HOVER) {
BroadcastNetwork();
selectedServer = nullptr;
}
else if (joinButton.MouseButtonUp(button) == Button::State::HOVER) {
if (selectedServer) {
ConnectToServer(selectedServer);
selectedServer = nullptr;
}
}
else if (backButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::MAINMENU);
endQueueThread();
selectedServer = nullptr;
}
else if (
//clicked within bounds TODO: make the damn collision system
button.x > listBox.x &&
button.y > listBox.y &&
button.x < listBox.x + listBox.w &&
button.y < listBox.y + (listBox.h * serverList.size())
)
{
//selecting a server
selectedServer = &serverList[(button.y - listBox.y) / listBox.h];
}
else {
//lose focus on a server
selectedServer = nullptr;
}
}
void Lobby::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
SetNextScene(SceneList::MAINMENU);
break;
}
}
void Lobby::KeyUp(SDL_KeyboardEvent const& key) {
//
}
//-------------------------
//Utilities
//-------------------------
int Lobby::HandlePacket(Packet p) {
switch(p.meta.type) {
case Packet::Type::NONE:
//DO NOTHING
return 0;
break;
case Packet::Type::PING:
//quick pong
p.meta.type = Packet::Type::PONG;
netUtil->Send(&p.meta.address, &p, sizeof(Packet));
break;
case Packet::Type::PONG:
//
break;
// case Packet::Type::BROADCAST_REQUEST:
// //
// break;
case Packet::Type::BROADCAST_RESPONSE:
PushServer(p);
break;
// case Packet::Type::JOIN_REQUEST:
// //
// break;
case Packet::Type::JOIN_RESPONSE:
BeginGame(p);
break;
// case Packet::Type::DISCONNECT:
// //
// break;
// case Packet::Type::SYNCHRONIZE:
// //
// break;
// case Packet::Type::PLAYER_NEW:
// //
// break;
// case Packet::Type::PLAYER_DELETE:
// //
// break;
// case Packet::Type::PLAYER_UPDATE:
// //
// break;
default:
throw(runtime_error("Failed to recognize the packet type: " + itos(int(p.meta.type))));
}
return 1;
}
void Lobby::BroadcastNetwork() {
Packet p;
p.meta.type = Packet::Type::BROADCAST_REQUEST;
netUtil->Send("255.255.255.255", configUtil->Int("server.port"), &p, sizeof(Packet));
serverList.clear();
}
void Lobby::PushServer(Packet& bcast) {
ServerEntry entry;
entry.name = bcast.serverInfo.name;
entry.address = bcast.meta.address;
serverList.push_back(entry);
}
void Lobby::ConnectToServer(ServerEntry* server) {
//_attempt_ to connect to a server
if (!server) {
throw(runtime_error("No server received"));
}
Packet p;
p.meta.type = Packet::Type::JOIN_REQUEST;
netUtil->Send(&server->address, reinterpret_cast<void*>(&p), sizeof(Packet));
}
void Lobby::BeginGame(Packet& response) {
//should be downloading the resources here as well
infoMgr->SetClientIndex(response.meta.clientIndex);
netUtil->Bind(&response.meta.address, GAME_CHANNEL);
SetNextScene(SceneList::INWORLD);
}
+89
View File
@@ -0,0 +1,89 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef LOBBY_HPP_
#define LOBBY_HPP_
#include "base_scene.hpp"
#include "utilities.hpp"
#include "defines.hpp"
#include "singleton.hpp"
#include "server_entry.hpp"
#include "packet.hpp"
#include "network_queue.hpp"
#include "information_manager.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "udp_network_utility.hpp"
#include "button.hpp"
#include "raster_font.hpp"
#include <vector>
#include <string>
class Lobby : public BaseScene {
public:
//Public access members
Lobby();
~Lobby();
protected:
//Frame loop
void FrameStart();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
//Event handlers
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//utilities
int HandlePacket(Packet);
void BroadcastNetwork();
void PushServer(Packet&);
void ConnectToServer(ServerEntry*);
void BeginGame(Packet&);
//services
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
InformationManager* infoMgr = Singleton<InformationManager>::Get();
//members
Button refreshButton;
Button joinButton;
Button backButton;
RasterFont font;
SDL_Rect listBox;
std::vector<ServerEntry> serverList;
ServerEntry* selectedServer = nullptr;
};
#endif
+47
View File
@@ -0,0 +1,47 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "client_application.hpp"
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int, char**) {
#ifdef DEBUG
cout << "Beginning program" << endl;
#endif
try {
ClientApplication app;
app.Init();
app.Proc();
app.Quit();
}
catch(exception& e) {
cerr << "Fatal error: " << e.what() << endl;
return 1;
}
#ifdef DEBUG
cout << "Clean exit" << endl;
#endif
return 0;
}
+103
View File
@@ -0,0 +1,103 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "main_menu.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
MainMenu::MainMenu() {
#ifdef DEBUG
cout << "entering MainMenu" << endl;
#endif
startButton.Setup(50, 50, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Start");
optionsButton.Setup(50, 100, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Options");
quitButton.Setup(50, 150, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Quit");
}
MainMenu::~MainMenu() {
#ifdef DEBUG
cout << "leaving MainMenu" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void MainMenu::FrameStart() {
//
}
void MainMenu::Update(double delta) {
//
}
void MainMenu::FrameEnd() {
//
}
void MainMenu::Render(SDL_Surface* const screen) {
startButton.DrawTo(screen);
optionsButton.DrawTo(screen);
quitButton.DrawTo(screen);
}
//-------------------------
//Event handlers
//-------------------------
void MainMenu::MouseMotion(SDL_MouseMotionEvent const& motion) {
startButton.MouseMotion(motion);
optionsButton.MouseMotion(motion);
quitButton.MouseMotion(motion);
}
void MainMenu::MouseButtonDown(SDL_MouseButtonEvent const& button) {
startButton.MouseButtonDown(button);
optionsButton.MouseButtonDown(button);
quitButton.MouseButtonDown(button);
}
void MainMenu::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (startButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::LOBBY);
}
if (optionsButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::OPTIONSCREEN);
}
if (quitButton.MouseButtonUp(button) == Button::State::HOVER) {
QuitEvent();
}
}
void MainMenu::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
QuitEvent();
break;
}
}
+57
View File
@@ -0,0 +1,57 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef MAINMENU_HPP_
#define MAINMENU_HPP_
#include "base_scene.hpp"
#include "singleton.hpp"
#include "surface_manager.hpp"
#include "button.hpp"
class MainMenu : public BaseScene {
public:
/* Public access members */
MainMenu();
~MainMenu();
protected:
/* Frame loop */
void FrameStart();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
/* Event handlers */
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
Button startButton;
Button optionsButton;
Button quitButton;
};
#endif
+39
View File
@@ -0,0 +1,39 @@
#config
LIBDIR=../libs
LOCALLIBS=$(LIBDIR)/out/libCodebase.a $(LIBDIR)/out/libCommon.a
LIB=$(LOCALLIBS) -lSDL_net -lwsock32 -liphlpapi -lmingw32 -lSDLmain -lSDL
INCLUDES=$(LIBDIR)/Codebase $(LIBDIR)/common
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,client)
#targets
all: $(OBJ) $(OUT)
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIB)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
+77
View File
@@ -0,0 +1,77 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "option_screen.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
OptionScreen::OptionScreen() {
#ifdef DEBUG
cout << "entering OptionScreen" << endl;
#endif
backButton.Setup(50, 50, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Back");
}
OptionScreen::~OptionScreen() {
#ifdef DEBUG
cout << "leaving OptionScreen" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void OptionScreen::Render(SDL_Surface* const screen) {
backButton.DrawTo(screen);
}
//-------------------------
//Event handlers
//-------------------------
void OptionScreen::MouseMotion(SDL_MouseMotionEvent const& motion) {
backButton.MouseMotion(motion);
}
void OptionScreen::MouseButtonDown(SDL_MouseButtonEvent const& button) {
backButton.MouseButtonDown(button);
}
void OptionScreen::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (backButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::MAINMENU);
}
}
void OptionScreen::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
SetNextScene(SceneList::MAINMENU);
break;
}
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,26 +19,33 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef MAPGENERATOR_HPP_
#define MAPGENERATOR_HPP_
#ifndef OPTIONSCREEN_HPP_
#define OPTIONSCREEN_HPP_
#include "simple_rng.hpp"
#include "base_scene.hpp"
#include "singleton.hpp"
#include "vector2.hpp"
#include "surface_manager.hpp"
#include "button.hpp"
class MapGenerator {
class OptionScreen : public BaseScene {
public:
MapGenerator() = default;
~MapGenerator() = default;
/* Public access members */
OptionScreen();
~OptionScreen();
Vector2 RawNoise(Vector2 const&);
double Influence(Vector2 const& gridPoint, Vector2 const& queryPoint, double width, double height);
double ScaledNoise(double x, double y, double width, double height);
double ScaledOctave(double x, double y, double width, double height, double octave);
double GetPixel(double x, double y, double width, double height, double octave);
protected:
/* Frame loop */
void Render(SDL_Surface* const);
private:
SimpleRNG rng;
/* Event handlers */
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
Button backButton;
};
#endif
#endif
+114
View File
@@ -0,0 +1,114 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "player_character.hpp"
void PlayerCharacter::Update(double delta) {
if (limitSpeed) {
constexpr double d = 1.0/sqrt(2);
position += motion * delta * d;
}
else {
position += motion * delta;
}
sprite.Update(delta);
}
void PlayerCharacter::MoveDirection(CardinalDirection cd) {
//shift the movement in this direction
switch(cd) {
case CardinalDirection::NORTH:
if (motion.y >= 0) {
motion.y -= WALKING_SPEED;
}
break;
case CardinalDirection::SOUTH:
if (motion.y <= 0) {
motion.y += WALKING_SPEED;
}
break;
case CardinalDirection::WEST:
if (motion.x >= 0) {
motion.x -= WALKING_SPEED;
}
break;
case CardinalDirection::EAST:
if (motion.x <= 0) {
motion.x += WALKING_SPEED;
}
break;
}
//face the correct direction
FaceDirection();
}
void PlayerCharacter::FaceDirection(CardinalDirection cd) {
switch(cd) {
case CardinalDirection::NORTH:
sprite.SetCurrentStrip(1);
break;
case CardinalDirection::SOUTH:
sprite.SetCurrentStrip(0);
break;
case CardinalDirection::WEST:
sprite.SetCurrentStrip(2);
break;
case CardinalDirection::EAST:
sprite.SetCurrentStrip(3);
break;
}
}
void PlayerCharacter::FaceDirection() {
//base the direction on the character's movement
if (motion.y < 0) {
FaceDirection(CardinalDirection::NORTH);
}
if (motion.y > 0) {
FaceDirection(CardinalDirection::SOUTH);
}
if (motion.x < 0) {
FaceDirection(CardinalDirection::WEST);
}
if (motion.x > 0) {
FaceDirection(CardinalDirection::EAST);
}
CheckSpeed();
}
void PlayerCharacter::CheckSpeed() {
//diagonal
if (motion.x != 0 && motion.y != 0) {
sprite.SetInterval(0.1);
limitSpeed = true;
}
//cardinal
else if (motion != 0) {
sprite.SetInterval(0.1);
limitSpeed = false;
}
//not moving
else {
sprite.SetInterval(0);
sprite.SetCurrentFrame(0);
limitSpeed = false;
}
}
+63
View File
@@ -0,0 +1,63 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef PLAYERCHARACTER_HPP_
#define PLAYERCHARACTER_HPP_
#include "vector2.hpp"
#include "sprite_sheet.hpp"
#include "defines.hpp"
class PlayerCharacter {
public:
PlayerCharacter() = default;
~PlayerCharacter() = default;
void Update(double delta);
void MoveDirection(CardinalDirection);
void FaceDirection(CardinalDirection);
void FaceDirection();
void DrawTo(SDL_Surface* const dest) { sprite.DrawTo(dest, position.x, position.y); }
//accessors and mutators
Vector2 SetPosition(Vector2 v) { return position = v; }
Vector2 ShiftPosition(Vector2 v) { return position += v; }
Vector2 GetPosition() { return position; }
Vector2 SetMotion(Vector2 v) { return motion = v; }
Vector2 ShiftMotion(Vector2 v) { return motion += v; }
Vector2 GetMotion() { return motion; }
SpriteSheet* GetSprite() { return &sprite; }
private:
void CheckSpeed();
Vector2 position;
Vector2 motion;
SpriteSheet sprite;
//for moving diagonal
bool limitSpeed = false;
};
#endif
+40
View File
@@ -0,0 +1,40 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SCENELIST_HPP_
#define SCENELIST_HPP_
enum class SceneList {
//these are reserved
QUIT,
CONTINUE,
FIRST,
//custom indexes
INCOMBAT,
INWORLD,
LOBBY,
MAINMENU,
OPTIONSCREEN,
SPLASHSCREEN,
};
#endif
+86
View File
@@ -0,0 +1,86 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "splash_screen.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
SplashScreen::SplashScreen() {
#ifdef DEBUG
cout << "entering SplashScreen" << endl;
#endif
logo.SetSurface(surfaceMgr->Load("splash-logo", configUtil->String("logos") + "/krstudios.bmp"));
}
SplashScreen::~SplashScreen() {
surfaceMgr->Free("splash-logo");
#ifdef DEBUG
cout << "leaving SplashScreen" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void SplashScreen::RunFrame(double delta) {
HandleEvents();
if (!loaded) {
//never repeat this
loaded = true;
//quick draw
RenderFrame();
LoadResources();
}
if (std::chrono::steady_clock::now() - start > std::chrono::duration<int>(1)) {
SetNextScene(SceneList::MAINMENU);
}
}
void SplashScreen::RenderFrame() {
SDL_FillRect(GetScreen(), 0, 0);
int x = (GetScreen()->w - logo.GetClipW()) / 2;
int y = (GetScreen()->h - logo.GetClipH()) / 2;
logo.DrawTo(GetScreen(), x, y);
SDL_Flip(GetScreen());
}
void SplashScreen::LoadResources() {
//standard
surfaceMgr->Load("font", configUtil->String("fonts") + "/pokemon_dark_font.bmp");
surfaceMgr->Load("button", configUtil->String("interface") + "/button.bmp");
//debugging
surfaceMgr->Load("elliot", configUtil->String("sprites") + "/elliot2.bmp");
surfaceMgr->Load("coa", configUtil->String("sprites") + "/coa2.bmp");
surfaceMgr->Load("flower", configUtil->String("sprites") + "/aniflower.bmp");
surfaceMgr->Load("terrain", configUtil->String("tilesets") + "/terrain.bmp");
//TODO
}
+53
View File
@@ -0,0 +1,53 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SPLASHSCREEN_HPP_
#define SPLASHSCREEN_HPP_
#include "base_scene.hpp"
#include "singleton.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "image.hpp"
#include <chrono>
class SplashScreen : public BaseScene {
public:
/* Public access members */
SplashScreen();
~SplashScreen();
protected:
/* Frame loop */
void RunFrame(double delta);
void RenderFrame();
void LoadResources();
bool loaded = false;
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
Image logo;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
};
#endif
+139
View File
@@ -0,0 +1,139 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "base_scene.hpp"
#include <stdexcept>
//-------------------------
//Static declarations
//-------------------------
SDL_Surface* BaseScene::screen = nullptr;
//-------------------------
//Public access members
//-------------------------
BaseScene::BaseScene() {
nextScene = SceneList::CONTINUE;
}
BaseScene::~BaseScene() {
//
}
//-------------------------
//Program control
//-------------------------
SDL_Surface* BaseScene::SetScreen(int w, int h, int bpp, Uint32 flags) {
if (!bpp) {
bpp = SDL_GetVideoInfo()->vfmt->BitsPerPixel;
}
screen = SDL_SetVideoMode(w, h, bpp, flags);
if (!screen) {
throw(std::runtime_error("Failed to create the screen surface"));
}
return screen;
}
SDL_Surface* BaseScene::GetScreen() {
return screen;
}
SceneList BaseScene::SetNextScene(SceneList sceneIndex) {
return nextScene = sceneIndex;
}
SceneList BaseScene::GetNextScene() const {
return nextScene;
}
//-------------------------
//Frame loop
//-------------------------
void BaseScene::RunFrame(double delta) {
FrameStart();
HandleEvents();
Update(delta);
FrameEnd();
}
void BaseScene::RenderFrame() {
SDL_FillRect(screen, 0, 0);
Render(screen);
SDL_Flip(screen);
}
//-------------------------
//Event handlers
//-------------------------
void BaseScene::HandleEvents() {
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT:
QuitEvent();
break;
case SDL_VIDEORESIZE:
SetScreen(event.resize.w, event.resize.h, 0, screen->flags);
break;
case SDL_MOUSEMOTION:
MouseMotion(event.motion);
break;
case SDL_MOUSEBUTTONDOWN:
MouseButtonDown(event.button);
break;
case SDL_MOUSEBUTTONUP:
MouseButtonUp(event.button);
break;
case SDL_KEYDOWN:
KeyDown(event.key);
break;
case SDL_KEYUP:
KeyUp(event.key);
break;
#ifdef USE_EVENT_JOYSTICK
//TODO: joystick/gamepad support
#endif
#ifdef USE_EVENT_UNKNOWN
default:
UnknownEvent(event);
break;
#endif
}//switch
}//while
}
+74
View File
@@ -0,0 +1,74 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef BASESCENE_HPP_
#define BASESCENE_HPP_
#include "scene_list.hpp"
#include "SDL/SDL.h"
class BaseScene {
public:
/* Public access members */
BaseScene();
virtual ~BaseScene();
/* Program control */
static SDL_Surface* SetScreen(int w, int h, int bpp = 0, Uint32 flags = SDL_HWSURFACE|SDL_DOUBLEBUF);
static SDL_Surface* GetScreen();
SceneList SetNextScene(SceneList sceneIndex);
SceneList GetNextScene() const;
/* Frame loop */
virtual void RunFrame(double delta);
virtual void RenderFrame();
protected:
virtual void FrameStart() {}
virtual void HandleEvents();
virtual void Update(double delta) {}
virtual void FrameEnd() {}
virtual void Render(SDL_Surface* const screen) {}
/* Event handlers */
virtual void QuitEvent() { SetNextScene(SceneList::QUIT); }
virtual void MouseMotion(SDL_MouseMotionEvent const&) {}
virtual void MouseButtonDown(SDL_MouseButtonEvent const&) {}
virtual void MouseButtonUp(SDL_MouseButtonEvent const&) {}
virtual void KeyDown(SDL_KeyboardEvent const&) {}
virtual void KeyUp(SDL_KeyboardEvent const&) {}
#ifdef USE_EVENT_JOYSTICK
//TODO: joystick/gamepad support
#endif
#ifdef USE_EVENT_UNKNOWN
virtual void UnknownEvent(SDL_Event const&) {}
#endif
private:
static SDL_Surface* screen;
SceneList nextScene;
};
#endif
@@ -1,11 +1,11 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial Applications, and to alter it and redistribute it
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
@@ -19,38 +19,44 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "application.hpp"
#include "editor_application.hpp"
#include <stdexcept>
#include <chrono>
#include <sstream>
//-------------------------
//Scene headers
//-------------------------
//Add the custom scene headers here
#include "shell_scene.hpp"
#include "map_editor.hpp"
//-------------------------
//Public access members
//-------------------------
void Application::Init(int argc, char** argv) {
//initialize SDL
if (SDL_Init(SDL_INIT_VIDEO)) {
throw(std::runtime_error("Failed to initialize SDL"));
}
BaseScene::SetScreen(800, 600, 0, SDL_HWSURFACE|SDL_DOUBLEBUF);
EditorApplication::EditorApplication() {
//
}
void Application::Proc() {
EditorApplication::~EditorApplication() {
UnloadScene();
}
void EditorApplication::Init() {
if (SDL_Init(SDL_INIT_VIDEO))
throw(std::runtime_error("Failed to initialize SDL"));
BaseScene::SetScreen(800, 600);
}
void EditorApplication::Proc() {
LoadScene(SceneList::FIRST);
//prepare the time system
typedef std::chrono::steady_clock Clock;
typedef std::chrono::high_resolution_clock Clock;
std::chrono::duration<int, std::milli> delta(16);
Clock::duration delta(16 * Clock::duration::period::den / std::milli::den);
Clock::time_point simTime = Clock::now();
Clock::time_point realTime;
@@ -68,18 +74,22 @@ void Application::Proc() {
//simulate game time
while (simTime < realTime) {
//call each user defined function
activeScene->RunFrame(double(delta.count()) / std::chrono::duration<int, std::milli>::period::den);
activeScene->RunFrame(double(delta.count()) / Clock::duration::period::den);
simTime += delta;
}
//draw the game to the screen
activeScene->RenderFrame();
//give the computer a break
SDL_Delay(10);
}
UnloadScene();
}
void Application::Quit() {
void EditorApplication::Quit() {
UnloadScene();
SDL_Quit();
}
@@ -87,24 +97,22 @@ void Application::Quit() {
//Private access members
//-------------------------
void Application::LoadScene(SceneList sceneIndex) {
void EditorApplication::LoadScene(SceneList sceneIndex) {
UnloadScene();
switch(sceneIndex) {
//add scene creation calls here
case SceneList::FIRST:
case SceneList::SHELL:
activeScene = new ShellScene();
case SceneList::MAPEDITOR:
activeScene = new MapEditor();
break;
default: {
std::ostringstream msg;
msg << "Failed to recognize the scene index: ";
msg << sceneIndex;
throw(std::logic_error(msg.str()));
}
default:
throw(std::logic_error("Failed to recognize the scene index"));
}
}
void Application::UnloadScene() {
void EditorApplication::UnloadScene() {
delete activeScene;
activeScene = nullptr;
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,23 +19,28 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef APPLICATION_HPP_
#define APPLICATION_HPP_
#ifndef EDITORAPPLICATION_HPP_
#define EDITORAPPLICATION_HPP_
#include "scene_list.hpp"
#include "base_scene.hpp"
class Application {
public:
Application() = default;
~Application() = default;
#include "SDL/SDL.h"
void Init(int argc, char** argv);
class EditorApplication {
public:
/* Public access members */
EditorApplication();
~EditorApplication();
void Init();
void Proc();
void Quit();
EditorApplication(EditorApplication const&) = delete;
EditorApplication(EditorApplication const&&) = delete;
private:
//Private access members
/* Private access members */
void LoadScene(SceneList sceneIndex);
void UnloadScene();
+47
View File
@@ -0,0 +1,47 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "editor_application.hpp"
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int, char**) {
#ifdef DEBUG
cout << "Beginning program" << endl;
#endif
try {
EditorApplication app;
app.Init();
app.Proc();
app.Quit();
}
catch(exception& e) {
cerr << "Fatal error: " << e.what() << endl;
return 1;
}
#ifdef DEBUG
cout << "Clean exit" << endl;
#endif
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#config
LIBDIR=../libs
LOCALLIBS=$(LIBDIR)/out/libCodebase.a $(LIBDIR)/out/libCommon.a
LIB=$(LOCALLIBS) -lmingw32 -lSDLmain -lSDL
INCLUDES=$(LIBDIR)/Codebase $(LIBDIR)/common
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,editor)
#targets
all: $(OBJ) $(OUT)
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIB)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
+82
View File
@@ -0,0 +1,82 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "map_editor.hpp"
//-------------------------
//Public access members
//-------------------------
MapEditor::MapEditor() {
//
}
MapEditor::~MapEditor() {
//
}
//-------------------------
//Frame loop
//-------------------------
void MapEditor::FrameStart() {
//
}
void MapEditor::Update(double delta) {
//
}
void MapEditor::FrameEnd() {
//
}
void MapEditor::Render(SDL_Surface* const screen) {
//
}
//-------------------------
//Event handlers
//-------------------------
void MapEditor::MouseMotion(SDL_MouseMotionEvent const& motion) {
//
}
void MapEditor::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//
}
void MapEditor::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//
}
void MapEditor::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
QuitEvent();
break;
}
}
void MapEditor::KeyUp(SDL_KeyboardEvent const& key) {
//
}
+6 -14
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,20 +19,16 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SHELLSCENE_HPP_
#define SHELLSCENE_HPP_
#ifndef MAPEDITOR_HPP_
#define MAPEDITOR_HPP_
#include "base_scene.hpp"
#include "map_generator.hpp"
#include "image.hpp"
class ShellScene : public BaseScene {
class MapEditor : public BaseScene {
public:
//Public access members
ShellScene();
~ShellScene();
MapEditor();
~MapEditor();
protected:
//Frame loop
@@ -47,10 +43,6 @@ protected:
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//members
MapGenerator generator;
Image image;
};
#endif
+3 -3
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -22,14 +22,14 @@
#ifndef SCENELIST_HPP_
#define SCENELIST_HPP_
enum SceneList {
enum class SceneList {
//these are reserved
QUIT,
CONTINUE,
FIRST,
//custom indexes
SHELL,
MAPEDITOR,
};
#endif
+101
View File
@@ -0,0 +1,101 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "button.hpp"
#include <stdexcept>
Button::Button(Sint16 i, Sint16 j, SDL_Surface* imageSurface, SDL_Surface* fontSurface, std::string s) {
Setup(i, j, imageSurface, fontSurface, s);
}
void Button::Setup(Sint16 i, Sint16 j, SDL_Surface* imageSurface, SDL_Surface* fontSurface, std::string s) {
x = i;
y = j;
SetSurfaces(imageSurface, fontSurface);
SetText(s);
}
Button::State Button::MouseMotion(SDL_MouseMotionEvent const& motion) {
if (motion.state & SDL_BUTTON_LMASK) {
return CalcState(motion.x, motion.y, true);
}
else {
return CalcState(motion.x, motion.y, false);
}
return state;
}
Button::State Button::MouseButtonDown(SDL_MouseButtonEvent const& button) {
if (button.button == SDL_BUTTON_LEFT) {
return CalcState(button.x, button.y, true);
}
return state;
}
Button::State Button::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (button.button == SDL_BUTTON_LEFT) {
return CalcState(button.x, button.y, false);
}
return state;
}
void Button::DrawTo(SDL_Surface* const dest) {
image.DrawTo(dest, x, y);
font.DrawStringTo(text, dest, textX + x, textY + y);
}
void Button::SetSurfaces(SDL_Surface* imageSurface, SDL_Surface* fontSurface) {
//graphical stuff
image.SetSurface(imageSurface);
image.SetClipH(image.GetClipH() / 3); //3 phases
font.SetSurface(fontSurface);
//reset textX & textY
SetText(text);
}
std::string Button::SetText(std::string s) {
//one line
text = s;
textX = (image.GetClipW() / 2) - (font.GetCharW() * text.size() / 2);
textY = (image.GetClipH() / 2) - (font.GetCharH() / 2);
return text;
}
Button::State Button::CalcState(Sint16 i, Sint16 j, bool leftPressed) {
if (i < x || i > (x + image.GetClipW()) ||
j < y || j > (y + image.GetClipH())
) {
image.SetClipY(0);
return state = State::NORMAL;
}
if (leftPressed) {
image.SetClipY(image.GetClipH()*2);
return state = State::PRESSED;
}
else {
image.SetClipY(image.GetClipH());
return state = State::HOVER;
}
}
+82
View File
@@ -0,0 +1,82 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef BUTTON_HPP_
#define BUTTON_HPP_
#include "image.hpp"
#include "raster_font.hpp"
#include <string>
//3-phases, no toggle, centred text
class Button {
public:
enum class State {
NORMAL, HOVER, PRESSED
};
Button() = default;
Button(Sint16 x, Sint16 y, SDL_Surface* imageSurface, SDL_Surface* fontSurface, std::string text = "");
void Setup(Sint16 x, Sint16 y, SDL_Surface* imageSurface, SDL_Surface* fontSurface, std::string text = "");
//return the current state
State MouseMotion(SDL_MouseMotionEvent const&);
State MouseButtonDown(SDL_MouseButtonEvent const&);
State MouseButtonUp(SDL_MouseButtonEvent const&);
State GetState() const {
return state;
}
//yet another draw function
void DrawTo(SDL_Surface* const);
//simple accessors and mutators
Sint16 SetX(Sint16 i) { return x = i; }
Sint16 SetY(Sint16 i) { return y = i; }
Sint16 GetX() const { return x; }
Sint16 GetY() const { return y; }
void SetSurfaces(SDL_Surface* image, SDL_Surface* font);
std::string SetText(std::string s);
std::string GetText() const { return text; }
//raw access, be careful
Image* GetImage() { return &image; }
RasterFont* GetFont() { return &font; }
//debug
Sint16 GetTextX() const { return textX; }
Sint16 GetTextY() const { return textY; }
private:
State CalcState(Sint16 x, Sint16 y, bool leftPressed);
Sint16 x = 0, y = 0;
Sint16 textX = 0, textY = 0; //prevent recalc every loop
Image image;
RasterFont font;
State state = State::NORMAL;
std::string text;
};
#endif
+76
View File
@@ -0,0 +1,76 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "config_utility.hpp"
#include <stdexcept>
#include <fstream>
using namespace std;
void ConfigUtility::Load(string fname) {
ifstream is(fname);
if (!is.is_open()) {
throw(runtime_error("Failed to open config file"));
}
string key, val;
for (;;) { //forever
//eat whitespace
while(isspace(is.peek()))
is.ignore();
//end of file
if (is.eof())
break;
//skip comment lines
if (is.peek() == '#') {
while(is.peek() != '\n' && !is.eof()) {
is.ignore();
}
continue;
}
//read in the pair
getline(is, key,'=');
getline(is, val);
//trim the strings at the start & end
while(key.size() && isspace(*key.begin())) key.erase(0, 1);
while(val.size() && isspace(*val.begin())) val.erase(0, 1);
while(key.size() && isspace(*(key.end()-1))) key.erase(key.end() - 1);
while(val.size() && isspace(*(val.end()-1))) val.erase(val.end() - 1);
//allow empty/wiped values
if (key.size() == 0) {
continue;
}
//save the pair
table[key] = val;
}
is.close();
}
+68
View File
@@ -0,0 +1,68 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CONFIGUTILITY_HPP_
#define CONFIGUTILITY_HPP_
#include <map>
#include <string>
#include <cstdlib>
class ConfigUtility {
public:
ConfigUtility() {}
ConfigUtility(std::string s) { Load(s); }
void Load(std::string fname);
std::string String(std::string s) {
return table[s];
}
const char* CString(std::string s) {
return table[s].c_str();
}
int Integer(std::string s) {
return atoi(table[s].c_str());
}
double Double(std::string s) {
return atof(table[s].c_str());
}
bool Boolean(std::string s) {
return table[s] == "true";
}
std::string& operator[](std::string s) {
return table[s];
}
int Int(std::string s) {
return Integer(s);
}
int Bool(std::string s) {
return Boolean(s);
}
std::map<std::string, std::string>* GetMap() {
return &table;
}
private:
std::map<std::string, std::string> table;
};
#endif
+44
View File
@@ -0,0 +1,44 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "frame_rate.hpp"
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
static int frameCount = 0;
static int lastFrameRate = 0;
static Clock::time_point tick = Clock::now();
int ClockFrameRate() {
frameCount++;
if (Clock::now() - tick >= std::chrono::duration<int>(1)) {
lastFrameRate = frameCount;
frameCount = 0;
tick = Clock::now();
}
return lastFrameRate;
}
int GetFrameRate() {
return lastFrameRate;
}
+28
View File
@@ -0,0 +1,28 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef FRAMERATE_HPP_
#define FRAMERATE_HPP_
int ClockFrameRate();
int GetFrameRate();
#endif
+26 -17
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,27 +19,36 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "maths.hpp"
#include "image.hpp"
double curve(double x) {
return 3.0 * pow(x, 2.0) - 2.0 * pow(x, 3.0);
Image::Image(SDL_Surface* p) {
SetSurface(p);
}
double snap(double x, double base) {
//snap to a grid (floating point version)
return floor(x / base) * base;
Image::Image(SDL_Surface* p, SDL_Rect r) {
SetSurface(p, r);
}
int snap(int x, int base) {
//snap to a grid (integer devision version)
if (x < 0) {
++x;
return x / base * base - base;
SDL_Surface* Image::SetSurface(SDL_Surface* p) {
if (!(surface = p)) {
clip = {0, 0, 0, 0};
}
return x / base * base;
else {
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
}
return surface;
}
double scalarProduct(Vector2 lhs, Vector2 rhs) {
//the dot product
return lhs.x * rhs.x + lhs.y * rhs.y;
}
SDL_Surface* Image::SetSurface(SDL_Surface* const p, SDL_Rect r) {
surface = p;
clip = r;
return surface;
}
void Image::DrawTo(SDL_Surface* dest, Sint16 x, Sint16 y) {
if (!surface) {
return;
}
SDL_Rect sclip = clip, dclip = {x,y};
SDL_BlitSurface(surface, &sclip, dest, &dclip);
}
+5 -20
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,26 +23,17 @@
#define IMAGE_HPP_
#include "SDL/SDL.h"
#include <string>
class Image {
public:
Image() = default;
Image(Image const& rhs) { *this = rhs; }
Image(Image&& rhs) { *this = std::move(rhs); }
Image(std::string fname) { LoadSurface(fname); }
Image(Uint16 w, Uint16 h) { CreateSurface(w, h); }
Image(SDL_Surface* p) { SetSurface(p); }
~Image() { FreeSurface(); }
Image(SDL_Surface*);
Image(SDL_Surface*, SDL_Rect);
~Image() = default;
Image& operator=(Image const&);
Image& operator=(Image&&);
SDL_Surface* LoadSurface(std::string fname);
SDL_Surface* CreateSurface(Uint16 w, Uint16 h);
SDL_Surface* SetSurface(SDL_Surface*);
SDL_Surface* SetSurface(SDL_Surface*, SDL_Rect);
SDL_Surface* GetSurface() const { return surface; }
void FreeSurface();
void DrawTo(SDL_Surface* const, Sint16 x, Sint16 y);
@@ -59,15 +50,9 @@ public:
Sint16 GetClipY() const { return clip.y; }
Uint16 GetClipW() const { return clip.w; }
Uint16 GetClipH() const { return clip.h; }
bool GetLocal() const { return local; }
void SetTransparentColor(Uint8 r, Uint8 g, Uint8 b);
void ClearTransparentColor();
protected:
SDL_Surface* surface = nullptr;
SDL_Rect clip = {0, 0, 0, 0};
bool local = false;
};
#endif
+9 -7
View File
@@ -1,18 +1,20 @@
#config
INCLUDES+=. ../utils
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
LIBDIR=..
LOCALLIBS=
LIB=
INCLUDES=
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,libCodebase.a)
#targets
all: $(OBJ) $(OUT)
+49
View File
@@ -0,0 +1,49 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "raster_font.hpp"
#include <stdexcept>
RasterFont::RasterFont(SDL_Surface* p) {
SetSurface(p);
}
void RasterFont::DrawStringTo(std::string s, SDL_Surface* const dest, Sint16 x, Sint16 y) {
if (!image.GetSurface()) {
throw(std::runtime_error("RasterFont not loaded"));
}
const Uint16 w = image.GetClipW();
const Uint16 h = image.GetClipH();
for (int i = 0; i < s.size(); i++) {
image.SetClipX(s[i] % w * w);
image.SetClipY(s[i] / h * h);
image.DrawTo(dest, x + i * w, y);
}
}
SDL_Surface* RasterFont::SetSurface(SDL_Surface* p) {
if (image.SetSurface(p)) {
image.SetClipW(image.GetSurface()->w/16);
image.SetClipH(image.GetSurface()->h/16);
}
return image.GetSurface();
}
+46
View File
@@ -0,0 +1,46 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef RASTERFONT_HPP_
#define RASTERFONT_HPP_
#include "image.hpp"
#include <string>
class RasterFont {
public:
RasterFont() = default;
RasterFont(SDL_Surface* p);
~RasterFont() = default;
void DrawStringTo(std::string, SDL_Surface* const, Sint16 x, Sint16 y);
//Accessors and Mutators
SDL_Surface* SetSurface(SDL_Surface*);
SDL_Surface* GetSurface() const { return image.GetSurface(); }
Uint16 GetCharW() { return image.GetClipW(); }
Uint16 GetCharH() { return image.GetClipH(); }
private:
Image image;
};
#endif
+44
View File
@@ -0,0 +1,44 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "sprite_sheet.hpp"
SpriteSheet::SpriteSheet(SDL_Surface* s, Uint16 w, Uint16 h) {
SetSurface(s, w, h);
}
void SpriteSheet::Update(double delta) {
if (interval && (ticks += delta) >= interval) {
if (++currentFrame >= maxFrames) {
currentFrame = 0;
}
ticks = 0;
}
image.SetClipX(currentFrame * image.GetClipW());
image.SetClipY(currentStrip * image.GetClipH());
}
SDL_Surface* SpriteSheet::SetSurface(SDL_Surface* const s, Uint16 w, Uint16 h) {
image.SetSurface(s, {0, 0, w, h});
currentFrame = 0; maxFrames = image.GetSurface()->w / image.GetClipW();
currentStrip = 0; maxStrips = image.GetSurface()->h / image.GetClipH();
interval = ticks = 0;
}
+66
View File
@@ -0,0 +1,66 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SPRITESHEET_HPP_
#define SPRITESHEET_HPP_
#include "image.hpp"
#include "SDL/SDL.h"
class SpriteSheet {
public:
SpriteSheet() = default;
SpriteSheet(SDL_Surface*, Uint16 w, Uint16 h);
~SpriteSheet() = default;
void Update(double delta);
SDL_Surface* SetSurface(SDL_Surface* const, Uint16 w, Uint16 h);
SDL_Surface* GetSurface() const {
return image.GetSurface();
}
void DrawTo(SDL_Surface* const dest, Sint16 x, Sint16 y) {
image.DrawTo(dest, x, y);
}
//Accessors and Mutators
double SetInterval(double i) { return interval = i; }
double GetInterval() const { return interval; }
int SetCurrentFrame(int i) { return currentFrame = i; }
int SetCurrentStrip(int i) { return currentStrip = i; }
Uint16 GetFrameWidth() const { return image.GetClipW(); }
Uint16 GetFrameHeight() const { return image.GetClipH(); }
int GetCurrentFrame() const { return currentFrame; };
int GetCurrentStrip() const { return currentStrip; };
int GetMaxFrames() const { return maxFrames; }
int GetMaxStrips() const { return maxStrips; }
private:
Image image;
int currentFrame = 0, maxFrames = 0;
int currentStrip = 0, maxStrips = 0;
double interval = 0, ticks = 0;
};
#endif
+85
View File
@@ -0,0 +1,85 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "surface_manager.hpp"
#include <stdexcept>
SurfaceManager::~SurfaceManager() noexcept {
FreeAll();
}
SDL_Surface* SurfaceManager::Load(std::string key, std::string fname) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
throw(std::runtime_error(std::string("Surface already loaded: ") + key + std::string(", ") + fname));
}
return LoadSurface(key, fname);
}
SDL_Surface* SurfaceManager::Reload(std::string key, std::string fname) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
SDL_FreeSurface(it->second);
surfaceMap.erase(it);
}
return LoadSurface(key, fname);
}
SDL_Surface* SurfaceManager::Get(std::string key) {
MapType::iterator it = surfaceMap.find(key);
if (it == surfaceMap.end()) {
throw(std::runtime_error(std::string("Could not find key: ") + key));
}
return it->second;
}
SDL_Surface* SurfaceManager::Set(std::string key, SDL_Surface* ptr) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
throw(std::runtime_error(std::string("Key already exists: ") + key));
}
return surfaceMap[key] = ptr;
}
void SurfaceManager::Free(std::string key) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
SDL_FreeSurface(it->second);
surfaceMap.erase(it);
}
}
void SurfaceManager::FreeAll() {
for (auto it : surfaceMap) {
SDL_FreeSurface(it.second);
}
surfaceMap.clear();
}
SDL_Surface* SurfaceManager::LoadSurface(std::string key, std::string fname) {
SDL_Surface* ptr = SDL_LoadBMP(fname.c_str());
if (!ptr) {
throw(std::runtime_error(std::string("Failed to load file: ") + fname));
}
SDL_SetColorKey(ptr, SDL_SRCCOLORKEY, SDL_MapRGB(ptr->format, 255, 0, 255)); //default
return surfaceMap[key] = ptr;
}
+49
View File
@@ -0,0 +1,49 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SURFACEMANAGER_HPP_
#define SURFACEMANAGER_HPP_
#include "SDL/SDL.h"
#include <map>
#include <string>
class SurfaceManager {
public:
SurfaceManager() = default;
~SurfaceManager() noexcept;
SDL_Surface* Load(std::string key, std::string fname);
SDL_Surface* Reload(std::string key, std::string fname);
SDL_Surface* Get(std::string key);
SDL_Surface* Set(std::string key, SDL_Surface* ptr);
void Free(std::string key);
void FreeAll();
SDL_Surface* operator[](std::string key) { return Get(key); };
private:
SDL_Surface* LoadSurface(std::string key, std::string fname);
typedef std::map<std::string, SDL_Surface*> MapType;
MapType surfaceMap;
};
#endif
+148
View File
@@ -0,0 +1,148 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "udp_network_utility.hpp"
#include <stdexcept>
void UDPNetworkUtility::Open(int port, int packSize) {
if (!(socket = SDLNet_UDP_Open(port))) {
Close();
throw(std::runtime_error("Failed to open a UDP socket"));
}
if (!(packOut = SDLNet_AllocPacket(packSize))) {
Close();
throw(std::runtime_error("Failed to allocate the out packet"));
}
if (!(packIn = SDLNet_AllocPacket(packSize))) {
Close();
throw(std::runtime_error("Failed to allocate the in packet"));
}
}
void UDPNetworkUtility::Close() {
SDLNet_UDP_Close(socket);
SDLNet_FreePacket(packOut);
SDLNet_FreePacket(packIn);
socket = nullptr;
packOut = nullptr;
packIn = nullptr;
}
int UDPNetworkUtility::Bind(const char* ip, int port, int channel) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
return Bind(&add, channel);
}
int UDPNetworkUtility::Bind(IPaddress* add, int channel) {
int ret = SDLNet_UDP_Bind(socket, channel, add);
if (ret == -1) {
throw(std::runtime_error("Failed to bind to a channel"));
}
return ret;
}
void UDPNetworkUtility::Unbind(int channel) {
SDLNet_UDP_Unbind(socket, channel);
}
int UDPNetworkUtility::Send(const char* ip, int port, void* data, int len) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
Send(&add, data, len);
}
int UDPNetworkUtility::Send(IPaddress* add, void* data, int len) {
if (len > packOut->maxlen) {
throw(std::runtime_error("Failed to copy the data into the packet"));
}
memset(packOut->data, 0, packOut->maxlen);
memcpy(packOut->data, data, len);
packOut->len = len;
packOut->address = *add;
int ret = SDLNet_UDP_Send(socket, -1, packOut);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::Send(int channel, void* data, int len) {
if (len > packOut->maxlen) {
throw(std::runtime_error("Failed to copy the data into the packet"));
}
memset(packOut->data, 0, packOut->maxlen);
memcpy(packOut->data, data, len);
packOut->len = len;
int ret = SDLNet_UDP_Send(socket, channel, packOut);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::SendAll(void* data, int len) {
if (len > packOut->maxlen) {
throw(std::runtime_error("Failed to copy the data into the packet"));
}
memset(packOut->data, 0, packOut->maxlen);
memcpy(packOut->data, data, len);
packOut->len = len;
int sent = 0;
//send to all bound channels
for (int i = 0; i < SDLNET_MAX_UDPCHANNELS; i++) {
if (SDLNet_UDP_GetPeerAddress(socket, i)) {
sent += SDLNet_UDP_Send(socket, i, packOut);
}
}
return sent;
}
int UDPNetworkUtility::Receive() {
memset(packIn->data, 0, packIn->maxlen);
int ret = SDLNet_UDP_Recv(socket, packIn);
if (ret < 0) {
throw(std::runtime_error("Unknown network error occured"));
}
return ret;
}
+79
View File
@@ -0,0 +1,79 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef UDPNETWORKUTILITY_HPP_
#define UDPNETWORKUTILITY_HPP_
#include "SDL_net/SDL_net.h"
class UDPNetworkUtility {
public:
UDPNetworkUtility() = default;
~UDPNetworkUtility() = default;
void Open(int port, int packSize);
void Close();
//bind to an available channel
int Bind(const char* ip, int port) {
Bind(ip, port, -1);
}
int Bind(IPaddress* add) {
Bind(add, -1);
}
//bind to certain channel
int Bind(const char* ip, int port, int channel);
int Bind(IPaddress* add, int channel);
void Unbind(int channel);
IPaddress* GetIPAddress(int channel) {
return SDLNet_UDP_GetPeerAddress(socket, channel);
}
int Send(const char* ip, int port, void* data, int len);
int Send(IPaddress* add, void* data, int len);
int Send(int channel, void* data, int len);
int SendAll(void* data, int len);
int Receive();
void* GetOutData() const {
return reinterpret_cast<void*>(packOut->data);
};
void* GetInData() const {
return reinterpret_cast<void*>(packIn->data);
};
UDPpacket* GetOutPacket() const {
return packOut;
}
UDPpacket* GetInPacket() const {
return packIn;
}
UDPsocket GetSocket() const {
return socket;
}
private:
UDPsocket socket = nullptr;
UDPpacket* packOut = nullptr;
UDPpacket* packIn = nullptr;
};
#endif
+25 -47
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -22,78 +22,50 @@
#ifndef VECTOR2_HPP_
#define VECTOR2_HPP_
#include <type_traits>
#include <stdexcept>
#include <cmath>
class Vector2 {
public:
double x, y;
double x = 0, y = 0;
Vector2() = default;
Vector2(double i, double j): x(i), y(j) {};
~Vector2() = default;
Vector2& operator=(Vector2 const&) = default;
Vector2(double i, double j) {
x = i; y = j;
}
double Length() const {
return sqrt(x*x+y*y);
}
double SquaredLength() const {
return x*x+y*y;
}
void Normalize() {
double l = Length();
x /= l;
y /= l;
double operator[](size_t i) {
if (i >= 2)
throw(std::domain_error("Out of range"));
return *(&x+i);
}
//Arithmetic operators
Vector2 operator+(Vector2 v) const {
Vector2 ret;
ret.x = x + v.x;
ret.y = y + v.y;
return ret;
}
Vector2 operator-(Vector2 v) const {
Vector2 ret;
ret.x = x - v.x;
ret.y = y - v.y;
return ret;
}
Vector2 operator*(Vector2 v) const {
Vector2 ret;
ret.x = x * v.x;
ret.y = y * v.y;
return ret;
}
Vector2 operator*(double d) const {
Vector2 ret;
ret.x = x * d;
ret.y = y * d;
return ret;
}
Vector2 operator+(Vector2 v) const { return Vector2(x + v.x, y + v.y); }
Vector2 operator-(Vector2 v) const { return Vector2(x - v.x, y - v.y); }
Vector2 operator*(Vector2 v) const { return Vector2(x * v.x, y * v.y); }
Vector2 operator*(double d) const { return Vector2(x * d, y * d); }
Vector2 operator/(Vector2 v) {
if (!v.x || !v.y)
throw(std::domain_error("Divide by zero"));
Vector2 ret;
ret.x = x / v.x;
ret.y = y / v.y;
return ret;
return Vector2(x / v.x, y / v.y);
}
Vector2 operator/(double d) {
if (!d)
throw(std::domain_error("Divide by zero"));
Vector2 ret;
ret.x = x / d;
ret.y = y / d;
return ret;
return Vector2(x / d, y / d);
}
bool operator==(Vector2 v) { return (x == v.x && y == v.y); }
bool operator!=(Vector2 v) { return (x != v.x || y != v.y); }
//member templates (curry the above operators)
//member templates
template<typename T> Vector2 operator+=(T t) { return *this = *this + t; }
template<typename T> Vector2 operator-=(T t) { return *this = *this - t; }
template<typename T> Vector2 operator*=(T t) { return *this = *this * t; }
@@ -102,7 +74,13 @@ public:
template<typename T> bool operator!=(T t) { return (x != t || y != t); }
};
//This is explicitly a POD
static_assert(std::is_pod<Vector2>::value, "Vector2 is not a POD");
//non-member templates
template<typename T> Vector2 operator+(T t, Vector2 v) { return v + t; }
template<typename T> Vector2 operator-(T t, Vector2 v) { return v - t; }
template<typename T> Vector2 operator*(T t, Vector2 v) { return v * t; }
template<typename T> Vector2 operator/(T t, Vector2 v) { return v / t; }
template<typename T> bool operator==(T t, Vector2 v) { return v == t; }
template<typename T> bool operator!=(T t, Vector2 v) { return v != t; }
#endif
+452
View File
@@ -0,0 +1,452 @@
/*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
#ifndef _SDL_NET_H
#define _SDL_NET_H
#include "SDL/SDL.h"
#include "SDL/SDL_endian.h"
#include "SDL/SDL_version.h"
#include "SDL/begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL
*/
#define SDL_NET_MAJOR_VERSION 1
#define SDL_NET_MINOR_VERSION 2
#define SDL_NET_PATCHLEVEL 8
/* This macro can be used to fill a version structure with the compile-time
* version of the SDL_net library.
*/
#define SDL_NET_VERSION(X) \
{ \
(X)->major = SDL_NET_MAJOR_VERSION; \
(X)->minor = SDL_NET_MINOR_VERSION; \
(X)->patch = SDL_NET_PATCHLEVEL; \
}
/* This function gets the version of the dynamically linked SDL_net library.
it should NOT be used to fill a version structure, instead you should
use the SDL_NET_VERSION() macro.
*/
extern DECLSPEC const SDL_version * SDLCALL SDLNet_Linked_Version(void);
/* Initialize/Cleanup the network API
SDL must be initialized before calls to functions in this library,
because this library uses utility functions from the SDL library.
*/
extern DECLSPEC int SDLCALL SDLNet_Init(void);
extern DECLSPEC void SDLCALL SDLNet_Quit(void);
/***********************************************************************/
/* IPv4 hostname resolution API */
/***********************************************************************/
typedef struct {
Uint32 host; /* 32-bit IPv4 host address */
Uint16 port; /* 16-bit protocol port */
} IPaddress;
/* Resolve a host name and port to an IP address in network form.
If the function succeeds, it will return 0.
If the host couldn't be resolved, the host portion of the returned
address will be INADDR_NONE, and the function will return -1.
If 'host' is NULL, the resolved host will be set to INADDR_ANY.
*/
#ifndef INADDR_ANY
#define INADDR_ANY 0x00000000
#endif
#ifndef INADDR_NONE
#define INADDR_NONE 0xFFFFFFFF
#endif
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK 0x7f000001
#endif
#ifndef INADDR_BROADCAST
#define INADDR_BROADCAST 0xFFFFFFFF
#endif
extern DECLSPEC int SDLCALL SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port);
/* Resolve an ip address to a host name in canonical form.
If the ip couldn't be resolved, this function returns NULL,
otherwise a pointer to a static buffer containing the hostname
is returned. Note that this function is not thread-safe.
*/
extern DECLSPEC const char * SDLCALL SDLNet_ResolveIP(const IPaddress *ip);
/* Get the addresses of network interfaces on this system.
This returns the number of addresses saved in 'addresses'
*/
extern DECLSPEC int SDLCALL SDLNet_GetLocalAddresses(IPaddress *addresses, int maxcount);
/***********************************************************************/
/* TCP network API */
/***********************************************************************/
typedef struct _TCPsocket *TCPsocket;
/* Open a TCP network socket
If ip.host is INADDR_NONE or INADDR_ANY, this creates a local server
socket on the given port, otherwise a TCP connection to the remote
host and port is attempted. The address passed in should already be
swapped to network byte order (addresses returned from
SDLNet_ResolveHost() are already in the correct form).
The newly created socket is returned, or NULL if there was an error.
*/
extern DECLSPEC TCPsocket SDLCALL SDLNet_TCP_Open(IPaddress *ip);
/* Accept an incoming connection on the given server socket.
The newly created socket is returned, or NULL if there was an error.
*/
extern DECLSPEC TCPsocket SDLCALL SDLNet_TCP_Accept(TCPsocket server);
/* Get the IP address of the remote system associated with the socket.
If the socket is a server socket, this function returns NULL.
*/
extern DECLSPEC IPaddress * SDLCALL SDLNet_TCP_GetPeerAddress(TCPsocket sock);
/* Send 'len' bytes of 'data' over the non-server socket 'sock'
This function returns the actual amount of data sent. If the return value
is less than the amount of data sent, then either the remote connection was
closed, or an unknown socket error occurred.
*/
extern DECLSPEC int SDLCALL SDLNet_TCP_Send(TCPsocket sock, const void *data,
int len);
/* Receive up to 'maxlen' bytes of data over the non-server socket 'sock',
and store them in the buffer pointed to by 'data'.
This function returns the actual amount of data received. If the return
value is less than or equal to zero, then either the remote connection was
closed, or an unknown socket error occurred.
*/
extern DECLSPEC int SDLCALL SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen);
/* Close a TCP network socket */
extern DECLSPEC void SDLCALL SDLNet_TCP_Close(TCPsocket sock);
/***********************************************************************/
/* UDP network API */
/***********************************************************************/
/* The maximum channels on a a UDP socket */
#define SDLNET_MAX_UDPCHANNELS 32
/* The maximum addresses bound to a single UDP socket channel */
#define SDLNET_MAX_UDPADDRESSES 4
typedef struct _UDPsocket *UDPsocket;
typedef struct {
int channel; /* The src/dst channel of the packet */
Uint8 *data; /* The packet data */
int len; /* The length of the packet data */
int maxlen; /* The size of the data buffer */
int status; /* packet status after sending */
IPaddress address; /* The source/dest address of an incoming/outgoing packet */
} UDPpacket;
/* Allocate/resize/free a single UDP packet 'size' bytes long.
The new packet is returned, or NULL if the function ran out of memory.
*/
extern DECLSPEC UDPpacket * SDLCALL SDLNet_AllocPacket(int size);
extern DECLSPEC int SDLCALL SDLNet_ResizePacket(UDPpacket *packet, int newsize);
extern DECLSPEC void SDLCALL SDLNet_FreePacket(UDPpacket *packet);
/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets,
each 'size' bytes long.
A pointer to the first packet in the array is returned, or NULL if the
function ran out of memory.
*/
extern DECLSPEC UDPpacket ** SDLCALL SDLNet_AllocPacketV(int howmany, int size);
extern DECLSPEC void SDLCALL SDLNet_FreePacketV(UDPpacket **packetV);
/* Open a UDP network socket
If 'port' is non-zero, the UDP socket is bound to a local port.
The 'port' should be given in native byte order, but is used
internally in network (big endian) byte order, in addresses, etc.
This allows other systems to send to this socket via a known port.
*/
extern DECLSPEC UDPsocket SDLCALL SDLNet_UDP_Open(Uint16 port);
/* Set the percentage of simulated packet loss for packets sent on the socket.
*/
extern DECLSPEC void SDLCALL SDLNet_UDP_SetPacketLoss(UDPsocket sock, int percent);
/* Bind the address 'address' to the requested channel on the UDP socket.
If the channel is -1, then the first unbound channel will be bound with
the given address as it's primary address.
If the channel is already bound, this new address will be added to the
list of valid source addresses for packets arriving on the channel.
If the channel is not already bound, then the address becomes the primary
address, to which all outbound packets on the channel are sent.
This function returns the channel which was bound, or -1 on error.
*/
extern DECLSPEC int SDLCALL SDLNet_UDP_Bind(UDPsocket sock, int channel, const IPaddress *address);
/* Unbind all addresses from the given channel */
extern DECLSPEC void SDLCALL SDLNet_UDP_Unbind(UDPsocket sock, int channel);
/* Get the primary IP address of the remote system associated with the
socket and channel. If the channel is -1, then the primary IP port
of the UDP socket is returned -- this is only meaningful for sockets
opened with a specific port.
If the channel is not bound and not -1, this function returns NULL.
*/
extern DECLSPEC IPaddress * SDLCALL SDLNet_UDP_GetPeerAddress(UDPsocket sock, int channel);
/* Send a vector of packets to the the channels specified within the packet.
If the channel specified in the packet is -1, the packet will be sent to
the address in the 'src' member of the packet.
Each packet will be updated with the status of the packet after it has
been sent, -1 if the packet send failed.
This function returns the number of packets sent.
*/
extern DECLSPEC int SDLCALL SDLNet_UDP_SendV(UDPsocket sock, UDPpacket **packets, int npackets);
/* Send a single packet to the specified channel.
If the channel specified in the packet is -1, the packet will be sent to
the address in the 'src' member of the packet.
The packet will be updated with the status of the packet after it has
been sent.
This function returns 1 if the packet was sent, or 0 on error.
NOTE:
The maximum size of the packet is limited by the MTU (Maximum Transfer Unit)
of the transport medium. It can be as low as 250 bytes for some PPP links,
and as high as 1500 bytes for ethernet.
*/
extern DECLSPEC int SDLCALL SDLNet_UDP_Send(UDPsocket sock, int channel, UDPpacket *packet);
/* Receive a vector of pending packets from the UDP socket.
The returned packets contain the source address and the channel they arrived
on. If they did not arrive on a bound channel, the the channel will be set
to -1.
The channels are checked in highest to lowest order, so if an address is
bound to multiple channels, the highest channel with the source address
bound will be returned.
This function returns the number of packets read from the network, or -1
on error. This function does not block, so can return 0 packets pending.
*/
extern DECLSPEC int SDLCALL SDLNet_UDP_RecvV(UDPsocket sock, UDPpacket **packets);
/* Receive a single packet from the UDP socket.
The returned packet contains the source address and the channel it arrived
on. If it did not arrive on a bound channel, the the channel will be set
to -1.
The channels are checked in highest to lowest order, so if an address is
bound to multiple channels, the highest channel with the source address
bound will be returned.
This function returns the number of packets read from the network, or -1
on error. This function does not block, so can return 0 packets pending.
*/
extern DECLSPEC int SDLCALL SDLNet_UDP_Recv(UDPsocket sock, UDPpacket *packet);
/* Close a UDP network socket */
extern DECLSPEC void SDLCALL SDLNet_UDP_Close(UDPsocket sock);
/***********************************************************************/
/* Hooks for checking sockets for available data */
/***********************************************************************/
typedef struct _SDLNet_SocketSet *SDLNet_SocketSet;
/* Any network socket can be safely cast to this socket type */
typedef struct _SDLNet_GenericSocket {
int ready;
} *SDLNet_GenericSocket;
/* Allocate a socket set for use with SDLNet_CheckSockets()
This returns a socket set for up to 'maxsockets' sockets, or NULL if
the function ran out of memory.
*/
extern DECLSPEC SDLNet_SocketSet SDLCALL SDLNet_AllocSocketSet(int maxsockets);
/* Add a socket to a set of sockets to be checked for available data */
#define SDLNet_TCP_AddSocket(set, sock) \
SDLNet_AddSocket(set, SDL_reinterpret_cast(SDLNet_GenericSocket, sock))
#define SDLNet_UDP_AddSocket(set, sock) \
SDLNet_AddSocket(set, SDL_reinterpret_cast(SDLNet_GenericSocket, sock))
extern DECLSPEC int SDLCALL SDLNet_AddSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock);
/* Remove a socket from a set of sockets to be checked for available data */
#define SDLNet_TCP_DelSocket(set, sock) \
SDLNet_DelSocket(set, SDL_reinterpret_cast(SDLNet_GenericSocket, sock))
#define SDLNet_UDP_DelSocket(set, sock) \
SDLNet_DelSocket(set, SDL_reinterpret_cast(SDLNet_GenericSocket, sock))
extern DECLSPEC int SDLCALL SDLNet_DelSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock);
/* This function checks to see if data is available for reading on the
given set of sockets. If 'timeout' is 0, it performs a quick poll,
otherwise the function returns when either data is available for
reading, or the timeout in milliseconds has elapsed, which ever occurs
first. This function returns the number of sockets ready for reading,
or -1 if there was an error with the select() system call.
*/
extern DECLSPEC int SDLCALL SDLNet_CheckSockets(SDLNet_SocketSet set, Uint32 timeout);
/* After calling SDLNet_CheckSockets(), you can use this function on a
socket that was in the socket set, to find out if data is available
for reading.
*/
#define SDLNet_SocketReady(sock) \
((sock != NULL) && SDL_reinterpret_cast(SDLNet_GenericSocket, sock)->ready)
/* Free a set of sockets allocated by SDL_NetAllocSocketSet() */
extern DECLSPEC void SDLCALL SDLNet_FreeSocketSet(SDLNet_SocketSet set);
/***********************************************************************/
/* Platform-independent data conversion functions */
/***********************************************************************/
/* Write a 16/32 bit value to network packet buffer */
extern DECLSPEC void SDLCALL SDLNet_Write16(Uint16 value, void *area);
extern DECLSPEC void SDLCALL SDLNet_Write32(Uint32 value, void *area);
/* Read a 16/32 bit value from network packet buffer */
extern DECLSPEC Uint16 SDLCALL SDLNet_Read16(void *area);
extern DECLSPEC Uint32 SDLCALL SDLNet_Read32(void *area);
/***********************************************************************/
/* Error reporting functions */
/***********************************************************************/
/* We'll use SDL's functions for error reporting */
#define SDLNet_SetError SDL_SetError
#define SDLNet_GetError SDL_GetError
/* I'm eventually going to try to disentangle SDL_net from SDL, thus making
SDL_net an independent X-platform networking toolkit. Not today though....
extern no_parse_DECLSPEC void SDLCALL SDLNet_SetError(const char *fmt, ...);
extern no_parse_DECLSPEC char * SDLCALL SDLNet_GetError(void);
*/
/* Inline macro functions to read/write network data */
/* Warning, some systems have data access alignment restrictions */
#if defined(sparc) || defined(mips)
#define SDL_DATA_ALIGNED 1
#endif
#ifndef SDL_DATA_ALIGNED
#define SDL_DATA_ALIGNED 0
#endif
/* Write a 16 bit value to network packet buffer */
#if !SDL_DATA_ALIGNED
#define SDLNet_Write16(value, areap) \
(*SDL_reinterpret_cast(Uint16 *, areap) = SDL_SwapBE16(value))
#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
#define SDLNet_Write16(value, areap) \
do \
{ \
Uint8 *area = SDL_reinterpret_cast(Uint8 *, areap); \
area[0] = (value >> 8) & 0xFF; \
area[1] = value & 0xFF; \
} while ( 0 )
#else
#define SDLNet_Write16(value, areap) \
do \
{ \
Uint8 *area = SDL_reinterpret_cast(Uint8 *, areap); \
area[1] = (value >> 8) & 0xFF; \
area[0] = value & 0xFF; \
} while ( 0 )
#endif
#endif /* !SDL_DATA_ALIGNED */
/* Write a 32 bit value to network packet buffer */
#if !SDL_DATA_ALIGNED
#define SDLNet_Write32(value, areap) \
*SDL_reinterpret_cast(Uint32 *, areap) = SDL_SwapBE32(value);
#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
#define SDLNet_Write32(value, areap) \
do \
{ \
Uint8 *area = SDL_reinterpret_cast(Uint8 *, areap); \
area[0] = (value >> 24) & 0xFF; \
area[1] = (value >> 16) & 0xFF; \
area[2] = (value >> 8) & 0xFF; \
area[3] = value & 0xFF; \
} while ( 0 )
#else
#define SDLNet_Write32(value, areap) \
do \
{ \
Uint8 *area = SDL_reinterpret_cast(Uint8 *, areap); \
area[3] = (value >> 24) & 0xFF; \
area[2] = (value >> 16) & 0xFF; \
area[1] = (value >> 8) & 0xFF; \
area[0] = value & 0xFF; \
} while ( 0 )
#endif
#endif /* !SDL_DATA_ALIGNED */
/* Read a 16 bit value from network packet buffer */
#if !SDL_DATA_ALIGNED
#define SDLNet_Read16(areap) \
(SDL_SwapBE16(*SDL_reinterpret_cast(Uint16 *, areap)))
#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
#define SDLNet_Read16(areap) \
(((SDL_reinterpret_cast(Uint8 *, areap))[0] << 8) | (SDL_reinterpret_cast(Uint8 *, areap))[1] << 0)
#else
#define SDLNet_Read16(areap) \
(((SDL_reinterpret_cast(Uint8 *, areap))[1] << 8) | (SDL_reinterpret_cast(Uint8 *, areap))[0] << 0)
#endif
#endif /* !SDL_DATA_ALIGNED */
/* Read a 32 bit value from network packet buffer */
#if !SDL_DATA_ALIGNED
#define SDLNet_Read32(areap) \
(SDL_SwapBE32(*SDL_reinterpret_cast(Uint32 *, areap)))
#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
#define SDLNet_Read32(areap) \
(((SDL_reinterpret_cast(Uint8 *, areap))[0] << 24) | ((SDL_reinterpret_cast(Uint8 *, areap))[1] << 16) | \
((SDL_reinterpret_cast(Uint8 *, areap))[2] << 8) | (SDL_reinterpret_cast(Uint8 *, areap))[3] << 0)
#else
#define SDLNet_Read32(areap) \
(((SDL_reinterpret_cast(Uint8 *, areap))[3] << 24) | ((SDL_reinterpret_cast(Uint8 *, areap))[2] << 16) | \
((SDL_reinterpret_cast(Uint8 *, areap))[1] << 8) | (SDL_reinterpret_cast(Uint8 *, areap))[0] << 0)
#endif
#endif /* !SDL_DATA_ALIGNED */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "SDL/close_code.h"
#endif /* _SDL_NET_H */
+269
View File
@@ -0,0 +1,269 @@
/*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
#include <string.h>
#include "SDL/SDL_endian.h"
#include "SDLnetsys.h"
#include "SDL_net.h"
const SDL_version *SDLNet_Linked_Version(void)
{
static SDL_version linked_version;
SDL_NET_VERSION(&linked_version);
return(&linked_version);
}
/* Since the UNIX/Win32/BeOS code is so different from MacOS,
we'll just have two completely different sections here.
*/
static int SDLNet_started = 0;
#ifndef __USE_W32_SOCKETS
#include <signal.h>
#endif
#ifndef __USE_W32_SOCKETS
int SDLNet_GetLastError(void)
{
return errno;
}
void SDLNet_SetLastError(int err)
{
errno = err;
}
#endif
/* Initialize/Cleanup the network API */
int SDLNet_Init(void)
{
if ( !SDLNet_started ) {
#ifdef __USE_W32_SOCKETS
/* Start up the windows networking */
WORD version_wanted = MAKEWORD(1,1);
WSADATA wsaData;
if ( WSAStartup(version_wanted, &wsaData) != 0 ) {
SDLNet_SetError("Couldn't initialize Winsock 1.1\n");
return(-1);
}
#else
/* SIGPIPE is generated when a remote socket is closed */
void (*handler)(int);
handler = signal(SIGPIPE, SIG_IGN);
if ( handler != SIG_DFL ) {
signal(SIGPIPE, handler);
}
#endif
}
++SDLNet_started;
return(0);
}
void SDLNet_Quit(void)
{
if ( SDLNet_started == 0 ) {
return;
}
if ( --SDLNet_started == 0 ) {
#ifdef __USE_W32_SOCKETS
/* Clean up windows networking */
if ( WSACleanup() == SOCKET_ERROR ) {
if ( WSAGetLastError() == WSAEINPROGRESS ) {
#ifndef _WIN32_WCE
WSACancelBlockingCall();
#endif
WSACleanup();
}
}
#else
/* Restore the SIGPIPE handler */
void (*handler)(int);
handler = signal(SIGPIPE, SIG_DFL);
if ( handler != SIG_IGN ) {
signal(SIGPIPE, handler);
}
#endif
}
}
/* Resolve a host name and port to an IP address in network form */
int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port)
{
int retval = 0;
/* Perform the actual host resolution */
if ( host == NULL ) {
address->host = INADDR_ANY;
} else {
address->host = inet_addr(host);
if ( address->host == INADDR_NONE ) {
struct hostent *hp;
hp = gethostbyname(host);
if ( hp ) {
memcpy(&address->host,hp->h_addr,hp->h_length);
} else {
retval = -1;
}
}
}
address->port = SDL_SwapBE16(port);
/* Return the status */
return(retval);
}
/* Resolve an ip address to a host name in canonical form.
If the ip couldn't be resolved, this function returns NULL,
otherwise a pointer to a static buffer containing the hostname
is returned. Note that this function is not thread-safe.
*/
/* Written by Miguel Angel Blanch.
* Main Programmer of Arianne RPG.
* http://come.to/arianne_rpg
*/
const char *SDLNet_ResolveIP(const IPaddress *ip)
{
struct hostent *hp;
struct in_addr in;
hp = gethostbyaddr((const char *)&ip->host, sizeof(ip->host), AF_INET);
if ( hp != NULL ) {
return hp->h_name;
}
in.s_addr = ip->host;
return inet_ntoa(in);
}
int SDLNet_GetLocalAddresses(IPaddress *addresses, int maxcount)
{
int count = 0;
#ifdef SIOCGIFCONF
/* Defined on Mac OS X */
#ifndef _SIZEOF_ADDR_IFREQ
#define _SIZEOF_ADDR_IFREQ sizeof
#endif
SOCKET sock;
struct ifconf conf;
char data[4096];
struct ifreq *ifr;
struct sockaddr_in *sock_addr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if ( sock == INVALID_SOCKET ) {
return 0;
}
conf.ifc_len = sizeof(data);
conf.ifc_buf = (caddr_t) data;
if ( ioctl(sock, SIOCGIFCONF, &conf) < 0 ) {
closesocket(sock);
return 0;
}
ifr = (struct ifreq*)data;
while ((char*)ifr < data+conf.ifc_len) {
if (ifr->ifr_addr.sa_family == AF_INET) {
if (count < maxcount) {
sock_addr = (struct sockaddr_in*)&ifr->ifr_addr;
addresses[count].host = sock_addr->sin_addr.s_addr;
addresses[count].port = sock_addr->sin_port;
}
++count;
}
ifr = (struct ifreq*)((char*)ifr + _SIZEOF_ADDR_IFREQ(*ifr));
}
closesocket(sock);
#elif defined(__WIN32__)
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter;
PIP_ADDR_STRING pAddress;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO *) SDL_malloc(sizeof (IP_ADAPTER_INFO));
if (pAdapterInfo == NULL) {
return 0;
}
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == ERROR_BUFFER_OVERFLOW) {
pAdapterInfo = (IP_ADAPTER_INFO *) SDL_realloc(pAdapterInfo, ulOutBufLen);
if (pAdapterInfo == NULL) {
return 0;
}
dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
}
if (dwRetVal == NO_ERROR) {
for (pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) {
for (pAddress = &pAdapterInfo->IpAddressList; pAddress; pAddress = pAddress->Next) {
if (count < maxcount) {
addresses[count].host = inet_addr(pAddress->IpAddress.String);
addresses[count].port = 0;
}
++count;
}
}
}
SDL_free(pAdapterInfo);
#endif
return count;
}
#if !SDL_DATA_ALIGNED /* function versions for binary compatibility */
/* Write a 16 bit value to network packet buffer */
#undef SDLNet_Write16
void SDLNet_Write16(Uint16 value, void *areap)
{
(*(Uint16 *)(areap) = SDL_SwapBE16(value));
}
/* Write a 32 bit value to network packet buffer */
#undef SDLNet_Write32
void SDLNet_Write32(Uint32 value, void *areap)
{
*(Uint32 *)(areap) = SDL_SwapBE32(value);
}
/* Read a 16 bit value from network packet buffer */
#undef SDLNet_Read16
Uint16 SDLNet_Read16(void *areap)
{
return (SDL_SwapBE16(*(Uint16 *)(areap)));
}
/* Read a 32 bit value from network packet buffer */
#undef SDLNet_Read32
Uint32 SDLNet_Read32(void *areap)
{
return (SDL_SwapBE32(*(Uint32 *)(areap)));
}
#endif /* !SDL_DATA_ALIGNED */
+295
View File
@@ -0,0 +1,295 @@
/*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
#include "SDLnetsys.h"
#include "SDL_net.h"
/* The network API for TCP sockets */
/* Since the UNIX/Win32/BeOS code is so different from MacOS,
we'll just have two completely different sections here.
*/
struct _TCPsocket {
int ready;
SOCKET channel;
IPaddress remoteAddress;
IPaddress localAddress;
int sflag;
};
/* Open a TCP network socket
If 'remote' is NULL, this creates a local server socket on the given port,
otherwise a TCP connection to the remote host and port is attempted.
The newly created socket is returned, or NULL if there was an error.
*/
TCPsocket SDLNet_TCP_Open(IPaddress *ip)
{
TCPsocket sock;
struct sockaddr_in sock_addr;
/* Allocate a TCP socket structure */
sock = (TCPsocket)malloc(sizeof(*sock));
if ( sock == NULL ) {
SDLNet_SetError("Out of memory");
goto error_return;
}
/* Open the socket */
sock->channel = socket(AF_INET, SOCK_STREAM, 0);
if ( sock->channel == INVALID_SOCKET ) {
SDLNet_SetError("Couldn't create socket");
goto error_return;
}
/* Connect to remote, or bind locally, as appropriate */
if ( (ip->host != INADDR_NONE) && (ip->host != INADDR_ANY) ) {
// ######### Connecting to remote
memset(&sock_addr, 0, sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = ip->host;
sock_addr.sin_port = ip->port;
/* Connect to the remote host */
if ( connect(sock->channel, (struct sockaddr *)&sock_addr,
sizeof(sock_addr)) == SOCKET_ERROR ) {
SDLNet_SetError("Couldn't connect to remote host");
goto error_return;
}
sock->sflag = 0;
} else {
// ########## Binding locally
memset(&sock_addr, 0, sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = INADDR_ANY;
sock_addr.sin_port = ip->port;
/*
* Windows gets bad mojo with SO_REUSEADDR:
* http://www.devolution.com/pipermail/sdl/2005-September/070491.html
* --ryan.
*/
#ifndef WIN32
/* allow local address reuse */
{ int yes = 1;
setsockopt(sock->channel, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
}
#endif
/* Bind the socket for listening */
if ( bind(sock->channel, (struct sockaddr *)&sock_addr,
sizeof(sock_addr)) == SOCKET_ERROR ) {
SDLNet_SetError("Couldn't bind to local port");
goto error_return;
}
if ( listen(sock->channel, 5) == SOCKET_ERROR ) {
SDLNet_SetError("Couldn't listen to local port");
goto error_return;
}
/* Set the socket to non-blocking mode for accept() */
#if defined(__BEOS__) && defined(SO_NONBLOCK)
/* On BeOS r5 there is O_NONBLOCK but it's for files only */
{
long b = 1;
setsockopt(sock->channel, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
}
#elif defined(O_NONBLOCK)
{
fcntl(sock->channel, F_SETFL, O_NONBLOCK);
}
#elif defined(WIN32)
{
unsigned long mode = 1;
ioctlsocket (sock->channel, FIONBIO, &mode);
}
#elif defined(__OS2__)
{
int dontblock = 1;
ioctl(sock->channel, FIONBIO, &dontblock);
}
#else
#warning How do we set non-blocking mode on other operating systems?
#endif
sock->sflag = 1;
}
sock->ready = 0;
#ifdef TCP_NODELAY
/* Set the nodelay TCP option for real-time games */
{ int yes = 1;
setsockopt(sock->channel, IPPROTO_TCP, TCP_NODELAY, (char*)&yes, sizeof(yes));
}
#endif /* TCP_NODELAY */
/* Fill in the channel host address */
sock->remoteAddress.host = sock_addr.sin_addr.s_addr;
sock->remoteAddress.port = sock_addr.sin_port;
/* The socket is ready */
return(sock);
error_return:
SDLNet_TCP_Close(sock);
return(NULL);
}
/* Accept an incoming connection on the given server socket.
The newly created socket is returned, or NULL if there was an error.
*/
TCPsocket SDLNet_TCP_Accept(TCPsocket server)
{
TCPsocket sock;
struct sockaddr_in sock_addr;
socklen_t sock_alen;
/* Only server sockets can accept */
if ( ! server->sflag ) {
SDLNet_SetError("Only server sockets can accept()");
return(NULL);
}
server->ready = 0;
/* Allocate a TCP socket structure */
sock = (TCPsocket)malloc(sizeof(*sock));
if ( sock == NULL ) {
SDLNet_SetError("Out of memory");
goto error_return;
}
/* Accept a new TCP connection on a server socket */
sock_alen = sizeof(sock_addr);
sock->channel = accept(server->channel, (struct sockaddr *)&sock_addr,
&sock_alen);
if ( sock->channel == INVALID_SOCKET ) {
SDLNet_SetError("accept() failed");
goto error_return;
}
#ifdef WIN32
{
/* passing a zero value, socket mode set to block on */
unsigned long mode = 0;
ioctlsocket (sock->channel, FIONBIO, &mode);
}
#elif defined(O_NONBLOCK)
{
int flags = fcntl(sock->channel, F_GETFL, 0);
fcntl(sock->channel, F_SETFL, flags & ~O_NONBLOCK);
}
#endif /* WIN32 */
sock->remoteAddress.host = sock_addr.sin_addr.s_addr;
sock->remoteAddress.port = sock_addr.sin_port;
sock->sflag = 0;
sock->ready = 0;
/* The socket is ready */
return(sock);
error_return:
SDLNet_TCP_Close(sock);
return(NULL);
}
/* Get the IP address of the remote system associated with the socket.
If the socket is a server socket, this function returns NULL.
*/
IPaddress *SDLNet_TCP_GetPeerAddress(TCPsocket sock)
{
if ( sock->sflag ) {
return(NULL);
}
return(&sock->remoteAddress);
}
/* Send 'len' bytes of 'data' over the non-server socket 'sock'
This function returns the actual amount of data sent. If the return value
is less than the amount of data sent, then either the remote connection was
closed, or an unknown socket error occurred.
*/
int SDLNet_TCP_Send(TCPsocket sock, const void *datap, int len)
{
const Uint8 *data = (const Uint8 *)datap; /* For pointer arithmetic */
int sent, left;
/* Server sockets are for accepting connections only */
if ( sock->sflag ) {
SDLNet_SetError("Server sockets cannot send");
return(-1);
}
/* Keep sending data until it's sent or an error occurs */
left = len;
sent = 0;
SDLNet_SetLastError(0);
do {
len = send(sock->channel, (const char *) data, left, 0);
if ( len > 0 ) {
sent += len;
left -= len;
data += len;
}
} while ( (left > 0) && ((len > 0) || (SDLNet_GetLastError() == EINTR)) );
return(sent);
}
/* Receive up to 'maxlen' bytes of data over the non-server socket 'sock',
and store them in the buffer pointed to by 'data'.
This function returns the actual amount of data received. If the return
value is less than or equal to zero, then either the remote connection was
closed, or an unknown socket error occurred.
*/
int SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen)
{
int len;
/* Server sockets are for accepting connections only */
if ( sock->sflag ) {
SDLNet_SetError("Server sockets cannot receive");
return(-1);
}
SDLNet_SetLastError(0);
do {
len = recv(sock->channel, (char *) data, maxlen, 0);
} while ( SDLNet_GetLastError() == EINTR );
sock->ready = 0;
return(len);
}
/* Close a TCP network socket */
void SDLNet_TCP_Close(TCPsocket sock)
{
if ( sock != NULL ) {
if ( sock->channel != INVALID_SOCKET ) {
closesocket(sock->channel);
}
free(sock);
}
}
+528
View File
@@ -0,0 +1,528 @@
/*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
#include "SDLnetsys.h"
#include "SDL_net.h"
#ifdef __WIN32__
#define srandom srand
#define random rand
#endif
struct UDP_channel {
int numbound;
IPaddress address[SDLNET_MAX_UDPADDRESSES];
};
struct _UDPsocket {
int ready;
SOCKET channel;
IPaddress address;
struct UDP_channel binding[SDLNET_MAX_UDPCHANNELS];
/* For debugging purposes */
int packetloss;
};
/* Allocate/free a single UDP packet 'size' bytes long.
The new packet is returned, or NULL if the function ran out of memory.
*/
extern UDPpacket *SDLNet_AllocPacket(int size)
{
UDPpacket *packet;
int error;
error = 1;
packet = (UDPpacket *)malloc(sizeof(*packet));
if ( packet != NULL ) {
packet->maxlen = size;
packet->data = (Uint8 *)malloc(size);
if ( packet->data != NULL ) {
error = 0;
}
}
if ( error ) {
SDLNet_SetError("Out of memory");
SDLNet_FreePacket(packet);
packet = NULL;
}
return(packet);
}
int SDLNet_ResizePacket(UDPpacket *packet, int newsize)
{
Uint8 *newdata;
newdata = (Uint8 *)malloc(newsize);
if ( newdata != NULL ) {
free(packet->data);
packet->data = newdata;
packet->maxlen = newsize;
}
return(packet->maxlen);
}
extern void SDLNet_FreePacket(UDPpacket *packet)
{
if ( packet ) {
if ( packet->data )
free(packet->data);
free(packet);
}
}
/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets,
each 'size' bytes long.
A pointer to the packet array is returned, or NULL if the function ran out
of memory.
*/
UDPpacket **SDLNet_AllocPacketV(int howmany, int size)
{
UDPpacket **packetV;
packetV = (UDPpacket **)malloc((howmany+1)*sizeof(*packetV));
if ( packetV != NULL ) {
int i;
for ( i=0; i<howmany; ++i ) {
packetV[i] = SDLNet_AllocPacket(size);
if ( packetV[i] == NULL ) {
break;
}
}
packetV[i] = NULL;
if ( i != howmany ) {
SDLNet_SetError("Out of memory");
SDLNet_FreePacketV(packetV);
packetV = NULL;
}
}
return(packetV);
}
void SDLNet_FreePacketV(UDPpacket **packetV)
{
if ( packetV ) {
int i;
for ( i=0; packetV[i]; ++i ) {
SDLNet_FreePacket(packetV[i]);
}
free(packetV);
}
}
/* Since the UNIX/Win32/BeOS code is so different from MacOS,
we'll just have two completely different sections here.
*/
/* Open a UDP network socket
If 'port' is non-zero, the UDP socket is bound to a fixed local port.
*/
UDPsocket SDLNet_UDP_Open(Uint16 port)
{
UDPsocket sock;
struct sockaddr_in sock_addr;
socklen_t sock_len;
/* Allocate a UDP socket structure */
sock = (UDPsocket)malloc(sizeof(*sock));
if ( sock == NULL ) {
SDLNet_SetError("Out of memory");
goto error_return;
}
memset(sock, 0, sizeof(*sock));
memset(&sock_addr, 0, sizeof(sock_addr));
/* Open the socket */
sock->channel = socket(AF_INET, SOCK_DGRAM, 0);
if ( sock->channel == INVALID_SOCKET )
{
SDLNet_SetError("Couldn't create socket");
goto error_return;
}
/* Bind locally, if appropriate */
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = INADDR_ANY;
sock_addr.sin_port = SDL_SwapBE16(port);
/* Bind the socket for listening */
if ( bind(sock->channel, (struct sockaddr *)&sock_addr,
sizeof(sock_addr)) == SOCKET_ERROR ) {
SDLNet_SetError("Couldn't bind to local port");
goto error_return;
}
/* Get the bound address and port */
sock_len = sizeof(sock_addr);
if ( getsockname(sock->channel, (struct sockaddr *)&sock_addr, &sock_len) < 0 ) {
perror("getsockname");
SDLNet_SetError("Couldn't get socket address");
goto error_return;
}
/* Fill in the channel host address */
sock->address.host = sock_addr.sin_addr.s_addr;
sock->address.port = sock_addr.sin_port;
#ifdef SO_BROADCAST
/* Allow LAN broadcasts with the socket */
{ int yes = 1;
setsockopt(sock->channel, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes));
}
#endif
#ifdef IP_ADD_MEMBERSHIP
/* Receive LAN multicast packets on 224.0.0.1
This automatically works on Mac OS X, Linux and BSD, but needs
this code on Windows.
*/
/* A good description of multicast can be found here:
http://www.docs.hp.com/en/B2355-90136/ch05s05.html
*/
/* FIXME: Add support for joining arbitrary groups to the API */
{
struct ip_mreq g;
g.imr_multiaddr.s_addr = inet_addr("224.0.0.1");
g.imr_interface.s_addr = INADDR_ANY;
setsockopt(sock->channel, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char*)&g, sizeof(g));
}
#endif
/* The socket is ready */
return(sock);
error_return:
SDLNet_UDP_Close(sock);
return(NULL);
}
void SDLNet_UDP_SetPacketLoss(UDPsocket sock, int percent)
{
/* FIXME: We may want this behavior to be reproducible
but there isn't a portable reentrant random
number generator with good randomness.
*/
srandom(SDL_GetTicks());
if (percent < 0) {
percent = 0;
} else if (percent > 100) {
percent = 100;
}
sock->packetloss = percent;
}
/* Verify that the channel is in the valid range */
static int ValidChannel(int channel)
{
if ( (channel < 0) || (channel >= SDLNET_MAX_UDPCHANNELS) ) {
SDLNet_SetError("Invalid channel");
return(0);
}
return(1);
}
/* Bind the address 'address' to the requested channel on the UDP socket.
If the channel is -1, then the first unbound channel will be bound with
the given address as it's primary address.
If the channel is already bound, this new address will be added to the
list of valid source addresses for packets arriving on the channel.
If the channel is not already bound, then the address becomes the primary
address, to which all outbound packets on the channel are sent.
This function returns the channel which was bound, or -1 on error.
*/
int SDLNet_UDP_Bind(UDPsocket sock, int channel, const IPaddress *address)
{
struct UDP_channel *binding;
if ( sock == NULL ) {
SDLNet_SetError("Passed a NULL socket");
return(-1);
}
if ( channel == -1 ) {
for ( channel=0; channel < SDLNET_MAX_UDPCHANNELS; ++channel ) {
binding = &sock->binding[channel];
if ( binding->numbound < SDLNET_MAX_UDPADDRESSES ) {
break;
}
}
} else {
if ( ! ValidChannel(channel) ) {
return(-1);
}
binding = &sock->binding[channel];
}
if ( binding->numbound == SDLNET_MAX_UDPADDRESSES ) {
SDLNet_SetError("No room for new addresses");
return(-1);
}
binding->address[binding->numbound++] = *address;
return(channel);
}
/* Unbind all addresses from the given channel */
void SDLNet_UDP_Unbind(UDPsocket sock, int channel)
{
if ( (channel >= 0) && (channel < SDLNET_MAX_UDPCHANNELS) ) {
sock->binding[channel].numbound = 0;
}
}
/* Get the primary IP address of the remote system associated with the
socket and channel.
If the channel is not bound, this function returns NULL.
*/
IPaddress *SDLNet_UDP_GetPeerAddress(UDPsocket sock, int channel)
{
IPaddress *address;
address = NULL;
switch (channel) {
case -1:
/* Return the actual address of the socket */
address = &sock->address;
break;
default:
/* Return the address of the bound channel */
if ( ValidChannel(channel) &&
(sock->binding[channel].numbound > 0) ) {
address = &sock->binding[channel].address[0];
}
break;
}
return(address);
}
/* Send a vector of packets to the the channels specified within the packet.
If the channel specified in the packet is -1, the packet will be sent to
the address in the 'src' member of the packet.
Each packet will be updated with the status of the packet after it has
been sent, -1 if the packet send failed.
This function returns the number of packets sent.
*/
int SDLNet_UDP_SendV(UDPsocket sock, UDPpacket **packets, int npackets)
{
int numsent, i, j;
struct UDP_channel *binding;
int status;
int sock_len;
struct sockaddr_in sock_addr;
if ( sock == NULL ) {
SDLNet_SetError("Passed a NULL socket");
return(0);
}
/* Set up the variables to send packets */
sock_len = sizeof(sock_addr);
numsent = 0;
for ( i=0; i<npackets; ++i )
{
/* Simulate packet loss, if desired */
if (sock->packetloss) {
if ((random()%100) <= sock->packetloss) {
packets[i]->status = packets[i]->len;
++numsent;
continue;
}
}
/* if channel is < 0, then use channel specified in sock */
if ( packets[i]->channel < 0 )
{
sock_addr.sin_addr.s_addr = packets[i]->address.host;
sock_addr.sin_port = packets[i]->address.port;
sock_addr.sin_family = AF_INET;
status = sendto(sock->channel,
packets[i]->data, packets[i]->len, 0,
(struct sockaddr *)&sock_addr,sock_len);
if ( status >= 0 )
{
packets[i]->status = status;
++numsent;
}
}
else
{
/* Send to each of the bound addresses on the channel */
#ifdef DEBUG_NET
printf("SDLNet_UDP_SendV sending packet to channel = %d\n", packets[i]->channel );
#endif
binding = &sock->binding[packets[i]->channel];
for ( j=binding->numbound-1; j>=0; --j )
{
sock_addr.sin_addr.s_addr = binding->address[j].host;
sock_addr.sin_port = binding->address[j].port;
sock_addr.sin_family = AF_INET;
status = sendto(sock->channel,
packets[i]->data, packets[i]->len, 0,
(struct sockaddr *)&sock_addr,sock_len);
if ( status >= 0 )
{
packets[i]->status = status;
++numsent;
}
}
}
}
return(numsent);
}
int SDLNet_UDP_Send(UDPsocket sock, int channel, UDPpacket *packet)
{
/* This is silly, but... */
packet->channel = channel;
return(SDLNet_UDP_SendV(sock, &packet, 1));
}
/* Returns true if a socket is has data available for reading right now */
static int SocketReady(SOCKET sock)
{
int retval = 0;
struct timeval tv;
fd_set mask;
/* Check the file descriptors for available data */
do {
SDLNet_SetLastError(0);
/* Set up the mask of file descriptors */
FD_ZERO(&mask);
FD_SET(sock, &mask);
/* Set up the timeout */
tv.tv_sec = 0;
tv.tv_usec = 0;
/* Look! */
retval = select(sock+1, &mask, NULL, NULL, &tv);
} while ( SDLNet_GetLastError() == EINTR );
return(retval == 1);
}
/* Receive a vector of pending packets from the UDP socket.
The returned packets contain the source address and the channel they arrived
on. If they did not arrive on a bound channel, the the channel will be set
to -1.
This function returns the number of packets read from the network, or -1
on error. This function does not block, so can return 0 packets pending.
*/
extern int SDLNet_UDP_RecvV(UDPsocket sock, UDPpacket **packets)
{
int numrecv, i, j;
struct UDP_channel *binding;
socklen_t sock_len;
struct sockaddr_in sock_addr;
if ( sock == NULL ) {
return(0);
}
numrecv = 0;
while ( packets[numrecv] && SocketReady(sock->channel) )
{
UDPpacket *packet;
packet = packets[numrecv];
sock_len = sizeof(sock_addr);
packet->status = recvfrom(sock->channel,
packet->data, packet->maxlen, 0,
(struct sockaddr *)&sock_addr,
&sock_len);
if ( packet->status >= 0 ) {
packet->len = packet->status;
packet->address.host = sock_addr.sin_addr.s_addr;
packet->address.port = sock_addr.sin_port;
packet->channel = -1;
for (i=(SDLNET_MAX_UDPCHANNELS-1); i>=0; --i )
{
binding = &sock->binding[i];
for ( j=binding->numbound-1; j>=0; --j )
{
if ( (packet->address.host == binding->address[j].host) &&
(packet->address.port == binding->address[j].port) )
{
packet->channel = i;
goto foundit; /* break twice */
}
}
}
foundit:
++numrecv;
}
else
{
packet->len = 0;
}
}
sock->ready = 0;
return(numrecv);
}
/* Receive a single packet from the UDP socket.
The returned packet contains the source address and the channel it arrived
on. If it did not arrive on a bound channel, the the channel will be set
to -1.
This function returns the number of packets read from the network, or -1
on error. This function does not block, so can return 0 packets pending.
*/
int SDLNet_UDP_Recv(UDPsocket sock, UDPpacket *packet)
{
UDPpacket *packets[2];
/* Receive a packet array of 1 */
packets[0] = packet;
packets[1] = NULL;
return(SDLNet_UDP_RecvV(sock, packets));
}
/* Close a UDP network socket */
extern void SDLNet_UDP_Close(UDPsocket sock)
{
if ( sock != NULL )
{
if ( sock->channel != INVALID_SOCKET )
{
closesocket(sock->channel);
}
free(sock);
}
}
+163
View File
@@ -0,0 +1,163 @@
/*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
#include "SDLnetsys.h"
#include "SDL_net.h"
/* The select() API for network sockets */
struct SDLNet_Socket {
int ready;
SOCKET channel;
};
struct _SDLNet_SocketSet {
int numsockets;
int maxsockets;
struct SDLNet_Socket **sockets;
};
/* Allocate a socket set for use with SDLNet_CheckSockets()
This returns a socket set for up to 'maxsockets' sockets, or NULL if
the function ran out of memory.
*/
SDLNet_SocketSet SDLNet_AllocSocketSet(int maxsockets)
{
struct _SDLNet_SocketSet *set;
int i;
set = (struct _SDLNet_SocketSet *)malloc(sizeof(*set));
if ( set != NULL ) {
set->numsockets = 0;
set->maxsockets = maxsockets;
set->sockets = (struct SDLNet_Socket **)malloc
(maxsockets*sizeof(*set->sockets));
if ( set->sockets != NULL ) {
for ( i=0; i<maxsockets; ++i ) {
set->sockets[i] = NULL;
}
} else {
free(set);
set = NULL;
}
}
return(set);
}
/* Add a socket to a set of sockets to be checked for available data */
int SDLNet_AddSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock)
{
if ( sock != NULL ) {
if ( set->numsockets == set->maxsockets ) {
SDLNet_SetError("socketset is full");
return(-1);
}
set->sockets[set->numsockets++] = (struct SDLNet_Socket *)sock;
}
return(set->numsockets);
}
/* Remove a socket from a set of sockets to be checked for available data */
int SDLNet_DelSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock)
{
int i;
if ( sock != NULL ) {
for ( i=0; i<set->numsockets; ++i ) {
if ( set->sockets[i] == (struct SDLNet_Socket *)sock ) {
break;
}
}
if ( i == set->numsockets ) {
SDLNet_SetError("socket not found in socketset");
return(-1);
}
--set->numsockets;
for ( ; i<set->numsockets; ++i ) {
set->sockets[i] = set->sockets[i+1];
}
}
return(set->numsockets);
}
/* This function checks to see if data is available for reading on the
given set of sockets. If 'timeout' is 0, it performs a quick poll,
otherwise the function returns when either data is available for
reading, or the timeout in milliseconds has elapsed, which ever occurs
first. This function returns the number of sockets ready for reading,
or -1 if there was an error with the select() system call.
*/
int SDLNet_CheckSockets(SDLNet_SocketSet set, Uint32 timeout)
{
int i;
SOCKET maxfd;
int retval;
struct timeval tv;
fd_set mask;
/* Find the largest file descriptor */
maxfd = 0;
for ( i=set->numsockets-1; i>=0; --i ) {
if ( set->sockets[i]->channel > maxfd ) {
maxfd = set->sockets[i]->channel;
}
}
/* Check the file descriptors for available data */
do {
SDLNet_SetLastError(0);
/* Set up the mask of file descriptors */
FD_ZERO(&mask);
for ( i=set->numsockets-1; i>=0; --i ) {
FD_SET(set->sockets[i]->channel, &mask);
}
/* Set up the timeout */
tv.tv_sec = timeout/1000;
tv.tv_usec = (timeout%1000)*1000;
/* Look! */
retval = select(maxfd+1, &mask, NULL, NULL, &tv);
} while ( SDLNet_GetLastError() == EINTR );
/* Mark all file descriptors ready that have data available */
if ( retval > 0 ) {
for ( i=set->numsockets-1; i>=0; --i ) {
if ( FD_ISSET(set->sockets[i]->channel, &mask) ) {
set->sockets[i]->ready = 1;
}
}
}
return(retval);
}
/* Free a set of sockets allocated by SDL_NetAllocSocketSet() */
extern void SDLNet_FreeSocketSet(SDLNet_SocketSet set)
{
if ( set ) {
free(set->sockets);
free(set);
}
}
+94
View File
@@ -0,0 +1,94 @@
/*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
/* Include normal system headers */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32_WCE
#include <errno.h>
#endif
/* Include system network headers */
#if defined(__WIN32__) || defined(WIN32)
#define __USE_W32_SOCKETS
#ifdef _WIN64
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <winsock.h>
/* NOTE: windows socklen_t is signed
* and is defined only for winsock2. */
typedef int socklen_t;
#endif /* W64 */
#include <iphlpapi.h>
#else /* UNIX */
#include <sys/types.h>
#ifdef __FreeBSD__
#include <sys/socket.h>
#endif
#include <sys/ioctl.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#ifndef __BEOS__
#include <arpa/inet.h>
#endif
#ifdef linux /* FIXME: what other platforms have this? */
#include <netinet/tcp.h>
#endif
#include <sys/socket.h>
#include <net/if.h>
#include <netdb.h>
#endif /* WIN32 */
/* FIXME: What platforms need this? */
#if 0
typedef Uint32 socklen_t;
#endif
/* System-dependent definitions */
#ifndef __USE_W32_SOCKETS
#ifdef __OS2__
#define closesocket soclose
#else /* !__OS2__ */
#define closesocket close
#endif /* __OS2__ */
#define SOCKET int
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#endif /* __USE_W32_SOCKETS */
#ifdef __USE_W32_SOCKETS
#define SDLNet_GetLastError WSAGetLastError
#define SDLNet_SetLastError WSASetLastError
#ifndef EINTR
#define EINTR WSAEINTR
#endif
#else
int SDLNet_GetLastError(void);
void SDLNet_SetLastError(int err);
#endif
+39
View File
@@ -0,0 +1,39 @@
#config
LIBDIR=..
LOCALLIBS=
LIB=
INCLUDES=
CFLAGS+=$(addprefix -I,$(INCLUDES))
#source
SRC=$(wildcard *.c)
#objects
OBJDIR=obj
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.c=.o))
#output
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,libSDL_net.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
+32
View File
@@ -0,0 +1,32 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CLIENTENTRY_HPP_
#define CLIENTENTRY_HPP_
#include "SDL_net/SDL_net.h"
struct ClientEntry {
int index;
IPaddress address;
};
#endif
+34
View File
@@ -0,0 +1,34 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef DEFINES_HPP_
#define DEFINES_HPP_
#define GAME_CHANNEL 0
#define CHAT_CHANNEL 1
#define WALKING_SPEED 140
enum class CardinalDirection {
NORTH, SOUTH, EAST, WEST
};
#endif
+9 -7
View File
@@ -1,18 +1,20 @@
#config
INCLUDES+=.
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
LIBDIR=..
LOCALLIBS=$(LIBDIR)/out/libCodebase.a
LIB=
INCLUDES=$(LIBDIR)/Codebase
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,libCommon.a)
#targets
all: $(OBJ) $(OUT)
+110
View File
@@ -0,0 +1,110 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "network_queue.hpp"
#include "singleton.hpp"
#include "udp_network_utility.hpp"
#include "SDL/SDL_thread.h"
#include <stdexcept>
#include <deque>
static SDL_sem* lock = SDL_CreateSemaphore(1);
static SDL_Thread* queueThread = nullptr;
static std::deque<Packet> queue;
static bool running = false;
static int networkQueue(void*) {
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
while(running) {
SDL_SemWait(lock);
while(netUtil->Receive()) {
Packet p;
memcpy(&p, netUtil->GetInData(), sizeof(Packet));
p.meta.address = netUtil->GetInPacket()->address;
queue.push_back(p);
}
SDL_SemPost(lock);
SDL_Delay(10);
}
return 0;
}
void beginQueueThread() {
if (running) {
return;
}
running = true;
if (!(queueThread = SDL_CreateThread(networkQueue, nullptr))) {
throw(std::runtime_error("Failed to create the network thread"));
}
}
void endQueueThread() {
if (!running) {
return;
}
running = false;
SDL_WaitThread(queueThread, nullptr);
queueThread = nullptr;
}
void killQueueThread() {
if (!running) {
return;
}
running = false;
SDL_KillThread(queueThread);
queueThread = nullptr;
}
Packet peekNetworkPacket() {
SDL_SemWait(lock);
Packet p;
if (queue.size() > 0) {
Packet p = queue[0];
}
SDL_SemPost(lock);
return p;
}
Packet popNetworkPacket() {
SDL_SemWait(lock);
Packet p;
if (queue.size() > 0) {
p = queue[0];
queue.pop_front();
}
SDL_SemPost(lock);
return p;
}
void flushNetworkQueue() {
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
SDL_SemWait(lock);
while(netUtil->Receive());
queue.clear();
SDL_SemPost(lock);
}
+34
View File
@@ -0,0 +1,34 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef NETWORKQUEUE_HPP_
#define NETWORKQUEUE_HPP_
#include "packet.hpp"
void beginQueueThread();
void endQueueThread();
void killQueueThread();
Packet peekNetworkPacket();
Packet popNetworkPacket();
void flushNetworkQueue();
#endif
+90
View File
@@ -0,0 +1,90 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef PACKETTYPE_HPP_
#define PACKETTYPE_HPP_
#include "vector2.hpp"
#include "SDL_net/SDL_net.h"
#define PACKET_STRING_SIZE 100
#pragma pack(push, 0)
union Packet {
//the type of packet being sent
enum class Type {
NONE = 0,
PING = 1,
PONG = 2,
BROADCAST_REQUEST = 3,
BROADCAST_RESPONSE = 4,
JOIN_REQUEST = 5,
JOIN_RESPONSE = 6,
DISCONNECT = 7,
SYNCHRONIZE = 8,
PLAYER_NEW = 9,
PLAYER_DELETE = 10,
PLAYER_UPDATE = 11,
};
//metadata on the packet itself
struct Metadata {
Type type;
IPaddress address;
int clientIndex;
}meta;
//information about the server
struct ServerInformation {
Metadata meta;
//TODO: version info
char name[PACKET_STRING_SIZE];
//TODO: player count
}serverInfo;
//information about a specific player
struct PlayerInformation {
Metadata meta;
int index;
char handle[PACKET_STRING_SIZE];
char avatar[PACKET_STRING_SIZE];
Vector2 position;
Vector2 motion;
//TODO Playerdata
}playerInfo;
//zero the packet
Packet() {
meta.type = Type::NONE;
meta.address.host = 0;
meta.address.port = 0;
meta.clientIndex = -1;
};
};
#pragma pack(pop)
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,19 +19,20 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef MATHS_HPP_
#define MATHS_HPP_
#ifndef PLAYERENTRY_HPP_
#define PLAYERENTRY_HPP_
#include "vector2.hpp"
//param: 0 to 1 inclusive
double curve(double);
#include <string>
//snap x to a grid of base
double snap(double x, double base);
int snap(int x, int base);
struct PlayerEntry {
int index;
int clientIndex;
std::string handle;
std::string avatar;
Vector2 position;
Vector2 motion;
};
//vector dot product
double scalarProduct(Vector2, Vector2);
#endif
#endif
+35
View File
@@ -0,0 +1,35 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERVERENTRY_HPP_
#define SERVERENTRY_HPP_
#include "SDL_net/SDL_net.h"
#include <string>
struct ServerEntry {
std::string name;
IPaddress address;
//TODO: player count
};
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,24 +19,20 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SIMPLERNG_HPP_
#define SIMPLERNG_HPP_
#ifndef SINGLETON_HPP_
#define SINGLETON_HPP_
//a simple, stateless, random number generator
class SimpleRNG {
template<typename T>
class Singleton {
public:
SimpleRNG() { SetSeed(8891.0); }
SimpleRNG(double x) { SetSeed(x); }
double SetSeed(double s) { return seed = s; }
double GetSeed() { return seed; }
double operator()(double x) {
return (x + seed) * 11235.0 + 81321.0;
};
static T* Get() {
return &instance;
}
private:
double seed;
static T instance;
};
#endif
template<typename T>
T Singleton<T>::instance;
#endif
+30
View File
@@ -0,0 +1,30 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "utilities.hpp"
#include <cstdio>
std::string itos(int i) {
char buffer[20];
snprintf(buffer, 20, "%d", i);
return std::string(buffer);
}
+29
View File
@@ -0,0 +1,29 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef UTILITIES_HPP_
#define UTILITIES_HPP_
#include <string>
std::string itos(int i);
#endif
+13
View File
@@ -0,0 +1,13 @@
OUTDIR=out
all: $(OUTDIR)
$(MAKE) -C codebase
$(MAKE) -C common
$(OUTDIR):
mkdir $(OUTDIR)
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
+5 -12
View File
@@ -1,18 +1,11 @@
#for use on Windows:
#MKDIR=mkdir
#RM=del /y
CXXFLAGS+=-static-libgcc -static-libstdc++
export
OUTDIR=out
all: $(OUTDIR)
$(MAKE) -C utils
$(MAKE) -C mapgen
$(MAKE) -C src
$(MAKE) -C libs
$(MAKE) -C server
$(MAKE) -C client
$(MAKE) -C editor
$(MAKE) -C test
$(OUTDIR):
mkdir $(OUTDIR)
-120
View File
@@ -1,120 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "map_generator.hpp"
#include "vector2.hpp"
#include <cmath>
//-------------------------
//Utility functions
//-------------------------
//snap to a grid (floating point version)
static double snap(double x, double base) {
return floor(x / base) * base;
}
//A.K.A.: the dot product
static double scalarProduct(Vector2 lhs, Vector2 rhs) {
return lhs.x * rhs.x + lhs.y * rhs.y;
}
//curved interpolation
static double curve(double x) {
//param: 0 to 1 inclusive
return 3.0 * pow(x, 2.0) - 2.0 * pow(x, 3.0);
}
//fix the overflow
static double curl(double x) {
if (x > 1.0) {
return -curl(x-1) +1;
}
if (x < 0.0) {
return curl(-x);
}
return x;
}
static double cut(double x) {
if (x > 1.0) {
return 1.0;
}
if (x < 0.0) {
return 0.0;
}
return x;
}
//-------------------------
//Public methods
//-------------------------
Vector2 MapGenerator::RawNoise(Vector2 const& gridPoint) {
double angle = rng(gridPoint.x * 0xffff + gridPoint.y);
Vector2 v = {cos(angle), sin(angle)};
v.Normalize();
return v;
}
double MapGenerator::Influence(Vector2 const& gridPoint, Vector2 const& queryPoint, double width, double height) {
//note: inverting the distance here, so the smaller the distance the more influence it has
Vector2 distance = queryPoint - gridPoint;
Vector2 inverted = {width - distance.x, height - distance.y};
double ret = scalarProduct(RawNoise(gridPoint), inverted);
return ret > 0 ? ret : -ret;
}
double MapGenerator::ScaledNoise(double x, double y, double width, double height) {
Vector2 queryPoint = {x, y};
//the "grid points"
Vector2 tl = {snap(x, width), snap(y, height)};
Vector2 tr = {tl.x + width, tl.y};
Vector2 bl = {tl.x, tl.y + height};
Vector2 br = {tl.x + width, tl.y + height};
//influence equasion
double s = Influence(tl, queryPoint, width, height);
double t = Influence(tr, queryPoint, width, height);
double u = Influence(bl, queryPoint, width, height);
double v = Influence(br, queryPoint, width, height);
//Finally, calc the value
double a = s + curve((t - s) / width);
double b = u + curve((v - u) / width);
return curve((b - a) / height);
}
double MapGenerator::ScaledOctave(double x, double y, double width, double height, double octave) {
double ret = 0;
if (octave > 1) {
ret += ScaledOctave(x, y, width/2, height/2, octave-1);
}
return ret / octave + ScaledNoise(x, y, width, height);
}
double MapGenerator::GetPixel(double x, double y, double width, double height, double octave) {
//use this as a decorator function
return curl(ScaledOctave(x, y, width, height, octave));
}
+20
View File
@@ -0,0 +1,20 @@
#configuration of the programs
server.host = 127.0.0.1
server.port = 1991
server.name = foobar
screen.w = 800
screen.h = 600
screen.f = false
#directories
fonts = rsc/graphics/fonts
logos = rsc/graphics/logos
sprites = rsc/graphics/sprites
tilesets = rsc/graphics/tilesets
interface = rsc/graphics/interface
#debugging
debug = true
avatar = elliot
handle = UserName
Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

+11 -7
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,25 +19,29 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "application.hpp"
#include "server_application.hpp"
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
cout << "Beginning " << argv[0] << endl;
int main(int, char**) {
#ifdef DEBUG
cout << "Beginning server" << endl;
#endif
try {
Application app;
app.Init(argc, argv);
ServerApplication app;
app.Init();
app.Proc();
app.Quit();
}
catch(exception& e) {
cerr << "Fatal exception thrown: " << e.what() << endl;
cerr << "Fatal error: " << e.what() << endl;
return 1;
}
#ifdef DEBUG
cout << "Clean exit" << endl;
#endif
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#config
LIBDIR=../libs
LOCALLIBS=$(LIBDIR)/out/libCodebase.a $(LIBDIR)/out/libCommon.a
LIB=$(LOCALLIBS) -lSDL_net -lwsock32 -liphlpapi -lmingw32 -lSDLmain -lSDL
INCLUDES=$(LIBDIR)/Codebase $(LIBDIR)/common
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,server)
#targets
all: $(OBJ) $(OUT)
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIB)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
+308
View File
@@ -0,0 +1,308 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "server_application.hpp"
#include <stdexcept>
#include <iostream>
#include <chrono>
using namespace std;
//-------------------------
//Public access members
//-------------------------
ServerApplication::ServerApplication() {
//
}
ServerApplication::~ServerApplication() {
//
}
/* ServerApplication::Init()
* This function initializes the entire program. There are a number of things
* that could go wrong here, which is why there is such an unusual order of
* operations.
* Important things to note:
* The APIs are initiated here.
* The global objects are initialized here.
* The ConfigUtility's call to Load() also ensures that the "rsc\" folder is in the directory. It's easy to forget it.
*/
void ServerApplication::Init() {
//load the config file
try {
configUtil->Load("rsc/config.cfg");
}
catch(std::runtime_error& e) {
std::string s = e.what();
s += "; Ensure that the \"rsc\" directory is present";
throw(std::runtime_error(s));
}
//check the port is valid
if (configUtil->Int("server.port") <= 0) {
throw(runtime_error("Cannot open the server on an invalid port or port 0"));
}
//initialize the APIs
if (SDLNet_Init()) {
throw(runtime_error("Failed to initialize SDL_net"));
}
//initiate the remaining singletons
netUtil->Open(configUtil->Int("server.port"), sizeof(Packet));
//create the threads
beginQueueThread();
//output the server information
cout << configUtil->String("server.name") << endl;
cout << "Open on port " << configUtil->String("server.port") << endl;
//disable this for debugging
running = true;
}
void ServerApplication::Proc() {
typedef chrono::high_resolution_clock Clock;
Clock::time_point lastTick = Clock::now();
Clock::duration delta;
while(running) {
try {
//process all packets on the network queue
while(HandlePacket(popNetworkPacket()));
}
catch(exception& e) {
//handle any errors
cerr << "Network Error: " << e.what() << endl;
continue;
}
//get the time since last update
delta = Clock::now() - lastTick;
lastTick = Clock::now();
//update the world
UpdateWorld(double(delta.count()) / Clock::duration::period::den);
//give the machine a break
SDL_Delay(10);
}
}
void ServerApplication::Quit() {
//close the threads
endQueueThread();
//clean up the singletons
netUtil->Close();
//deinitialize the APIs
SDLNet_Quit();
}
//-------------------------
//Game loop
//-------------------------
void ServerApplication::UpdateWorld(double delta) {
//the recalc here each loop is a stopgap, see issue #9 for details
for (auto& it : players) {
if (it.second.motion.x != 0 && it.second.motion.y != 0) {
constexpr double d = 1.0/sqrt(2);
it.second.position += it.second.motion * delta * d;
}
else {
it.second.position += it.second.motion * delta;
}
}
}
//-------------------------
//Network loop
//-------------------------
int ServerApplication::HandlePacket(Packet p) {
switch(p.meta.type) {
case Packet::Type::NONE:
//DO NOTHING
return 0;
break;
case Packet::Type::PING:
//quick pong
p.meta.type = Packet::Type::PONG;
netUtil->Send(&p.meta.address, &p, sizeof(Packet));
break;
case Packet::Type::PONG:
//
break;
case Packet::Type::BROADCAST_REQUEST:
HandleBroadcast(p);
break;
// case PacketType::BROADCAST_RESPONSE:
// //
// break;
case Packet::Type::JOIN_REQUEST:
HandleConnection(p);
break;
// case PacketType::JOIN_RESPONSE:
// //
// break;
case Packet::Type::DISCONNECT:
HandleDisconnection(p);
break;
case Packet::Type::SYNCHRONIZE:
SynchronizeEverything(p);
break;
case Packet::Type::PLAYER_NEW:
AddPlayer(p);
RelayPacket(p);
break;
case Packet::Type::PLAYER_DELETE:
RemovePlayer(p);
RelayPacket(p);
break;
case Packet::Type::PLAYER_UPDATE:
UpdatePlayer(p);
RelayPacket(p);
break;
default:
throw(runtime_error("Failed to recognize the packet type: " + itos(int(p.meta.type))));
}
return 1;
}
void ServerApplication::RelayPacket(Packet& p) {
//pump this packet to all clients
for (auto& it : clients) {
netUtil->Send(&it.second.address, &p, sizeof(Packet));
}
}
void ServerApplication::SynchronizeEverything(Packet& sync) {
//send all known data to this client
//TODO multithreading?
//all players
Packet p;
p.meta.type = Packet::Type::PLAYER_UPDATE;
for (auto& it : players) {
p.meta.clientIndex = it.second.clientIndex;
p.playerInfo.index = it.second.index;
snprintf(p.playerInfo.handle, PACKET_STRING_SIZE, "%s", it.second.handle.c_str());
snprintf(p.playerInfo.avatar, PACKET_STRING_SIZE, "%s", it.second.avatar.c_str());
p.playerInfo.position = it.second.position;
p.playerInfo.motion = it.second.motion;
netUtil->Send(&clients[sync.meta.clientIndex].address, &p, sizeof(Packet));
}
}
void ServerApplication::HandleBroadcast(Packet& bcast) {
//respond to a broadcast request with the server's data
Packet p;
p.meta.type = Packet::Type::BROADCAST_RESPONSE;
snprintf(p.serverInfo.name, PACKET_STRING_SIZE, "%s", configUtil->CString("server.name"));
//TODO version information
netUtil->Send(&bcast.meta.address, &p, sizeof(Packet));
}
void ServerApplication::HandleConnection(Packet& request) {
//create the entries
ClientEntry newClient = {
uniqueIndex++,
request.meta.address
};
//push this information
clients[newClient.index] = newClient;
//send the player their information
Packet p;
p.meta.type = Packet::Type::JOIN_RESPONSE;
p.meta.clientIndex = newClient.index;
//TODO: resource list
netUtil->Send(&newClient.address, &p, sizeof(Packet));
//debugging
cout << "New connection: index " << newClient.index << endl;
cout << "number of clients: " << clients.size() << endl;
}
void ServerApplication::HandleDisconnection(Packet& disconnect) {
//disconnect a client (redundant message)
netUtil->Send(&clients[disconnect.meta.clientIndex].address, &disconnect, sizeof(Packet));
clients.erase(disconnect.meta.clientIndex);
//TODO remove the player...
//remove if(...)
//remove the player from other clients
//debugging
cout << "Lost connection: index " << disconnect.meta.clientIndex << endl;
cout << "number of clients: " << clients.size() << endl;
}
void ServerApplication::AddPlayer(Packet& p) {
//add the player
PlayerEntry newPlayer = {
uniqueIndex++,
p.meta.clientIndex,
p.playerInfo.handle,
p.playerInfo.avatar,
p.playerInfo.position,
p.playerInfo.motion
};
players[newPlayer.index] = newPlayer;
//prep for relay
p.playerInfo.index = newPlayer.index;
//debugging
cout << "New player " << newPlayer.handle << " has joined the game" << endl;
cout << "Number of players: " << players.size() << endl;
}
void ServerApplication::RemovePlayer(Packet& p) {
if (players.find(p.playerInfo.index) == players.end()) {
throw(runtime_error("Player to delete not found"));
}
players.erase(p.playerInfo.index);
}
void ServerApplication::UpdatePlayer(Packet& p) {
if (players.find(p.playerInfo.index) == players.end()) {
throw(runtime_error("Player to update not found"));
}
players[p.playerInfo.index].position = p.playerInfo.position;
players[p.playerInfo.index].motion = p.playerInfo.motion;
}
+84
View File
@@ -0,0 +1,84 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERVERAPPLICATION_HPP_
#define SERVERAPPLICATION_HPP_
#include "utilities.hpp"
#include "packet.hpp"
#include "singleton.hpp"
#include "network_queue.hpp"
#include "client_entry.hpp"
#include "player_entry.hpp"
#include "config_Utility.hpp"
#include "udp_network_utility.hpp"
#include "vector2.hpp"
#include "SDL/SDL_thread.h"
#include <map>
#include <string>
#include <algorithm>
class ServerApplication {
public:
ServerApplication();
~ServerApplication();
void Init();
void Proc();
void Quit();
ServerApplication(ServerApplication const&) = delete;
ServerApplication(ServerApplication const&&) = delete;
private:
//game loop
void UpdateWorld(double delta);
//network loop
int HandlePacket(Packet);
void RelayPacket(Packet&);
void SynchronizeEverything(Packet&);
void HandleBroadcast(Packet&);
void HandleConnection(Packet&);
void HandleDisconnection(Packet&);
void AddPlayer(Packet&);
void RemovePlayer(Packet&);
void UpdatePlayer(Packet&);
//services
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
//members
std::map<int, ClientEntry> clients;
std::map<int, PlayerEntry> players;
bool running = false;
int uniqueIndex = 0;
};
#endif
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=. ../utils ../mapgen
LIBS+=../libcommon.a -lmingw32 -lSDLmain -lSDL
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,shell)
#targets
all: $(OBJ) $(OUT)
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIBS)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
-150
View File
@@ -1,150 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "shell_scene.hpp"
#include <iostream>
//-------------------------
//Public access members
//-------------------------
static double max = 0;
static double min = 0;
void setPixel(SDL_Surface* const dest, int x, int y, int colour) {
*(static_cast<int*>(dest->pixels) + dest->w * y + x) = colour;
}
int convertToColour(SDL_PixelFormat* format, double x) {
//track the max value
max = x > max ? x : max;
min = x < min ? x : min;
if (x > 1) {
return SDL_MapRGB(format, 255, 0, 0);
}
if (x < 0) {
return SDL_MapRGB(format, 0, 255, 0);
}
if (x == 0) {
return SDL_MapRGB(format, 0, 0, 255);
}
return SDL_MapRGB(format, 255*x, 255*x, 255*x);
}
int convertToTerrain(SDL_PixelFormat* format, double x) {
//water
if (x < 0.4) {
return SDL_MapRGB(format, 0, 0, 255);
}
//sand
if (x < 0.5) {
return SDL_MapRGB(format, 255, 255, 0);
}
//grass
if (x < 0.6) {
return SDL_MapRGB(format, 0, 255, 0);
}
//forest
if (x < 0.8) {
return SDL_MapRGB(format, 0, 128, 0);
}
//snow
if (x < 0.8) {
return SDL_MapRGB(format, 255, 255, 255);
}
//dark snow
return SDL_MapRGB(format, 128, 128, 128);
}
ShellScene::ShellScene() {
//test the generator
int width = 256;
int height = 256;
image.CreateSurface(GetScreen()->w, GetScreen()->h);
double value;
int colour;
std::cout << "Beggining generation" << std::endl;
for (int i = 0; i < image.GetSurface()->w; i++) {
for (int j = 0; j < image.GetSurface()->h; j++) {
value = generator.GetPixel(i, j, width, height, 8);
colour = convertToColour(image.GetSurface()->format, value);
setPixel(image.GetSurface(), i, j, colour);
}
}
std::cout << "Finished generation" << std::endl;
std::cout << "Max: " << max << std::endl;
std::cout << "Min: " << min << std::endl;
}
ShellScene::~ShellScene() {
//
}
//-------------------------
//Frame loop
//-------------------------
void ShellScene::FrameStart() {
//
}
void ShellScene::Update(double delta) {
//
}
void ShellScene::FrameEnd() {
//
}
void ShellScene::Render(SDL_Surface* const screen) {
image.DrawTo(screen, 0, 0);
}
//-------------------------
//Event handlers
//-------------------------
void ShellScene::MouseMotion(SDL_MouseMotionEvent const& motion) {
//
}
void ShellScene::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//
}
void ShellScene::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//
}
void ShellScene::KeyDown(SDL_KeyboardEvent const& key) {
//
}
void ShellScene::KeyUp(SDL_KeyboardEvent const& key) {
//
}
+1
View File
@@ -0,0 +1 @@
#include "foobar.hpp"
+6
View File
@@ -0,0 +1,6 @@
#ifndef FOOBAR_HPP_
#define FOOBAR_HPP_
int FooBar();
#endif
+10
View File
@@ -0,0 +1,10 @@
#include "packet.hpp"
#include <iostream>
using namespace std;
int main(int, char**) {
Packet p;
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#config
LIBDIR=../libs
LOCALLIBS=$(LIBDIR)/out/libCodebase.a $(LIBDIR)/out/libCommon.a
LIB=$(LOCALLIBS) -lSDL_net -lwsock32 -liphlpapi -lmingw32 -lSDLmain -lSDL
INCLUDES=$(LIBDIR)/Codebase $(LIBDIR)/common
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=../out
OUT=$(addprefix $(OUTDIR)/,test)
#targets
all: $(OBJ) $(OUT)
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIB)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
-145
View File
@@ -1,145 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "image.hpp"
#include <stdexcept>
#include <sstream>
Image& Image::operator=(Image const& rhs) {
//don't screw yourself
if (this == &rhs) {
return *this;
}
FreeSurface();
//Copy the other Image's stuff
surface = rhs.surface;
clip = rhs.clip;
local = false;
}
Image& Image::operator=(Image&& rhs) {
//don't screw yourself
if (this == &rhs) {
return *this;
}
FreeSurface();
//Steal the other Image's stuff
surface = rhs.surface;
clip = rhs.clip;
local = rhs.local;
rhs.surface = nullptr;
rhs.clip = {0, 0, 0, 0};
rhs.local = false;
}
SDL_Surface* Image::LoadSurface(std::string fname) {
FreeSurface();
SDL_Surface* p = SDL_LoadBMP(fname.c_str());
if (!p) {
std::ostringstream os;
os << "Failed to load file: " << fname;
throw(std::runtime_error(os.str()));
}
surface = p;
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = true;
SetTransparentColor(255, 0, 255); //default
return surface;
}
SDL_Surface* Image::CreateSurface(Uint16 w, Uint16 h) {
FreeSurface();
Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
SDL_Surface* p = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, rmask, gmask, bmask, amask);
if (!p) {
throw(std::runtime_error("Failed to create Image surface"));
}
surface = p;
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = true;
SetTransparentColor(255, 0, 255); //default
return surface;
}
SDL_Surface* Image::SetSurface(SDL_Surface* p) {
FreeSurface();
if (!p) {
throw(std::invalid_argument("No surface pointer provided"));
}
surface = p;
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = false;
return surface;
}
void Image::FreeSurface() {
if (local) {
SDL_FreeSurface(surface);
local = false;
}
surface = nullptr;
clip = {0, 0, 0, 0};
}
void Image::DrawTo(SDL_Surface* dest, Sint16 x, Sint16 y) {
if (!surface) {
throw(std::logic_error("No image surface to draw"));
}
SDL_Rect sclip = clip, dclip = {x,y};
SDL_BlitSurface(surface, &sclip, dest, &dclip);
}
void Image::SetTransparentColor(Uint8 r, Uint8 g, Uint8 b) {
if (!surface) {
throw(std::logic_error("Failed to set the transparent color"));
}
if (!local) {
throw(std::logic_error("Cannot set the transparent color of a non-local surface"));
}
SDL_SetColorKey(surface, SDL_SRCCOLORKEY, SDL_MapRGB(surface->format, r, g, b));
}
void Image::ClearTransparentColor() {
if (!surface) {
throw(std::logic_error("Failed to clear the transparent color"));
}
if (!local) {
throw(std::logic_error("Cannot clear the transparent color of a non-local surface"));
}
SDL_SetColorKey(surface, 0, 0);
}