GameEngine.cpp 8.2 KB

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