CGuiHandler.cpp 20 KB

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