diff options
Diffstat (limited to 'src/libjin/Game')
-rw-r--r-- | src/libjin/Game/Game.cpp | 74 | ||||
-rw-r--r-- | src/libjin/Game/Game.h | 58 |
2 files changed, 132 insertions, 0 deletions
diff --git a/src/libjin/Game/Game.cpp b/src/libjin/Game/Game.cpp new file mode 100644 index 0000000..3f905f2 --- /dev/null +++ b/src/libjin/Game/Game.cpp @@ -0,0 +1,74 @@ +#include "game.h" +#include "../Time/Timer.h" +#include "../input/Event.h" +#include "../Graphics/Window.h" +#include "../Math/Math.h" +#include <iostream> + +namespace jin +{ +namespace core +{ + + using namespace jin::graphics; + using namespace jin::input; + using namespace jin::time; + using namespace jin::math; + + Game::Game() :_running(true) {}; + + void Game::run() + { + if (_onLoad != nullptr) + _onLoad(); + Window* wnd = Window::get(); + const int FPS = wnd ? wnd->getFPS() : 60; + const int MS_PER_UPDATE = 1000.0f / FPS; + _running = true; + Event e; + int previous = getMilliSecond(); + int dt = MS_PER_UPDATE; + while (_running) + { + while (jin::input::pollEvent(&e)) + { + if (_onEvent != nullptr) + _onEvent(&e); + if (!_running) goto quitloop; + } + if (_onUpdate != nullptr) _onUpdate(dt); + if (_onDraw != nullptr) _onDraw(); + wnd->swapBuffers(); + const int current = getMilliSecond(); + dt = current - previous; + const int wait = MS_PER_UPDATE - (current - previous); + previous += MS_PER_UPDATE; + if (wait > 0) + { + sleep(wait); + dt = MS_PER_UPDATE; + } + else + previous = current; + } + quitloop:; + } + + bool Game::initSystem(const SettingBase* setting) + { + if (setting == nullptr) + return false; + Game::Setting* s = (Game::Setting*) setting; + _onEvent = s->eventHandler; + _onUpdate = s->updater; + _onDraw = s->drawer; + _onLoad = s->loader; + return true; + } + + void Game::quitSystem() + { + } + +} // core +} // jin
\ No newline at end of file diff --git a/src/libjin/Game/Game.h b/src/libjin/Game/Game.h new file mode 100644 index 0000000..725c62c --- /dev/null +++ b/src/libjin/Game/Game.h @@ -0,0 +1,58 @@ +#ifndef __LIBJIN_CORE_GAME_H +#define __LIBJIN_CORE_GAME_H + +#include "SDL2/SDL.h" + +#include "../Common/Subsystem.hpp" +#include "../utils/macros.h" +#include "../Input/Event.h" + +namespace jin +{ +namespace core +{ + + class Game : public Subsystem<Game> + { + public: + + typedef void(*onLoad)(); + typedef void(*onEvent)(jin::input::Event* e); + typedef void(*onUpdate)(int dt); + typedef void(*onDraw)(); + + struct Setting : SettingBase + { + onEvent eventHandler; + onUpdate updater; + onDraw drawer; + onLoad loader; + }; + + void run(); + inline void stop() { _running = false; }; + inline bool running() { return _running; }; + + private: + + Game(); + ~Game() {}; + + SINGLETON(Game); + + onEvent _onEvent; + onUpdate _onUpdate; + onDraw _onDraw; + onLoad _onLoad; + + bool _running; + + bool initSystem(const SettingBase* setting); + void quitSystem(); + + }; + +} // core +} // jin + +#endif // __LIBJIN_CORE_GAME_H |