CGuiHandler.cpp 22 KB

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