CGuiHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * CGuiHandler.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 "CGuiHandler.h"
  12. #include "../lib/CondSh.h"
  13. #include <SDL.h>
  14. #include "CIntObject.h"
  15. #include "CCursorHandler.h"
  16. #include "../CGameInfo.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/CConfigHandler.h"
  19. #include "../CMT.h"
  20. #include "../CPlayerInterface.h"
  21. #include "../battle/CBattleInterface.h"
  22. extern std::queue<SDL_Event> SDLEventsQueue;
  23. extern boost::mutex eventsM;
  24. boost::thread_specific_ptr<bool> inGuiThread;
  25. SObjectConstruction::SObjectConstruction(CIntObject *obj)
  26. :myObj(obj)
  27. {
  28. GH.createdObj.push_front(obj);
  29. GH.captureChildren = true;
  30. }
  31. SObjectConstruction::~SObjectConstruction()
  32. {
  33. assert(GH.createdObj.size());
  34. assert(GH.createdObj.front() == myObj);
  35. GH.createdObj.pop_front();
  36. GH.captureChildren = GH.createdObj.size();
  37. }
  38. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  39. {
  40. previousCapture = GH.captureChildren;
  41. GH.captureChildren = false;
  42. prevActions = GH.defActionsDef;
  43. GH.defActionsDef = actions;
  44. }
  45. SSetCaptureState::~SSetCaptureState()
  46. {
  47. GH.captureChildren = previousCapture;
  48. GH.defActionsDef = prevActions;
  49. }
  50. static inline void
  51. processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
  52. {
  53. if (mask & flag)
  54. cb(lst);
  55. }
  56. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
  57. {
  58. processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
  59. processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
  60. processList(CIntObject::MCLICK,activityFlag,&mclickable,cb);
  61. processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
  62. processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
  63. processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
  64. processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
  65. processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
  66. processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
  67. processList(CIntObject::TEXTINPUT,activityFlag,&textInterested,cb);
  68. }
  69. void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
  70. {
  71. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  72. lst->push_front(elem);
  73. });
  74. elem->active_m |= activityFlag;
  75. }
  76. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  77. {
  78. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  79. auto hlp = std::find(lst->begin(),lst->end(),elem);
  80. assert(hlp != lst->end());
  81. lst->erase(hlp);
  82. });
  83. elem->active_m &= ~activityFlag;
  84. }
  85. void CGuiHandler::popInt(std::shared_ptr<IShowActivatable> top)
  86. {
  87. assert(listInt.front() == top);
  88. top->deactivate();
  89. disposed.push_back(top);
  90. listInt.pop_front();
  91. objsToBlit -= top;
  92. if(!listInt.empty())
  93. listInt.front()->activate();
  94. totalRedraw();
  95. pushSDLEvent(SDL_USEREVENT, EUserEvent::INTERFACE_CHANGED);
  96. }
  97. void CGuiHandler::pushInt(std::shared_ptr<IShowActivatable> newInt)
  98. {
  99. assert(newInt);
  100. assert(!vstd::contains(listInt, newInt)); // do not add same object twice
  101. //a new interface will be present, we'll need to use buffer surface (unless it's advmapint that will alter screenBuf on activate anyway)
  102. screenBuf = screen2;
  103. if(!listInt.empty())
  104. listInt.front()->deactivate();
  105. listInt.push_front(newInt);
  106. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  107. newInt->activate();
  108. objsToBlit.push_back(newInt);
  109. totalRedraw();
  110. pushSDLEvent(SDL_USEREVENT, EUserEvent::INTERFACE_CHANGED);
  111. }
  112. void CGuiHandler::popInts(int howMany)
  113. {
  114. if(!howMany) return; //senseless but who knows...
  115. assert(listInt.size() >= howMany);
  116. listInt.front()->deactivate();
  117. for(int i=0; i < howMany; i++)
  118. {
  119. objsToBlit -= listInt.front();
  120. disposed.push_back(listInt.front());
  121. listInt.pop_front();
  122. }
  123. if(!listInt.empty())
  124. {
  125. listInt.front()->activate();
  126. totalRedraw();
  127. }
  128. fakeMouseMove();
  129. pushSDLEvent(SDL_USEREVENT, EUserEvent::INTERFACE_CHANGED);
  130. }
  131. std::shared_ptr<IShowActivatable> CGuiHandler::topInt()
  132. {
  133. if(listInt.empty())
  134. return std::shared_ptr<IShowActivatable>();
  135. else
  136. return listInt.front();
  137. }
  138. void CGuiHandler::totalRedraw()
  139. {
  140. #ifdef VCMI_ANDROID
  141. SDL_FillRect(screen2, NULL, SDL_MapRGB(screen2->format, 0, 0, 0));
  142. #endif
  143. for(auto & elem : objsToBlit)
  144. elem->showAll(screen2);
  145. blitAt(screen2,0,0,screen);
  146. }
  147. void CGuiHandler::updateTime()
  148. {
  149. int ms = mainFPSmng->getElapsedMilliseconds();
  150. std::list<CIntObject*> hlp = timeinterested;
  151. for (auto & elem : hlp)
  152. {
  153. if(!vstd::contains(timeinterested,elem)) continue;
  154. (elem)->onTimer(ms);
  155. }
  156. }
  157. void CGuiHandler::handleEvents()
  158. {
  159. //player interface may want special event handling
  160. if(nullptr != LOCPLINT && LOCPLINT->capturedAllEvents())
  161. return;
  162. boost::unique_lock<boost::mutex> lock(eventsM);
  163. while(!SDLEventsQueue.empty())
  164. {
  165. continueEventHandling = true;
  166. SDL_Event ev = SDLEventsQueue.front();
  167. current = &ev;
  168. SDLEventsQueue.pop();
  169. // In a sequence of mouse motion events, skip all but the last one.
  170. // This prevents freezes when every motion event takes longer to handle than interval at which
  171. // the events arrive (like dragging on the minimap in world view, with redraw at every event)
  172. // so that the events would start piling up faster than they can be processed.
  173. if ((ev.type == SDL_MOUSEMOTION) && !SDLEventsQueue.empty() && (SDLEventsQueue.front().type == SDL_MOUSEMOTION))
  174. continue;
  175. handleCurrentEvent();
  176. }
  177. }
  178. void convertTouch(SDL_Event * current)
  179. {
  180. int rLogicalWidth, rLogicalHeight;
  181. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  182. int adjustedMouseY = (int)(current->tfinger.y * rLogicalHeight);
  183. int adjustedMouseX = (int)(current->tfinger.x * rLogicalWidth);
  184. current->button.x = adjustedMouseX;
  185. current->motion.x = adjustedMouseX;
  186. current->button.y = adjustedMouseY;
  187. current->motion.y = adjustedMouseY;
  188. }
  189. void CGuiHandler::handleCurrentEvent()
  190. {
  191. if(current->type == SDL_KEYDOWN || current->type == SDL_KEYUP)
  192. {
  193. SDL_KeyboardEvent key = current->key;
  194. if(current->type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  195. {
  196. //TODO: we need some central place for all interface-independent hotkeys
  197. Settings s = settings.write["session"];
  198. switch(key.keysym.sym)
  199. {
  200. case SDLK_F5:
  201. if(settings["session"]["spectate-locked-pim"].Bool())
  202. LOCPLINT->pim->unlock();
  203. else
  204. LOCPLINT->pim->lock();
  205. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  206. break;
  207. case SDLK_F6:
  208. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  209. break;
  210. case SDLK_F7:
  211. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  212. break;
  213. case SDLK_F8:
  214. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  215. break;
  216. case SDLK_F9:
  217. //not working yet since CClient::run remain locked after CBattleInterface removal
  218. // if(LOCPLINT->battleInt)
  219. // {
  220. // GH.popInts(1);
  221. // vstd::clear_pointer(LOCPLINT->battleInt);
  222. // }
  223. break;
  224. default:
  225. break;
  226. }
  227. return;
  228. }
  229. //translate numpad keys
  230. if(key.keysym.sym == SDLK_KP_ENTER)
  231. {
  232. key.keysym.sym = SDLK_RETURN;
  233. key.keysym.scancode = SDL_SCANCODE_RETURN;
  234. }
  235. bool keysCaptured = false;
  236. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  237. {
  238. if((*i)->captureThisEvent(key))
  239. {
  240. keysCaptured = true;
  241. break;
  242. }
  243. }
  244. std::list<CIntObject*> miCopy = keyinterested;
  245. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  246. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisEvent(key)))
  247. (**i).keyPressed(key);
  248. }
  249. else if(current->type == SDL_MOUSEMOTION)
  250. {
  251. handleMouseMotion();
  252. }
  253. else if(current->type == SDL_MOUSEBUTTONDOWN)
  254. {
  255. switch(current->button.button)
  256. {
  257. case SDL_BUTTON_LEFT:
  258. if(lastClick == current->motion && (SDL_GetTicks() - lastClickTime) < 300)
  259. {
  260. std::list<CIntObject*> hlp = doubleClickInterested;
  261. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  262. {
  263. if(!vstd::contains(doubleClickInterested, *i)) continue;
  264. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  265. {
  266. (*i)->onDoubleClick();
  267. }
  268. }
  269. }
  270. lastClick = current->motion;
  271. lastClickTime = SDL_GetTicks();
  272. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, true);
  273. break;
  274. case SDL_BUTTON_RIGHT:
  275. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  276. break;
  277. case SDL_BUTTON_MIDDLE:
  278. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, true);
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. else if(current->type == SDL_MOUSEWHEEL)
  285. {
  286. std::list<CIntObject*> hlp = wheelInterested;
  287. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  288. {
  289. if(!vstd::contains(wheelInterested,*i)) continue;
  290. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  291. int x = 0, y = 0;
  292. SDL_GetMouseState(&x, &y);
  293. (*i)->wheelScrolled(current->wheel.y < 0, isItIn(&(*i)->pos, x, y));
  294. }
  295. }
  296. else if(current->type == SDL_TEXTINPUT)
  297. {
  298. for(auto it : textInterested)
  299. {
  300. it->textInputed(current->text);
  301. }
  302. }
  303. else if(current->type == SDL_TEXTEDITING)
  304. {
  305. for(auto it : textInterested)
  306. {
  307. it->textEdited(current->edit);
  308. }
  309. }
  310. else if(current->type == SDL_MOUSEBUTTONUP)
  311. {
  312. if(!multifinger)
  313. {
  314. switch(current->button.button)
  315. {
  316. case SDL_BUTTON_LEFT:
  317. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, false);
  318. break;
  319. case SDL_BUTTON_RIGHT:
  320. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  321. break;
  322. case SDL_BUTTON_MIDDLE:
  323. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, false);
  324. break;
  325. }
  326. }
  327. }
  328. #ifndef VCMI_IOS
  329. else if(current->type == SDL_FINGERDOWN)
  330. {
  331. auto fingerCount = SDL_GetNumTouchFingers(current->tfinger.touchId);
  332. multifinger = fingerCount > 1;
  333. if(fingerCount == 2)
  334. {
  335. convertTouch(current);
  336. handleMouseMotion();
  337. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  338. }
  339. }
  340. else if(current->type == SDL_FINGERUP)
  341. {
  342. auto fingerCount = SDL_GetNumTouchFingers(current->tfinger.touchId);
  343. if(multifinger)
  344. {
  345. convertTouch(current);
  346. handleMouseMotion();
  347. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  348. multifinger = fingerCount != 0;
  349. }
  350. }
  351. #endif //VCMI_IOS
  352. current = nullptr;
  353. } //event end
  354. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntObjMouseBtnType btn, bool isPressed)
  355. {
  356. auto hlp = interestedObjs;
  357. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  358. {
  359. if(!vstd::contains(interestedObjs, *i)) continue;
  360. auto prev = (*i)->mouseState(btn);
  361. if(!isPressed)
  362. (*i)->updateMouseState(btn, isPressed);
  363. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  364. {
  365. if(isPressed)
  366. (*i)->updateMouseState(btn, isPressed);
  367. (*i)->click(btn, isPressed, prev);
  368. }
  369. else if(!isPressed)
  370. (*i)->click(btn, boost::logic::indeterminate, prev);
  371. }
  372. }
  373. void CGuiHandler::handleMouseMotion()
  374. {
  375. //sending active, hovered hoverable objects hover() call
  376. std::vector<CIntObject*> hlp;
  377. for(auto & elem : hoverable)
  378. {
  379. if(isItIn(&(elem)->pos, current->motion.x, current->motion.y))
  380. {
  381. if (!(elem)->hovered)
  382. hlp.push_back((elem));
  383. }
  384. else if ((elem)->hovered)
  385. {
  386. (elem)->hover(false);
  387. (elem)->hovered = false;
  388. }
  389. }
  390. for(auto & elem : hlp)
  391. {
  392. elem->hover(true);
  393. elem->hovered = true;
  394. }
  395. handleMoveInterested(current->motion);
  396. }
  397. void CGuiHandler::simpleRedraw()
  398. {
  399. //update only top interface and draw background
  400. if(objsToBlit.size() > 1)
  401. blitAt(screen2,0,0,screen); //blit background
  402. if(!objsToBlit.empty())
  403. objsToBlit.back()->show(screen); //blit active interface/window
  404. }
  405. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  406. {
  407. //sending active, MotionInterested objects mouseMoved() call
  408. std::list<CIntObject*> miCopy = motioninterested;
  409. for(auto & elem : miCopy)
  410. {
  411. if(elem->strongInterest || isItInOrLowerBounds(&elem->pos, motion.x, motion.y)) //checking lower bounds fixes bug #2476
  412. {
  413. (elem)->mouseMoved(motion);
  414. }
  415. }
  416. }
  417. void CGuiHandler::fakeMouseMove()
  418. {
  419. SDL_Event event;
  420. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  421. int x, y;
  422. sme.state = SDL_GetMouseState(&x, &y);
  423. sme.x = x;
  424. sme.y = y;
  425. event.motion = sme;
  426. SDL_PushEvent(&event);
  427. }
  428. void CGuiHandler::renderFrame()
  429. {
  430. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  431. // During game:
  432. // When ending the game, the pim mutex might be hold by other thread,
  433. // that will notify us about the ending game by setting terminate_cond flag.
  434. //in PreGame terminate_cond stay false
  435. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  436. while(!terminate_cond->get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  437. boost::this_thread::sleep(boost::posix_time::milliseconds(15));
  438. if(acquiredTheLockOnPim)
  439. {
  440. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  441. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  442. if(nullptr != curInt)
  443. curInt->update();
  444. if(settings["general"]["showfps"].Bool())
  445. drawFPSCounter();
  446. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  447. SDL_RenderClear(mainRenderer);
  448. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  449. CCS->curh->render();
  450. SDL_RenderPresent(mainRenderer);
  451. disposed.clear();
  452. }
  453. mainFPSmng->framerateDelay(); // holds a constant FPS
  454. }
  455. CGuiHandler::CGuiHandler()
  456. : lastClick(-500, -500),lastClickTime(0), defActionsDef(0), captureChildren(false),
  457. multifinger(false)
  458. {
  459. continueEventHandling = true;
  460. curInt = nullptr;
  461. current = nullptr;
  462. statusbar = nullptr;
  463. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  464. mainFPSmng = new CFramerateManager(48);
  465. //do not init CFramerateManager here --AVS
  466. terminate_cond = new CondSh<bool>(false);
  467. }
  468. CGuiHandler::~CGuiHandler()
  469. {
  470. delete mainFPSmng;
  471. delete terminate_cond;
  472. }
  473. void CGuiHandler::breakEventHandling()
  474. {
  475. continueEventHandling = false;
  476. }
  477. void CGuiHandler::drawFPSCounter()
  478. {
  479. const static SDL_Color yellow = {255, 255, 0, 0};
  480. static SDL_Rect overlay = { 0, 0, 64, 32};
  481. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  482. SDL_FillRect(screen, &overlay, black);
  483. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  484. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  485. }
  486. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  487. {
  488. switch(key)
  489. {
  490. case SDLK_DOWN:
  491. return SDLK_KP_2;
  492. case SDLK_UP:
  493. return SDLK_KP_8;
  494. case SDLK_LEFT:
  495. return SDLK_KP_4;
  496. case SDLK_RIGHT:
  497. return SDLK_KP_6;
  498. default:
  499. throw std::runtime_error("Wrong key!");
  500. }
  501. }
  502. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  503. {
  504. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  505. switch(key)
  506. {
  507. REMOVE_KP(0)
  508. REMOVE_KP(1)
  509. REMOVE_KP(2)
  510. REMOVE_KP(3)
  511. REMOVE_KP(4)
  512. REMOVE_KP(5)
  513. REMOVE_KP(6)
  514. REMOVE_KP(7)
  515. REMOVE_KP(8)
  516. REMOVE_KP(9)
  517. REMOVE_KP(PERIOD)
  518. REMOVE_KP(MINUS)
  519. REMOVE_KP(PLUS)
  520. REMOVE_KP(EQUALS)
  521. case SDLK_KP_MULTIPLY:
  522. return SDLK_ASTERISK;
  523. case SDLK_KP_DIVIDE:
  524. return SDLK_SLASH;
  525. case SDLK_KP_ENTER:
  526. return SDLK_RETURN;
  527. default:
  528. return SDLK_UNKNOWN;
  529. }
  530. #undef REMOVE_KP
  531. }
  532. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  533. {
  534. if(number)
  535. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  536. else
  537. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  538. }
  539. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  540. {
  541. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  542. }
  543. bool CGuiHandler::amIGuiThread()
  544. {
  545. return inGuiThread.get() && *inGuiThread;
  546. }
  547. void CGuiHandler::pushSDLEvent(int type, int usercode)
  548. {
  549. SDL_Event event;
  550. event.type = type;
  551. event.user.code = usercode; // not necessarily used
  552. SDL_PushEvent(&event);
  553. }
  554. CFramerateManager::CFramerateManager(int rate)
  555. {
  556. this->rate = rate;
  557. this->rateticks = (1000.0 / rate);
  558. this->fps = 0;
  559. this->accumulatedFrames = 0;
  560. this->accumulatedTime = 0;
  561. this->lastticks = 0;
  562. this->timeElapsed = 0;
  563. }
  564. void CFramerateManager::init()
  565. {
  566. this->lastticks = SDL_GetTicks();
  567. }
  568. void CFramerateManager::framerateDelay()
  569. {
  570. ui32 currentTicks = SDL_GetTicks();
  571. timeElapsed = currentTicks - lastticks;
  572. accumulatedFrames++;
  573. // FPS is higher than it should be, then wait some time
  574. if(timeElapsed < rateticks)
  575. {
  576. SDL_Delay((Uint32)ceil(this->rateticks) - timeElapsed);
  577. }
  578. currentTicks = SDL_GetTicks();
  579. // recalculate timeElapsed for external calls via getElapsed()
  580. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  581. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  582. lastticks = SDL_GetTicks();
  583. accumulatedTime += timeElapsed;
  584. if(accumulatedFrames >= 100)
  585. {
  586. //about 2 second should be passed
  587. fps = static_cast<int>(ceil(1000.0 / (accumulatedTime / accumulatedFrames)));
  588. accumulatedTime = 0;
  589. accumulatedFrames = 0;
  590. }
  591. }