GameEngine.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * GameEngine.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "GameEngine.h"
  12. #include "gui/CIntObject.h"
  13. #include "gui/CursorHandler.h"
  14. #include "gui/ShortcutHandler.h"
  15. #include "gui/FramerateManager.h"
  16. #include "gui/WindowHandler.h"
  17. #include "gui/EventDispatcher.h"
  18. #include "eventsSDL/InputHandler.h"
  19. #include "media/CMusicHandler.h"
  20. #include "media/CSoundHandler.h"
  21. #include "media/CVideoHandler.h"
  22. #include "media/CEmptyVideoPlayer.h"
  23. #include "adventureMap/AdventureMapInterface.h"
  24. #include "render/Canvas.h"
  25. #include "render/Colors.h"
  26. #include "render/IFont.h"
  27. #include "render/EFont.h"
  28. #include "renderSDL/ScreenHandler.h"
  29. #include "renderSDL/RenderHandler.h"
  30. #include "GameEngineUser.h"
  31. #include "battle/BattleInterface.h"
  32. #include "../lib/AsyncRunner.h"
  33. #include "../lib/CConfigHandler.h"
  34. #include "../lib/texts/TextOperations.h"
  35. #include <SDL_render.h>
  36. std::unique_ptr<GameEngine> ENGINE;
  37. static thread_local bool inGuiThread = false;
  38. ObjectConstruction::ObjectConstruction(CIntObject *obj)
  39. {
  40. ENGINE->createdObj.push_front(obj);
  41. ENGINE->captureChildren = true;
  42. }
  43. ObjectConstruction::~ObjectConstruction()
  44. {
  45. assert(!ENGINE->createdObj.empty());
  46. ENGINE->createdObj.pop_front();
  47. ENGINE->captureChildren = !ENGINE->createdObj.empty();
  48. }
  49. GameEngine::GameEngine()
  50. : captureChildren(false)
  51. , fakeStatusBar(std::make_shared<EmptyStatusBar>())
  52. {
  53. inGuiThread = true;
  54. eventDispatcherInstance = std::make_unique<EventDispatcher>();
  55. windowHandlerInstance = std::make_unique<WindowHandler>();
  56. screenHandlerInstance = std::make_unique<ScreenHandler>();
  57. renderHandlerInstance = std::make_unique<RenderHandler>();
  58. shortcutsHandlerInstance = std::make_unique<ShortcutHandler>();
  59. inputHandlerInstance = std::make_unique<InputHandler>(); // Must be after windowHandlerInstance and shortcutsHandlerInstance
  60. framerateManagerInstance = std::make_unique<FramerateManager>(settings["video"]["targetfps"].Integer());
  61. #ifndef ENABLE_VIDEO
  62. videoPlayerInstance = std::make_unique<CEmptyVideoPlayer>();
  63. #else
  64. if (settings["session"]["disableVideo"].Bool())
  65. videoPlayerInstance = std::make_unique<CEmptyVideoPlayer>();
  66. else
  67. videoPlayerInstance = std::make_unique<CVideoPlayer>();
  68. #endif
  69. soundPlayerInstance = std::make_unique<CSoundHandler>();
  70. musicPlayerInstance = std::make_unique<CMusicHandler>();
  71. sound().setVolume(settings["general"]["sound"].Integer());
  72. music().setVolume(settings["general"]["music"].Integer());
  73. cursorHandlerInstance = std::make_unique<CursorHandler>();
  74. asyncTasks = std::make_unique<AsyncRunner>();
  75. }
  76. void GameEngine::handleEvents()
  77. {
  78. events().dispatchTimer(framerate().getElapsedMilliseconds());
  79. //player interface may want special event handling
  80. if(engineUser->capturedAllEvents())
  81. return;
  82. input().processEvents();
  83. }
  84. void GameEngine::fakeMouseMove()
  85. {
  86. dispatchMainThread([](){
  87. ENGINE->events().dispatchMouseMoved(Point(0, 0), ENGINE->getCursorPosition());
  88. });
  89. }
  90. [[noreturn]] void GameEngine::mainLoop()
  91. {
  92. for (;;)
  93. {
  94. input().fetchEvents();
  95. updateFrame();
  96. screenHandlerInstance->presentScreenTexture();
  97. framerate().framerateDelay(); // holds a constant FPS
  98. }
  99. }
  100. void GameEngine::updateFrame()
  101. {
  102. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  103. engineUser->onUpdate();
  104. handleEvents();
  105. windows().simpleRedraw();
  106. if (settings["video"]["infobox"]["show"].Bool())
  107. drawInfoBox();
  108. screenHandlerInstance->updateScreenTexture();
  109. windows().onFrameRendered();
  110. ENGINE->cursor().update();
  111. }
  112. GameEngine::~GameEngine()
  113. {
  114. // enforce deletion order on shutdown
  115. // all UI elements including adventure map must be destroyed before Gui Handler
  116. // proper solution would be removal of adventureInt global
  117. adventureInt.reset();
  118. }
  119. ShortcutHandler & GameEngine::shortcuts()
  120. {
  121. assert(shortcutsHandlerInstance);
  122. return *shortcutsHandlerInstance;
  123. }
  124. FramerateManager & GameEngine::framerate()
  125. {
  126. assert(framerateManagerInstance);
  127. return *framerateManagerInstance;
  128. }
  129. bool GameEngine::isKeyboardCtrlDown() const
  130. {
  131. return inputHandlerInstance->isKeyboardCtrlDown();
  132. }
  133. bool GameEngine::isKeyboardCmdDown() const
  134. {
  135. return inputHandlerInstance->isKeyboardCmdDown();
  136. }
  137. bool GameEngine::isKeyboardAltDown() const
  138. {
  139. return inputHandlerInstance->isKeyboardAltDown();
  140. }
  141. bool GameEngine::isKeyboardShiftDown() const
  142. {
  143. return inputHandlerInstance->isKeyboardShiftDown();
  144. }
  145. const Point & GameEngine::getCursorPosition() const
  146. {
  147. return inputHandlerInstance->getCursorPosition();
  148. }
  149. Point GameEngine::screenDimensions() const
  150. {
  151. return screenHandlerInstance->getLogicalResolution();
  152. }
  153. void GameEngine::drawInfoBox()
  154. {
  155. auto font = EFonts::FONT_SMALL;
  156. const auto & fontPtr = ENGINE->renderHandler().loadFont(font);
  157. Canvas target = screenHandler().getScreenCanvas();
  158. auto powerState = ENGINE->input().getPowerState();
  159. std::string powerSymbol = ""; // add symbol if emoji are supported (e.g. VCMI extras)
  160. if(fontPtr->canRepresentCharacter("🔋") && powerState.powerState == PowerStateMode::ON_BATTERY)
  161. powerSymbol = "🔋 ";
  162. else if(fontPtr->canRepresentCharacter("🔌") && powerState.powerState == PowerStateMode::CHARGING)
  163. powerSymbol = "🔌 ";
  164. std::string fps = std::to_string(framerate().getFramerate())+" FPS";
  165. std::string time = TextOperations::getFormattedTimeLocal(std::time(nullptr));
  166. std::string power = powerState.powerState == PowerStateMode::UNKNOWN ? "" : powerSymbol + std::to_string(powerState.percent) + "%";
  167. std::string textToDisplay = time + (power.empty() ? "" : " | " + power) + " | " + fps;
  168. maxInfoBoxTextWidth = std::max(maxInfoBoxTextWidth, static_cast<int>(fontPtr->getStringWidth(textToDisplay))); // do not get smaller (can cause graphical glitches)
  169. Rect targetArea;
  170. std::string edge = settings["video"]["infobox"]["edge"].String();
  171. int pos1 = settings["video"]["infobox"]["pos1"].Integer();
  172. int pos2 = settings["video"]["infobox"]["pos2"].Integer();
  173. Point boxSize(maxInfoBoxTextWidth + 4, fontPtr->getLineHeight() + 2);
  174. if (edge == "topleft")
  175. targetArea = Rect(pos2, pos1, boxSize.x, boxSize.y);
  176. else if (edge == "topright")
  177. targetArea = Rect(screenDimensions().x - pos2 - boxSize.x, pos1, boxSize.x, boxSize.y);
  178. else if (edge == "bottomleft")
  179. targetArea = Rect(pos2, screenDimensions().y - pos1 - boxSize.y, boxSize.x, boxSize.y);
  180. else if (edge == "bottomright")
  181. targetArea = Rect(screenDimensions().x - pos2 - boxSize.x, screenDimensions().y - pos1 - boxSize.y, boxSize.x, boxSize.y);
  182. target.drawColor(targetArea.resize(1), Colors::BRIGHT_YELLOW);
  183. target.drawColor(targetArea, ColorRGBA(0, 0, 0));
  184. target.drawText(targetArea.center(), font, Colors::WHITE, ETextAlignment::CENTER, textToDisplay);
  185. }
  186. bool GameEngine::amIGuiThread()
  187. {
  188. return inGuiThread;
  189. }
  190. void GameEngine::dispatchMainThread(const std::function<void()> & functor)
  191. {
  192. inputHandlerInstance->dispatchMainThread(functor);
  193. }
  194. IScreenHandler & GameEngine::screenHandler()
  195. {
  196. return *screenHandlerInstance;
  197. }
  198. IRenderHandler & GameEngine::renderHandler()
  199. {
  200. return *renderHandlerInstance;
  201. }
  202. EventDispatcher & GameEngine::events()
  203. {
  204. return *eventDispatcherInstance;
  205. }
  206. InputHandler & GameEngine::input()
  207. {
  208. return *inputHandlerInstance;
  209. }
  210. WindowHandler & GameEngine::windows()
  211. {
  212. assert(windowHandlerInstance);
  213. return *windowHandlerInstance;
  214. }
  215. std::shared_ptr<IStatusBar> GameEngine::statusbar()
  216. {
  217. auto locked = currentStatusBar.lock();
  218. if (!locked)
  219. return fakeStatusBar;
  220. return locked;
  221. }
  222. void GameEngine::setStatusbar(const std::shared_ptr<IStatusBar> & newStatusBar)
  223. {
  224. currentStatusBar = newStatusBar;
  225. }
  226. void GameEngine::onScreenResize(bool resolutionChanged)
  227. {
  228. if(resolutionChanged)
  229. screenHandler().onScreenResize();
  230. windows().onScreenResize();
  231. ENGINE->cursor().onScreenResize();
  232. }
  233. void GameEngine::setEngineUser(IGameEngineUser * user)
  234. {
  235. engineUser = user;
  236. }