Input.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Mutex.h"
  26. #include "../Core/ProcessUtils.h"
  27. #include "../Core/Profiler.h"
  28. #include "../Core/StringUtils.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/GraphicsEvents.h"
  31. #include "../Graphics/GraphicsImpl.h"
  32. #include "../Input/Input.h"
  33. #include "../IO/FileSystem.h"
  34. #include "../IO/Log.h"
  35. #include "../IO/RWOpsWrapper.h"
  36. #include "../Resource/ResourceCache.h"
  37. #include "../UI/Text.h"
  38. #include "../UI/UI.h"
  39. #include <SDL/SDL.h>
  40. #ifdef __EMSCRIPTEN__
  41. #include <emscripten/html5.h>
  42. #endif
  43. #include "../DebugNew.h"
  44. extern "C" int SDL_AddTouch(SDL_TouchID touchID, const char* name);
  45. // Use a "click inside window to focus" mechanism on desktop platforms when the mouse cursor is hidden
  46. // TODO: For now, in this particular case only, treat all the Linux on ARM as "desktop" (e.g. RPI, odroid, etc), revisit this again when we support "mobile" Linux on ARM
  47. #if defined(_WIN32) || (defined(__APPLE__) && !defined(IOS)) || (defined(__linux__) && !defined(__ANDROID__))
  48. #define REQUIRE_CLICK_TO_FOCUS
  49. #endif
  50. namespace Urho3D
  51. {
  52. const int SCREEN_JOYSTICK_START_ID = 0x40000000;
  53. const StringHash VAR_BUTTON_KEY_BINDING("VAR_BUTTON_KEY_BINDING");
  54. const StringHash VAR_BUTTON_MOUSE_BUTTON_BINDING("VAR_BUTTON_MOUSE_BUTTON_BINDING");
  55. const StringHash VAR_LAST_KEYSYM("VAR_LAST_KEYSYM");
  56. const StringHash VAR_SCREEN_JOYSTICK_ID("VAR_SCREEN_JOYSTICK_ID");
  57. const unsigned TOUCHID_MAX = 32;
  58. /// Convert SDL keycode if necessary.
  59. int ConvertSDLKeyCode(int keySym, int scanCode)
  60. {
  61. if (scanCode == SCANCODE_AC_BACK)
  62. return KEY_ESCAPE;
  63. else
  64. return SDL_tolower(keySym);
  65. }
  66. UIElement* TouchState::GetTouchedElement()
  67. {
  68. return touchedElement_.Get();
  69. }
  70. #ifdef __EMSCRIPTEN__
  71. #define EM_TRUE 1
  72. #define EM_FALSE 0
  73. /// Glue between Urho Input and Emscripten HTML5
  74. /** HTML5 (Emscripten) is limited in the way it handles input. The EmscriptenInput class attempts to provide the glue between Urho3D Input behavior and HTML5, where SDL currently fails to do so.
  75. *
  76. * Mouse Input:
  77. * - The OS mouse cursor position can't be set.
  78. * - The mouse can be trapped within play area via 'PointerLock API', which requires a request and interaction between the user and browser.
  79. * - To request mouse lock, call SetMouseMode(MM_RELATIVE). The E_MOUSEMODECHANGED event will be sent if/when the user confirms the request.
  80. * NOTE: The request must be initiated by the user (eg: on mouse button down/up, key down/up).
  81. * - The user can press 'escape' key and browser will force user out of pointer lock. Urho will send the E_MOUSEMODECHANGED event.
  82. * - SetMouseMode(MM_ABSOLUTE) will leave pointer lock.
  83. * - MM_WRAP is unsupported.
  84. */
  85. /// % Emscripten Input glue. Intended to be used by the Input subsystem only.
  86. class EmscriptenInput
  87. {
  88. friend class Input;
  89. public:
  90. /// Constructor, expecting pointer to constructing Input instance.
  91. EmscriptenInput(Input* inputInst);
  92. /// Static callback method for Pointer Lock API. Handles change in Pointer Lock state and sends events for mouse mode change.
  93. static EM_BOOL HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent* keyEvent, void* userData);
  94. /// Static callback method for tracking focus change events.
  95. static EM_BOOL HandleFocusChange(int eventType, const EmscriptenFocusEvent* keyEvent, void* userData);
  96. /// Static callback method for suppressing mouse jump.
  97. static EM_BOOL HandleMouseJump(int eventType, const EmscriptenMouseEvent * mouseEvent, void* userData);
  98. /// Static callback method to handle SDL events.
  99. static int HandleSDLEvents(void* userData, SDL_Event* event);
  100. /// Send request to user to gain pointer lock. This requires a user-browser interaction on the first call.
  101. void RequestPointerLock(MouseMode mode, bool suppressEvent = false);
  102. /// Send request to exit pointer lock. This has the benefit of not requiring the user-browser interaction on the next pointer lock request.
  103. void ExitPointerLock(bool suppressEvent = false);
  104. /// Returns whether the page is visible.
  105. bool IsVisible();
  106. private:
  107. /// Instance of Input subsystem that constructed this instance.
  108. Input* inputInst_;
  109. /// The mouse mode being requested for pointer-lock.
  110. static MouseMode requestedMouseMode_;
  111. /// Flag indicating whether to suppress the next mouse mode change event.
  112. static bool suppressMouseModeEvent_;
  113. /// The mouse mode of the previous request for pointer-lock.
  114. static MouseMode invalidatedRequestedMouseMode_;
  115. /// Flag indicating the previous request to suppress the next mouse mode change event.
  116. static bool invalidatedSuppressMouseModeEvent_;
  117. };
  118. bool EmscriptenInput::suppressMouseModeEvent_ = false;
  119. MouseMode EmscriptenInput::requestedMouseMode_ = MM_INVALID;
  120. bool EmscriptenInput::invalidatedSuppressMouseModeEvent_ = false;
  121. MouseMode EmscriptenInput::invalidatedRequestedMouseMode_ = MM_INVALID;
  122. EmscriptenInput::EmscriptenInput(Input* inputInst) :
  123. inputInst_(inputInst)
  124. {
  125. void* vInputInst = (void*)inputInst;
  126. // Handle pointer lock
  127. emscripten_set_pointerlockchange_callback(NULL, vInputInst, false, EmscriptenInput::HandlePointerLockChange);
  128. // Handle mouse events to prevent mouse jumps
  129. emscripten_set_mousedown_callback(NULL, vInputInst, true, EmscriptenInput::HandleMouseJump);
  130. emscripten_set_mousemove_callback(NULL, vInputInst, true, EmscriptenInput::HandleMouseJump);
  131. // Handle focus changes
  132. emscripten_set_focusout_callback(NULL, vInputInst, false, EmscriptenInput::HandleFocusChange);
  133. emscripten_set_focus_callback(NULL, vInputInst, false, EmscriptenInput::HandleFocusChange);
  134. // Handle SDL events
  135. SDL_AddEventWatch(EmscriptenInput::HandleSDLEvents, vInputInst);
  136. }
  137. void EmscriptenInput::RequestPointerLock(MouseMode mode, bool suppressEvent)
  138. {
  139. requestedMouseMode_ = mode;
  140. suppressMouseModeEvent_ = suppressEvent;
  141. emscripten_request_pointerlock(NULL, true);
  142. }
  143. void EmscriptenInput::ExitPointerLock(bool suppressEvent)
  144. {
  145. if (requestedMouseMode_ != MM_INVALID)
  146. {
  147. invalidatedRequestedMouseMode_ = requestedMouseMode_;
  148. invalidatedSuppressMouseModeEvent_ = suppressMouseModeEvent_;
  149. }
  150. requestedMouseMode_ = MM_INVALID;
  151. suppressMouseModeEvent_ = suppressEvent;
  152. if (inputInst_->IsMouseLocked())
  153. {
  154. inputInst_->emscriptenExitingPointerLock_ = true;
  155. emscripten_exit_pointerlock();
  156. }
  157. }
  158. bool EmscriptenInput::IsVisible()
  159. {
  160. EmscriptenVisibilityChangeEvent visibilityStatus;
  161. if (emscripten_get_visibility_status(&visibilityStatus) >= EMSCRIPTEN_RESULT_SUCCESS)
  162. return visibilityStatus.hidden >= EM_TRUE ? false : true;
  163. // Assume visible
  164. URHO3D_LOGWARNING("Could not determine visibility status.");
  165. return true;
  166. }
  167. EM_BOOL EmscriptenInput::HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent* keyEvent, void* userData)
  168. {
  169. Input* const inputInst = (Input*)userData;
  170. bool invalid = false;
  171. const bool suppress = suppressMouseModeEvent_;
  172. if (requestedMouseMode_ == MM_INVALID && invalidatedRequestedMouseMode_ != MM_INVALID)
  173. {
  174. invalid = true;
  175. requestedMouseMode_ = invalidatedRequestedMouseMode_;
  176. suppressMouseModeEvent_ = invalidatedSuppressMouseModeEvent_;
  177. invalidatedRequestedMouseMode_ = MM_INVALID;
  178. invalidatedSuppressMouseModeEvent_ = false;
  179. }
  180. if (keyEvent->isActive >= EM_TRUE)
  181. {
  182. // Pointer Lock is now active
  183. inputInst->emscriptenPointerLock_ = true;
  184. inputInst->emscriptenEnteredPointerLock_ = true;
  185. inputInst->SetMouseModeEmscriptenFinal(requestedMouseMode_, suppressMouseModeEvent_);
  186. }
  187. else
  188. {
  189. // Pointer Lock is now inactive
  190. inputInst->emscriptenPointerLock_ = false;
  191. if (inputInst->mouseMode_ == MM_RELATIVE)
  192. inputInst->SetMouseModeEmscriptenFinal(MM_FREE, suppressMouseModeEvent_);
  193. else if (inputInst->mouseMode_ == MM_ABSOLUTE)
  194. inputInst->SetMouseModeEmscriptenFinal(MM_ABSOLUTE, suppressMouseModeEvent_);
  195. inputInst->emscriptenExitingPointerLock_ = false;
  196. }
  197. if (invalid)
  198. {
  199. if (keyEvent->isActive >= EM_TRUE)
  200. {
  201. // ExitPointerLock was called before the pointer-lock request was accepted.
  202. // Exit from pointer-lock to avoid unexpected behavior.
  203. invalidatedRequestedMouseMode_ = MM_INVALID;
  204. inputInst->emscriptenInput_->ExitPointerLock(suppress);
  205. return EM_TRUE;
  206. }
  207. }
  208. requestedMouseMode_ = MM_INVALID;
  209. suppressMouseModeEvent_ = false;
  210. invalidatedRequestedMouseMode_ = MM_INVALID;
  211. invalidatedSuppressMouseModeEvent_ = false;
  212. return EM_TRUE;
  213. }
  214. EM_BOOL EmscriptenInput::HandleFocusChange(int eventType, const EmscriptenFocusEvent* keyEvent, void* userData)
  215. {
  216. Input* const inputInst = (Input*)userData;
  217. inputInst->SuppressNextMouseMove();
  218. if (eventType == EMSCRIPTEN_EVENT_FOCUSOUT)
  219. inputInst->LoseFocus();
  220. else if (eventType == EMSCRIPTEN_EVENT_FOCUS)
  221. inputInst->GainFocus();
  222. return EM_TRUE;
  223. }
  224. EM_BOOL EmscriptenInput::HandleMouseJump(int eventType, const EmscriptenMouseEvent * mouseEvent, void* userData)
  225. {
  226. // Suppress mouse jump on pointer-lock change
  227. Input* const inputInst = (Input*)userData;
  228. bool suppress = false;
  229. if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN && inputInst->emscriptenEnteredPointerLock_)
  230. {
  231. suppress = true;
  232. inputInst->emscriptenEnteredPointerLock_ = false;
  233. }
  234. else if (eventType == EMSCRIPTEN_EVENT_MOUSEMOVE && inputInst->emscriptenExitingPointerLock_)
  235. {
  236. suppress = true;
  237. }
  238. if (suppress)
  239. inputInst->SuppressNextMouseMove();
  240. return EM_FALSE;
  241. }
  242. int EmscriptenInput::HandleSDLEvents(void* userData, SDL_Event* event)
  243. {
  244. Input* const inputInst = (Input*)userData;
  245. inputInst->HandleSDLEvent(event);
  246. return 0;
  247. }
  248. #endif
  249. void JoystickState::Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats)
  250. {
  251. buttons_.Resize(numButtons);
  252. buttonPress_.Resize(numButtons);
  253. axes_.Resize(numAxes);
  254. hats_.Resize(numHats);
  255. Reset();
  256. }
  257. void JoystickState::Reset()
  258. {
  259. for (unsigned i = 0; i < buttons_.Size(); ++i)
  260. {
  261. buttons_[i] = false;
  262. buttonPress_[i] = false;
  263. }
  264. for (unsigned i = 0; i < axes_.Size(); ++i)
  265. axes_[i] = 0.0f;
  266. for (unsigned i = 0; i < hats_.Size(); ++i)
  267. hats_[i] = HAT_CENTER;
  268. }
  269. Input::Input(Context* context) :
  270. Object(context),
  271. mouseButtonDown_(0),
  272. mouseButtonPress_(0),
  273. lastVisibleMousePosition_(MOUSE_POSITION_OFFSCREEN),
  274. mouseMoveWheel_(0),
  275. windowID_(0),
  276. toggleFullscreen_(true),
  277. mouseVisible_(false),
  278. lastMouseVisible_(false),
  279. mouseGrabbed_(false),
  280. lastMouseGrabbed_(false),
  281. mouseMode_(MM_ABSOLUTE),
  282. lastMouseMode_(MM_ABSOLUTE),
  283. #ifndef __EMSCRIPTEN__
  284. sdlMouseRelative_(false),
  285. #else
  286. emscriptenPointerLock_(false),
  287. emscriptenEnteredPointerLock_(false),
  288. emscriptenExitingPointerLock_(false),
  289. #endif
  290. touchEmulation_(false),
  291. inputFocus_(false),
  292. minimized_(false),
  293. focusedThisFrame_(false),
  294. suppressNextMouseMove_(false),
  295. inResize_(false),
  296. screenModeChanged_(false),
  297. initialized_(false)
  298. {
  299. for (int i = 0; i < TOUCHID_MAX; i++)
  300. availableTouchIDs_.Push(i);
  301. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(Input, HandleScreenMode));
  302. #if defined(__ANDROID__)
  303. SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1");
  304. #elif defined(__EMSCRIPTEN__)
  305. emscriptenInput_ = new EmscriptenInput(this);
  306. #endif
  307. // Try to initialize right now, but skip if screen mode is not yet set
  308. Initialize();
  309. }
  310. Input::~Input()
  311. {
  312. #ifdef __EMSCRIPTEN__
  313. delete emscriptenInput_;
  314. emscriptenInput_ = 0;
  315. #endif
  316. }
  317. void Input::Update()
  318. {
  319. assert(initialized_);
  320. URHO3D_PROFILE(UpdateInput);
  321. #ifndef __EMSCRIPTEN__
  322. bool mouseMoved = false;
  323. if (mouseMove_ != IntVector2::ZERO)
  324. mouseMoved = true;
  325. ResetInputAccumulation();
  326. SDL_Event evt;
  327. while (SDL_PollEvent(&evt))
  328. HandleSDLEvent(&evt);
  329. if (suppressNextMouseMove_ && (mouseMove_ != IntVector2::ZERO || mouseMoved))
  330. UnsuppressMouseMove();
  331. #endif
  332. // Check for focus change this frame
  333. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  334. unsigned flags = window ? SDL_GetWindowFlags(window) & (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS) : 0;
  335. #ifndef __EMSCRIPTEN__
  336. if (window)
  337. {
  338. #ifdef REQUIRE_CLICK_TO_FOCUS
  339. // When using the "click to focus" mechanism, only focus automatically in fullscreen or non-hidden mouse mode
  340. if (!inputFocus_ && ((mouseVisible_ || mouseMode_ == MM_FREE) || graphics_->GetFullscreen() || screenModeChanged_) && (flags & SDL_WINDOW_INPUT_FOCUS))
  341. #else
  342. if (!inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS))
  343. #endif
  344. {
  345. screenModeChanged_ = false;
  346. focusedThisFrame_ = true;
  347. }
  348. if (focusedThisFrame_)
  349. GainFocus();
  350. // Check for losing focus. The window flags are not reliable when using an external window, so prevent losing focus in that case
  351. if (inputFocus_ && !graphics_->GetExternalWindow() && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  352. LoseFocus();
  353. }
  354. else
  355. return;
  356. // Handle mouse mode MM_WRAP
  357. if (mouseVisible_ && mouseMode_ == MM_WRAP)
  358. {
  359. IntVector2 windowPos = graphics_->GetWindowPosition();
  360. IntVector2 mpos;
  361. SDL_GetGlobalMouseState(&mpos.x_, &mpos.y_);
  362. mpos -= windowPos;
  363. const int buffer = 5;
  364. const int width = graphics_->GetWidth() - buffer * 2;
  365. const int height = graphics_->GetHeight() - buffer * 2;
  366. bool warp = false;
  367. if (mpos.x_ < buffer)
  368. {
  369. warp = true;
  370. mpos.x_ += width;
  371. }
  372. if (mpos.x_ > buffer + width)
  373. {
  374. warp = true;
  375. mpos.x_ -= width;
  376. }
  377. if (mpos.y_ < buffer)
  378. {
  379. warp = true;
  380. mpos.y_ += height;
  381. }
  382. if (mpos.y_ > buffer + height)
  383. {
  384. warp = true;
  385. mpos.y_ -= height;
  386. }
  387. if (warp)
  388. {
  389. SetMousePosition(mpos);
  390. SuppressNextMouseMove();
  391. }
  392. }
  393. #else
  394. if (!window)
  395. return;
  396. #endif
  397. #ifndef __EMSCRIPTEN__
  398. if (!touchEmulation_ && (graphics_->GetExternalWindow() || ((!sdlMouseRelative_ && !mouseVisible_ && mouseMode_ != MM_FREE) && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  399. #else
  400. if (!touchEmulation_ && !emscriptenPointerLock_ && (graphics_->GetExternalWindow() || (!mouseVisible_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  401. #endif
  402. {
  403. const IntVector2 mousePosition = GetMousePosition();
  404. mouseMove_ = mousePosition - lastMousePosition_;
  405. #ifndef __EMSCRIPTEN__
  406. if (graphics_->GetExternalWindow())
  407. lastMousePosition_ = mousePosition;
  408. else
  409. {
  410. // Recenter the mouse cursor manually after move
  411. CenterMousePosition();
  412. }
  413. #else
  414. if (mouseMode_ == MM_ABSOLUTE || mouseMode_ == MM_FREE)
  415. lastMousePosition_ = mousePosition;
  416. if (emscriptenExitingPointerLock_)
  417. SuppressNextMouseMove();
  418. #endif
  419. // Send mouse move event if necessary
  420. if (mouseMove_ != IntVector2::ZERO)
  421. {
  422. if (!suppressNextMouseMove_)
  423. {
  424. using namespace MouseMove;
  425. VariantMap& eventData = GetEventDataMap();
  426. eventData[P_X] = mousePosition.x_;
  427. eventData[P_Y] = mousePosition.y_;
  428. eventData[P_DX] = mouseMove_.x_;
  429. eventData[P_DY] = mouseMove_.y_;
  430. eventData[P_BUTTONS] = mouseButtonDown_;
  431. eventData[P_QUALIFIERS] = GetQualifiers();
  432. SendEvent(E_MOUSEMOVE, eventData);
  433. }
  434. }
  435. }
  436. #ifndef __EMSCRIPTEN__
  437. else if (!touchEmulation_ && !mouseVisible_ && sdlMouseRelative_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))
  438. {
  439. // Keep the cursor trapped in window.
  440. CenterMousePosition();
  441. }
  442. #endif
  443. }
  444. void Input::SetMouseVisible(bool enable, bool suppressEvent)
  445. {
  446. const bool startMouseVisible = mouseVisible_;
  447. // In touch emulation mode only enabled mouse is allowed
  448. if (touchEmulation_)
  449. enable = true;
  450. // In mouse mode relative, the mouse should be invisible
  451. if (mouseMode_ == MM_RELATIVE)
  452. {
  453. if (!suppressEvent)
  454. lastMouseVisible_ = enable;
  455. enable = false;
  456. }
  457. // SDL Raspberry Pi "video driver" does not have proper OS mouse support yet, so no-op for now
  458. #ifndef RPI
  459. if (enable != mouseVisible_)
  460. {
  461. if (initialized_)
  462. {
  463. // External windows can only support visible mouse cursor
  464. if (graphics_->GetExternalWindow())
  465. {
  466. mouseVisible_ = true;
  467. if (!suppressEvent)
  468. lastMouseVisible_ = true;
  469. return;
  470. }
  471. if (!enable && inputFocus_)
  472. {
  473. #ifndef __EMSCRIPTEN__
  474. if (mouseVisible_)
  475. lastVisibleMousePosition_ = GetMousePosition();
  476. if (mouseMode_ == MM_ABSOLUTE)
  477. SetMouseModeAbsolute(SDL_TRUE);
  478. #else
  479. if (mouseMode_ == MM_ABSOLUTE && !emscriptenPointerLock_)
  480. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  481. #endif
  482. SDL_ShowCursor(SDL_FALSE);
  483. mouseVisible_ = false;
  484. }
  485. else if (mouseMode_ != MM_RELATIVE)
  486. {
  487. SetMouseGrabbed(false, suppressEvent);
  488. SDL_ShowCursor(SDL_TRUE);
  489. mouseVisible_ = true;
  490. #ifndef __EMSCRIPTEN__
  491. if (mouseMode_ == MM_ABSOLUTE)
  492. SetMouseModeAbsolute(SDL_FALSE);
  493. // Update cursor position
  494. UI* ui = GetSubsystem<UI>();
  495. Cursor* cursor = ui->GetCursor();
  496. // If the UI Cursor was visible, use that position instead of last visible OS cursor position
  497. if (cursor && cursor->IsVisible())
  498. {
  499. IntVector2 pos = cursor->GetScreenPosition();
  500. if (pos != MOUSE_POSITION_OFFSCREEN)
  501. {
  502. SetMousePosition(pos);
  503. lastMousePosition_ = pos;
  504. }
  505. }
  506. else
  507. {
  508. if (lastVisibleMousePosition_ != MOUSE_POSITION_OFFSCREEN)
  509. {
  510. SetMousePosition(lastVisibleMousePosition_);
  511. lastMousePosition_ = lastVisibleMousePosition_;
  512. }
  513. }
  514. #else
  515. if (mouseMode_ == MM_ABSOLUTE && emscriptenPointerLock_)
  516. emscriptenInput_->ExitPointerLock(suppressEvent);
  517. #endif
  518. }
  519. }
  520. if (mouseVisible_ != startMouseVisible)
  521. {
  522. SuppressNextMouseMove();
  523. if (!suppressEvent)
  524. {
  525. lastMouseVisible_ = mouseVisible_;
  526. using namespace MouseVisibleChanged;
  527. VariantMap& eventData = GetEventDataMap();
  528. eventData[P_VISIBLE] = mouseVisible_;
  529. SendEvent(E_MOUSEVISIBLECHANGED, eventData);
  530. }
  531. }
  532. }
  533. #endif
  534. }
  535. void Input::ResetMouseVisible()
  536. {
  537. #ifndef __EMSCRIPTEN__
  538. SetMouseVisible(lastMouseVisible_, false);
  539. #else
  540. SetMouseVisibleEmscripten(lastMouseVisible_, false);
  541. #endif
  542. }
  543. #ifdef __EMSCRIPTEN__
  544. void Input::SetMouseVisibleEmscripten(bool enable, bool suppressEvent)
  545. {
  546. if (enable != mouseVisible_)
  547. {
  548. if (mouseMode_ == MM_ABSOLUTE)
  549. {
  550. if (enable)
  551. {
  552. mouseVisible_ = true;
  553. SDL_ShowCursor(SDL_TRUE);
  554. emscriptenInput_->ExitPointerLock(suppressEvent);
  555. }
  556. else
  557. {
  558. if (emscriptenPointerLock_)
  559. {
  560. mouseVisible_ = false;
  561. SDL_ShowCursor(SDL_FALSE);
  562. }
  563. else
  564. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  565. }
  566. }
  567. else
  568. {
  569. mouseVisible_ = enable;
  570. SDL_ShowCursor(enable ? SDL_TRUE : SDL_FALSE);
  571. }
  572. }
  573. if (!suppressEvent)
  574. lastMouseVisible_ = mouseVisible_;
  575. }
  576. void Input::SetMouseModeEmscriptenFinal(MouseMode mode, bool suppressEvent)
  577. {
  578. if (!suppressEvent)
  579. lastMouseMode_ = mode;
  580. mouseMode_ = mode;
  581. if (mode == MM_ABSOLUTE)
  582. {
  583. if (emscriptenPointerLock_)
  584. {
  585. SetMouseVisibleEmscripten(false, suppressEvent);
  586. }
  587. else
  588. {
  589. SetMouseVisibleEmscripten(true, suppressEvent);
  590. }
  591. UI* const ui = GetSubsystem<UI>();
  592. Cursor* const cursor = ui->GetCursor();
  593. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  594. }
  595. else if (mode == MM_RELATIVE && emscriptenPointerLock_)
  596. {
  597. SetMouseGrabbed(true, suppressEvent);
  598. SetMouseVisibleEmscripten(false, suppressEvent);
  599. }
  600. else
  601. {
  602. SetMouseGrabbed(false, suppressEvent);
  603. }
  604. SuppressNextMouseMove();
  605. if (!suppressEvent)
  606. {
  607. VariantMap& eventData = GetEventDataMap();
  608. eventData[MouseModeChanged::P_MODE] = mode;
  609. eventData[MouseModeChanged::P_MOUSELOCKED] = IsMouseLocked();
  610. SendEvent(E_MOUSEMODECHANGED, eventData);
  611. }
  612. }
  613. void Input::SetMouseModeEmscripten(MouseMode mode, bool suppressEvent)
  614. {
  615. if (mode != mouseMode_)
  616. SuppressNextMouseMove();
  617. const MouseMode previousMode = mouseMode_;
  618. mouseMode_ = mode;
  619. UI* const ui = GetSubsystem<UI>();
  620. Cursor* const cursor = ui->GetCursor();
  621. // Handle changing from previous mode
  622. if (previousMode == MM_RELATIVE)
  623. ResetMouseVisible();
  624. // Handle changing to new mode
  625. if (mode == MM_FREE)
  626. {
  627. // Attempt to cancel pending pointer-lock requests
  628. emscriptenInput_->ExitPointerLock(suppressEvent);
  629. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  630. }
  631. else if (mode == MM_ABSOLUTE)
  632. {
  633. if (!mouseVisible_)
  634. {
  635. if (emscriptenPointerLock_)
  636. {
  637. SetMouseVisibleEmscripten(false, suppressEvent);
  638. }
  639. else
  640. {
  641. if (!cursor)
  642. SetMouseVisible(true, suppressEvent);
  643. // Deferred mouse mode change to pointer-lock callback
  644. mouseMode_ = previousMode;
  645. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  646. }
  647. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  648. }
  649. }
  650. else if (mode == MM_RELATIVE)
  651. {
  652. if (emscriptenPointerLock_)
  653. {
  654. SetMouseVisibleEmscripten(false, true);
  655. SetMouseGrabbed(!(cursor && cursor->IsVisible()), suppressEvent);
  656. }
  657. else
  658. {
  659. // Defer mouse mode change to pointer-lock callback
  660. SetMouseGrabbed(false, true);
  661. mouseMode_ = previousMode;
  662. emscriptenInput_->RequestPointerLock(MM_RELATIVE, suppressEvent);
  663. }
  664. }
  665. }
  666. #endif
  667. void Input::SetMouseGrabbed(bool grab, bool suppressEvent)
  668. {
  669. // To not interfere with touch UI operation, never report the mouse as grabbed on Android / iOS
  670. #if !defined(__ANDROID__) && !defined(IOS)
  671. mouseGrabbed_ = grab;
  672. if (!suppressEvent)
  673. lastMouseGrabbed_ = grab;
  674. #endif
  675. }
  676. void Input::ResetMouseGrabbed()
  677. {
  678. SetMouseGrabbed(lastMouseGrabbed_, true);
  679. }
  680. #ifndef __EMSCRIPTEN__
  681. void Input::SetMouseModeAbsolute(SDL_bool enable)
  682. {
  683. SDL_Window* const window = graphics_->GetImpl()->GetWindow();
  684. SDL_SetWindowGrab(window, enable);
  685. }
  686. void Input::SetMouseModeRelative(SDL_bool enable)
  687. {
  688. SDL_Window* const window = graphics_->GetImpl()->GetWindow();
  689. int result = SDL_SetRelativeMouseMode(enable);
  690. sdlMouseRelative_ = enable && (result == 0);
  691. if (result == -1)
  692. SDL_SetWindowGrab(window, enable);
  693. }
  694. #endif
  695. void Input::SetMouseMode(MouseMode mode, bool suppressEvent)
  696. {
  697. const MouseMode previousMode = mouseMode_;
  698. #ifdef __EMSCRIPTEN__
  699. SetMouseModeEmscripten(mode, suppressEvent);
  700. #else
  701. if (mode != mouseMode_)
  702. {
  703. SuppressNextMouseMove();
  704. mouseMode_ = mode;
  705. SDL_Window* const window = graphics_->GetImpl()->GetWindow();
  706. UI* const ui = GetSubsystem<UI>();
  707. Cursor* const cursor = ui->GetCursor();
  708. // Handle changing from previous mode
  709. if (previousMode == MM_ABSOLUTE)
  710. {
  711. if (!mouseVisible_)
  712. SetMouseModeAbsolute(SDL_FALSE);
  713. }
  714. if (previousMode == MM_RELATIVE)
  715. {
  716. SetMouseModeRelative(SDL_FALSE);
  717. ResetMouseVisible();
  718. }
  719. else if (previousMode == MM_WRAP)
  720. SDL_SetWindowGrab(window, SDL_FALSE);
  721. // Handle changing to new mode
  722. if (mode == MM_ABSOLUTE)
  723. {
  724. if (!mouseVisible_)
  725. SetMouseModeAbsolute(SDL_TRUE);
  726. }
  727. else if (mode == MM_RELATIVE)
  728. {
  729. SetMouseVisible(false, true);
  730. SetMouseModeRelative(SDL_TRUE);
  731. }
  732. else if (mode == MM_WRAP)
  733. {
  734. SetMouseGrabbed(true, suppressEvent);
  735. SDL_SetWindowGrab(window, SDL_TRUE);
  736. }
  737. if (mode != MM_WRAP)
  738. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  739. }
  740. #endif
  741. if (!suppressEvent)
  742. {
  743. lastMouseMode_ = mode;
  744. if (mouseMode_ != previousMode)
  745. {
  746. VariantMap& eventData = GetEventDataMap();
  747. eventData[MouseModeChanged::P_MODE] = mode;
  748. eventData[MouseModeChanged::P_MOUSELOCKED] = IsMouseLocked();
  749. SendEvent(E_MOUSEMODECHANGED, eventData);
  750. }
  751. }
  752. }
  753. void Input::ResetMouseMode()
  754. {
  755. SetMouseMode(lastMouseMode_, false);
  756. }
  757. void Input::SetToggleFullscreen(bool enable)
  758. {
  759. toggleFullscreen_ = enable;
  760. }
  761. static void PopulateKeyBindingMap(HashMap<String, int>& keyBindingMap)
  762. {
  763. if (keyBindingMap.Empty())
  764. {
  765. keyBindingMap.Insert(MakePair<String, int>("SPACE", KEY_SPACE));
  766. keyBindingMap.Insert(MakePair<String, int>("LCTRL", KEY_LCTRL));
  767. keyBindingMap.Insert(MakePair<String, int>("RCTRL", KEY_RCTRL));
  768. keyBindingMap.Insert(MakePair<String, int>("LSHIFT", KEY_LSHIFT));
  769. keyBindingMap.Insert(MakePair<String, int>("RSHIFT", KEY_RSHIFT));
  770. keyBindingMap.Insert(MakePair<String, int>("LALT", KEY_LALT));
  771. keyBindingMap.Insert(MakePair<String, int>("RALT", KEY_RALT));
  772. keyBindingMap.Insert(MakePair<String, int>("LGUI", KEY_LGUI));
  773. keyBindingMap.Insert(MakePair<String, int>("RGUI", KEY_RGUI));
  774. keyBindingMap.Insert(MakePair<String, int>("TAB", KEY_TAB));
  775. keyBindingMap.Insert(MakePair<String, int>("RETURN", KEY_RETURN));
  776. keyBindingMap.Insert(MakePair<String, int>("RETURN2", KEY_RETURN2));
  777. keyBindingMap.Insert(MakePair<String, int>("ENTER", KEY_KP_ENTER));
  778. keyBindingMap.Insert(MakePair<String, int>("SELECT", KEY_SELECT));
  779. keyBindingMap.Insert(MakePair<String, int>("LEFT", KEY_LEFT));
  780. keyBindingMap.Insert(MakePair<String, int>("RIGHT", KEY_RIGHT));
  781. keyBindingMap.Insert(MakePair<String, int>("UP", KEY_UP));
  782. keyBindingMap.Insert(MakePair<String, int>("DOWN", KEY_DOWN));
  783. keyBindingMap.Insert(MakePair<String, int>("PAGEUP", KEY_PAGEUP));
  784. keyBindingMap.Insert(MakePair<String, int>("PAGEDOWN", KEY_PAGEDOWN));
  785. keyBindingMap.Insert(MakePair<String, int>("F1", KEY_F1));
  786. keyBindingMap.Insert(MakePair<String, int>("F2", KEY_F2));
  787. keyBindingMap.Insert(MakePair<String, int>("F3", KEY_F3));
  788. keyBindingMap.Insert(MakePair<String, int>("F4", KEY_F4));
  789. keyBindingMap.Insert(MakePair<String, int>("F5", KEY_F5));
  790. keyBindingMap.Insert(MakePair<String, int>("F6", KEY_F6));
  791. keyBindingMap.Insert(MakePair<String, int>("F7", KEY_F7));
  792. keyBindingMap.Insert(MakePair<String, int>("F8", KEY_F8));
  793. keyBindingMap.Insert(MakePair<String, int>("F9", KEY_F9));
  794. keyBindingMap.Insert(MakePair<String, int>("F10", KEY_F10));
  795. keyBindingMap.Insert(MakePair<String, int>("F11", KEY_F11));
  796. keyBindingMap.Insert(MakePair<String, int>("F12", KEY_F12));
  797. }
  798. }
  799. static void PopulateMouseButtonBindingMap(HashMap<String, int>& mouseButtonBindingMap)
  800. {
  801. if (mouseButtonBindingMap.Empty())
  802. {
  803. mouseButtonBindingMap.Insert(MakePair<String, int>("LEFT", SDL_BUTTON_LEFT));
  804. mouseButtonBindingMap.Insert(MakePair<String, int>("MIDDLE", SDL_BUTTON_MIDDLE));
  805. mouseButtonBindingMap.Insert(MakePair<String, int>("RIGHT", SDL_BUTTON_RIGHT));
  806. mouseButtonBindingMap.Insert(MakePair<String, int>("X1", SDL_BUTTON_X1));
  807. mouseButtonBindingMap.Insert(MakePair<String, int>("X2", SDL_BUTTON_X2));
  808. }
  809. }
  810. SDL_JoystickID Input::AddScreenJoystick(XMLFile* layoutFile, XMLFile* styleFile)
  811. {
  812. static HashMap<String, int> keyBindingMap;
  813. static HashMap<String, int> mouseButtonBindingMap;
  814. if (!graphics_)
  815. {
  816. URHO3D_LOGWARNING("Cannot add screen joystick in headless mode");
  817. return -1;
  818. }
  819. // If layout file is not given, use the default screen joystick layout
  820. if (!layoutFile)
  821. {
  822. ResourceCache* cache = GetSubsystem<ResourceCache>();
  823. layoutFile = cache->GetResource<XMLFile>("UI/ScreenJoystick.xml");
  824. if (!layoutFile) // Error is already logged
  825. return -1;
  826. }
  827. UI* ui = GetSubsystem<UI>();
  828. SharedPtr<UIElement> screenJoystick = ui->LoadLayout(layoutFile, styleFile);
  829. if (!screenJoystick) // Error is already logged
  830. return -1;
  831. screenJoystick->SetSize(ui->GetRoot()->GetSize());
  832. ui->GetRoot()->AddChild(screenJoystick);
  833. // Get an unused ID for the screen joystick
  834. /// \todo After a real joystick has been plugged in 1073741824 times, the ranges will overlap
  835. SDL_JoystickID joystickID = SCREEN_JOYSTICK_START_ID;
  836. while (joysticks_.Contains(joystickID))
  837. ++joystickID;
  838. JoystickState& state = joysticks_[joystickID];
  839. state.joystickID_ = joystickID;
  840. state.name_ = screenJoystick->GetName();
  841. state.screenJoystick_ = screenJoystick;
  842. unsigned numButtons = 0;
  843. unsigned numAxes = 0;
  844. unsigned numHats = 0;
  845. const Vector<SharedPtr<UIElement> >& children = state.screenJoystick_->GetChildren();
  846. for (Vector<SharedPtr<UIElement> >::ConstIterator iter = children.Begin(); iter != children.End(); ++iter)
  847. {
  848. UIElement* element = iter->Get();
  849. String name = element->GetName();
  850. if (name.StartsWith("Button"))
  851. {
  852. ++numButtons;
  853. // Check whether the button has key binding
  854. Text* text = dynamic_cast<Text*>(element->GetChild("KeyBinding", false));
  855. if (text)
  856. {
  857. text->SetVisible(false);
  858. const String& key = text->GetText();
  859. int keyBinding;
  860. if (key.Length() == 1)
  861. keyBinding = key[0];
  862. else
  863. {
  864. PopulateKeyBindingMap(keyBindingMap);
  865. HashMap<String, int>::Iterator i = keyBindingMap.Find(key);
  866. if (i != keyBindingMap.End())
  867. keyBinding = i->second_;
  868. else
  869. {
  870. URHO3D_LOGERRORF("Unsupported key binding: %s", key.CString());
  871. keyBinding = M_MAX_INT;
  872. }
  873. }
  874. if (keyBinding != M_MAX_INT)
  875. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  876. }
  877. // Check whether the button has mouse button binding
  878. text = dynamic_cast<Text*>(element->GetChild("MouseButtonBinding", false));
  879. if (text)
  880. {
  881. text->SetVisible(false);
  882. const String& mouseButton = text->GetText();
  883. PopulateMouseButtonBindingMap(mouseButtonBindingMap);
  884. HashMap<String, int>::Iterator i = mouseButtonBindingMap.Find(mouseButton);
  885. if (i != mouseButtonBindingMap.End())
  886. element->SetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING, i->second_);
  887. else
  888. URHO3D_LOGERRORF("Unsupported mouse button binding: %s", mouseButton.CString());
  889. }
  890. }
  891. else if (name.StartsWith("Axis"))
  892. {
  893. ++numAxes;
  894. ///\todo Axis emulation for screen joystick is not fully supported yet.
  895. URHO3D_LOGWARNING("Axis emulation for screen joystick is not fully supported yet");
  896. }
  897. else if (name.StartsWith("Hat"))
  898. {
  899. ++numHats;
  900. Text* text = dynamic_cast<Text*>(element->GetChild("KeyBinding", false));
  901. if (text)
  902. {
  903. text->SetVisible(false);
  904. String keyBinding = text->GetText();
  905. int mappedKeyBinding[4] = {KEY_W, KEY_S, KEY_A, KEY_D};
  906. Vector<String> keyBindings;
  907. if (keyBinding.Contains(' ')) // e.g.: "UP DOWN LEFT RIGHT"
  908. keyBindings = keyBinding.Split(' '); // Attempt to split the text using ' ' as separator
  909. else if (keyBinding.Length() == 4)
  910. {
  911. keyBindings.Resize(4); // e.g.: "WSAD"
  912. for (unsigned i = 0; i < 4; ++i)
  913. keyBindings[i] = keyBinding.Substring(i, 1);
  914. }
  915. if (keyBindings.Size() == 4)
  916. {
  917. PopulateKeyBindingMap(keyBindingMap);
  918. for (unsigned j = 0; j < 4; ++j)
  919. {
  920. if (keyBindings[j].Length() == 1)
  921. mappedKeyBinding[j] = keyBindings[j][0];
  922. else
  923. {
  924. HashMap<String, int>::Iterator i = keyBindingMap.Find(keyBindings[j]);
  925. if (i != keyBindingMap.End())
  926. mappedKeyBinding[j] = i->second_;
  927. else
  928. URHO3D_LOGERRORF("%s - %s cannot be mapped, fallback to '%c'", name.CString(), keyBindings[j].CString(),
  929. mappedKeyBinding[j]);
  930. }
  931. }
  932. }
  933. else
  934. URHO3D_LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  935. element->SetVar(VAR_BUTTON_KEY_BINDING, IntRect(mappedKeyBinding));
  936. }
  937. }
  938. element->SetVar(VAR_SCREEN_JOYSTICK_ID, joystickID);
  939. }
  940. // Make sure all the children are non-focusable so they do not mistakenly to be considered as active UI input controls by application
  941. PODVector<UIElement*> allChildren;
  942. state.screenJoystick_->GetChildren(allChildren, true);
  943. for (PODVector<UIElement*>::Iterator iter = allChildren.Begin(); iter != allChildren.End(); ++iter)
  944. (*iter)->SetFocusMode(FM_NOTFOCUSABLE);
  945. state.Initialize(numButtons, numAxes, numHats);
  946. // There could be potentially more than one screen joystick, however they all will be handled by a same handler method
  947. // So there is no harm to replace the old handler with the new handler in each call to SubscribeToEvent()
  948. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  949. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  950. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  951. return joystickID;
  952. }
  953. bool Input::RemoveScreenJoystick(SDL_JoystickID id)
  954. {
  955. if (!joysticks_.Contains(id))
  956. {
  957. URHO3D_LOGERRORF("Failed to remove non-existing screen joystick ID #%d", id);
  958. return false;
  959. }
  960. JoystickState& state = joysticks_[id];
  961. if (!state.screenJoystick_)
  962. {
  963. URHO3D_LOGERRORF("Failed to remove joystick with ID #%d which is not a screen joystick", id);
  964. return false;
  965. }
  966. state.screenJoystick_->Remove();
  967. joysticks_.Erase(id);
  968. return true;
  969. }
  970. void Input::SetScreenJoystickVisible(SDL_JoystickID id, bool enable)
  971. {
  972. if (joysticks_.Contains(id))
  973. {
  974. JoystickState& state = joysticks_[id];
  975. if (state.screenJoystick_)
  976. state.screenJoystick_->SetVisible(enable);
  977. }
  978. }
  979. void Input::SetScreenKeyboardVisible(bool enable)
  980. {
  981. if (!graphics_)
  982. return;
  983. if (enable != IsScreenKeyboardVisible())
  984. {
  985. if (enable)
  986. SDL_StartTextInput();
  987. else
  988. SDL_StopTextInput();
  989. }
  990. }
  991. void Input::SetTouchEmulation(bool enable)
  992. {
  993. #if !defined(__ANDROID__) && !defined(IOS)
  994. if (enable != touchEmulation_)
  995. {
  996. if (enable)
  997. {
  998. // Touch emulation needs the mouse visible
  999. if (!mouseVisible_)
  1000. SetMouseVisible(true);
  1001. // Add a virtual touch device the first time we are enabling emulated touch
  1002. if (!SDL_GetNumTouchDevices())
  1003. SDL_AddTouch(0, "Emulated Touch");
  1004. }
  1005. else
  1006. ResetTouches();
  1007. touchEmulation_ = enable;
  1008. }
  1009. #endif
  1010. }
  1011. bool Input::RecordGesture()
  1012. {
  1013. // If have no touch devices, fail
  1014. if (!SDL_GetNumTouchDevices())
  1015. {
  1016. URHO3D_LOGERROR("Can not record gesture: no touch devices");
  1017. return false;
  1018. }
  1019. return SDL_RecordGesture(-1) != 0;
  1020. }
  1021. bool Input::SaveGestures(Serializer& dest)
  1022. {
  1023. RWOpsWrapper<Serializer> wrapper(dest);
  1024. return SDL_SaveAllDollarTemplates(wrapper.GetRWOps()) != 0;
  1025. }
  1026. bool Input::SaveGesture(Serializer& dest, unsigned gestureID)
  1027. {
  1028. RWOpsWrapper<Serializer> wrapper(dest);
  1029. return SDL_SaveDollarTemplate(gestureID, wrapper.GetRWOps()) != 0;
  1030. }
  1031. unsigned Input::LoadGestures(Deserializer& source)
  1032. {
  1033. // If have no touch devices, fail
  1034. if (!SDL_GetNumTouchDevices())
  1035. {
  1036. URHO3D_LOGERROR("Can not load gestures: no touch devices");
  1037. return 0;
  1038. }
  1039. RWOpsWrapper<Deserializer> wrapper(source);
  1040. return (unsigned)SDL_LoadDollarTemplates(-1, wrapper.GetRWOps());
  1041. }
  1042. bool Input::RemoveGesture(unsigned gestureID)
  1043. {
  1044. #ifdef __EMSCRIPTEN__
  1045. return false;
  1046. #else
  1047. return SDL_RemoveDollarTemplate(gestureID) != 0;
  1048. #endif
  1049. }
  1050. void Input::RemoveAllGestures()
  1051. {
  1052. #ifndef __EMSCRIPTEN__
  1053. SDL_RemoveAllDollarTemplates();
  1054. #endif
  1055. }
  1056. SDL_JoystickID Input::OpenJoystick(unsigned index)
  1057. {
  1058. SDL_Joystick* joystick = SDL_JoystickOpen(index);
  1059. if (!joystick)
  1060. {
  1061. URHO3D_LOGERRORF("Cannot open joystick #%d", index);
  1062. return -1;
  1063. }
  1064. // Create joystick state for the new joystick
  1065. int joystickID = SDL_JoystickInstanceID(joystick);
  1066. JoystickState& state = joysticks_[joystickID];
  1067. state.joystick_ = joystick;
  1068. state.joystickID_ = joystickID;
  1069. state.name_ = SDL_JoystickName(joystick);
  1070. if (SDL_IsGameController(index))
  1071. state.controller_ = SDL_GameControllerOpen(index);
  1072. unsigned numButtons = (unsigned)SDL_JoystickNumButtons(joystick);
  1073. unsigned numAxes = (unsigned)SDL_JoystickNumAxes(joystick);
  1074. unsigned numHats = (unsigned)SDL_JoystickNumHats(joystick);
  1075. // When the joystick is a controller, make sure there's enough axes & buttons for the standard controller mappings
  1076. if (state.controller_)
  1077. {
  1078. if (numButtons < SDL_CONTROLLER_BUTTON_MAX)
  1079. numButtons = SDL_CONTROLLER_BUTTON_MAX;
  1080. if (numAxes < SDL_CONTROLLER_AXIS_MAX)
  1081. numAxes = SDL_CONTROLLER_AXIS_MAX;
  1082. }
  1083. state.Initialize(numButtons, numAxes, numHats);
  1084. return joystickID;
  1085. }
  1086. int Input::GetKeyFromName(const String& name) const
  1087. {
  1088. return SDL_GetKeyFromName(name.CString());
  1089. }
  1090. int Input::GetKeyFromScancode(int scancode) const
  1091. {
  1092. return SDL_GetKeyFromScancode((SDL_Scancode)scancode);
  1093. }
  1094. String Input::GetKeyName(int key) const
  1095. {
  1096. return String(SDL_GetKeyName(key));
  1097. }
  1098. int Input::GetScancodeFromKey(int key) const
  1099. {
  1100. return SDL_GetScancodeFromKey(key);
  1101. }
  1102. int Input::GetScancodeFromName(const String& name) const
  1103. {
  1104. return SDL_GetScancodeFromName(name.CString());
  1105. }
  1106. String Input::GetScancodeName(int scancode) const
  1107. {
  1108. return SDL_GetScancodeName((SDL_Scancode)scancode);
  1109. }
  1110. bool Input::GetKeyDown(int key) const
  1111. {
  1112. return keyDown_.Contains(SDL_tolower(key));
  1113. }
  1114. bool Input::GetKeyPress(int key) const
  1115. {
  1116. return keyPress_.Contains(SDL_tolower(key));
  1117. }
  1118. bool Input::GetScancodeDown(int scancode) const
  1119. {
  1120. return scancodeDown_.Contains(scancode);
  1121. }
  1122. bool Input::GetScancodePress(int scancode) const
  1123. {
  1124. return scancodePress_.Contains(scancode);
  1125. }
  1126. bool Input::GetMouseButtonDown(int button) const
  1127. {
  1128. return (mouseButtonDown_ & button) != 0;
  1129. }
  1130. bool Input::GetMouseButtonPress(int button) const
  1131. {
  1132. return (mouseButtonPress_ & button) != 0;
  1133. }
  1134. bool Input::GetQualifierDown(int qualifier) const
  1135. {
  1136. if (qualifier == QUAL_SHIFT)
  1137. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  1138. if (qualifier == QUAL_CTRL)
  1139. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  1140. if (qualifier == QUAL_ALT)
  1141. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  1142. return false;
  1143. }
  1144. bool Input::GetQualifierPress(int qualifier) const
  1145. {
  1146. if (qualifier == QUAL_SHIFT)
  1147. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  1148. if (qualifier == QUAL_CTRL)
  1149. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  1150. if (qualifier == QUAL_ALT)
  1151. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  1152. return false;
  1153. }
  1154. int Input::GetQualifiers() const
  1155. {
  1156. int ret = 0;
  1157. if (GetQualifierDown(QUAL_SHIFT))
  1158. ret |= QUAL_SHIFT;
  1159. if (GetQualifierDown(QUAL_CTRL))
  1160. ret |= QUAL_CTRL;
  1161. if (GetQualifierDown(QUAL_ALT))
  1162. ret |= QUAL_ALT;
  1163. return ret;
  1164. }
  1165. IntVector2 Input::GetMousePosition() const
  1166. {
  1167. IntVector2 ret = IntVector2::ZERO;
  1168. if (!initialized_)
  1169. return ret;
  1170. SDL_GetMouseState(&ret.x_, &ret.y_);
  1171. return ret;
  1172. }
  1173. const IntVector2& Input::GetMouseMove() const
  1174. {
  1175. if (!suppressNextMouseMove_)
  1176. return mouseMove_;
  1177. else
  1178. return IntVector2::ZERO;
  1179. }
  1180. int Input::GetMouseMoveX() const
  1181. {
  1182. if (!suppressNextMouseMove_)
  1183. return mouseMove_.x_;
  1184. else
  1185. return 0;
  1186. }
  1187. int Input::GetMouseMoveY() const
  1188. {
  1189. if (!suppressNextMouseMove_)
  1190. return mouseMove_.y_;
  1191. else
  1192. return 0;
  1193. }
  1194. TouchState* Input::GetTouch(unsigned index) const
  1195. {
  1196. if (index >= touches_.Size())
  1197. return 0;
  1198. HashMap<int, TouchState>::ConstIterator i = touches_.Begin();
  1199. while (index--)
  1200. ++i;
  1201. return const_cast<TouchState*>(&i->second_);
  1202. }
  1203. JoystickState* Input::GetJoystickByIndex(unsigned index)
  1204. {
  1205. unsigned compare = 0;
  1206. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1207. {
  1208. if (compare++ == index)
  1209. return &(i->second_);
  1210. }
  1211. return 0;
  1212. }
  1213. JoystickState* Input::GetJoystickByName(const String& name)
  1214. {
  1215. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1216. {
  1217. if (i->second_.name_ == name)
  1218. return &(i->second_);
  1219. }
  1220. return 0;
  1221. }
  1222. JoystickState* Input::GetJoystick(SDL_JoystickID id)
  1223. {
  1224. HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Find(id);
  1225. return i != joysticks_.End() ? &(i->second_) : 0;
  1226. }
  1227. bool Input::IsScreenJoystickVisible(SDL_JoystickID id) const
  1228. {
  1229. HashMap<SDL_JoystickID, JoystickState>::ConstIterator i = joysticks_.Find(id);
  1230. return i != joysticks_.End() && i->second_.screenJoystick_ && i->second_.screenJoystick_->IsVisible();
  1231. }
  1232. bool Input::GetScreenKeyboardSupport() const
  1233. {
  1234. return graphics_ ? SDL_HasScreenKeyboardSupport() != 0 : false;
  1235. }
  1236. bool Input::IsScreenKeyboardVisible() const
  1237. {
  1238. if (graphics_)
  1239. {
  1240. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  1241. return SDL_IsScreenKeyboardShown(window) != SDL_FALSE;
  1242. }
  1243. else
  1244. return false;
  1245. }
  1246. bool Input::IsMouseLocked() const
  1247. {
  1248. #ifdef __EMSCRIPTEN__
  1249. return emscriptenPointerLock_;
  1250. #else
  1251. return !((mouseMode_ == MM_ABSOLUTE && mouseVisible_) || mouseMode_ == MM_FREE);
  1252. #endif
  1253. }
  1254. bool Input::IsMinimized() const
  1255. {
  1256. // Return minimized state also when unfocused in fullscreen
  1257. if (!inputFocus_ && graphics_ && graphics_->GetFullscreen())
  1258. return true;
  1259. else
  1260. return minimized_;
  1261. }
  1262. void Input::Initialize()
  1263. {
  1264. Graphics* graphics = GetSubsystem<Graphics>();
  1265. if (!graphics || !graphics->IsInitialized())
  1266. return;
  1267. graphics_ = graphics;
  1268. // In external window mode only visible mouse is supported
  1269. if (graphics_->GetExternalWindow())
  1270. mouseVisible_ = true;
  1271. // Set the initial activation
  1272. initialized_ = true;
  1273. #ifndef __EMSCRIPTEN__
  1274. GainFocus();
  1275. #else
  1276. // Note: Page visibility and focus are slightly different, however we can't query last focus with Emscripten (1.29.0)
  1277. if (emscriptenInput_->IsVisible())
  1278. GainFocus();
  1279. else
  1280. LoseFocus();
  1281. #endif
  1282. ResetJoysticks();
  1283. ResetState();
  1284. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(Input, HandleBeginFrame));
  1285. #ifdef __EMSCRIPTEN__
  1286. SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Input, HandleEndFrame));
  1287. #endif
  1288. URHO3D_LOGINFO("Initialized input");
  1289. }
  1290. void Input::ResetJoysticks()
  1291. {
  1292. joysticks_.Clear();
  1293. // Open each detected joystick automatically on startup
  1294. unsigned size = static_cast<unsigned>(SDL_NumJoysticks());
  1295. for (unsigned i = 0; i < size; ++i)
  1296. OpenJoystick(i);
  1297. }
  1298. void Input::ResetInputAccumulation()
  1299. {
  1300. // Reset input accumulation for this frame
  1301. keyPress_.Clear();
  1302. scancodePress_.Clear();
  1303. mouseButtonPress_ = 0;
  1304. mouseMove_ = IntVector2::ZERO;
  1305. mouseMoveWheel_ = 0;
  1306. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1307. {
  1308. for (unsigned j = 0; j < i->second_.buttonPress_.Size(); ++j)
  1309. i->second_.buttonPress_[j] = false;
  1310. }
  1311. // Reset touch delta movement
  1312. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  1313. {
  1314. TouchState& state = i->second_;
  1315. state.lastPosition_ = state.position_;
  1316. state.delta_ = IntVector2::ZERO;
  1317. }
  1318. }
  1319. void Input::GainFocus()
  1320. {
  1321. ResetState();
  1322. inputFocus_ = true;
  1323. focusedThisFrame_ = false;
  1324. // Restore mouse mode
  1325. #ifndef __EMSCRIPTEN__
  1326. const MouseMode mm = mouseMode_;
  1327. mouseMode_ = MM_FREE;
  1328. SetMouseMode(mm, true);
  1329. #endif
  1330. SuppressNextMouseMove();
  1331. // Re-establish mouse cursor hiding as necessary
  1332. if (!mouseVisible_)
  1333. SDL_ShowCursor(SDL_FALSE);
  1334. SendInputFocusEvent();
  1335. }
  1336. void Input::LoseFocus()
  1337. {
  1338. ResetState();
  1339. inputFocus_ = false;
  1340. focusedThisFrame_ = false;
  1341. // Show the mouse cursor when inactive
  1342. SDL_ShowCursor(SDL_TRUE);
  1343. // Change mouse mode -- removing any cursor grabs, etc.
  1344. #ifndef __EMSCRIPTEN__
  1345. const MouseMode mm = mouseMode_;
  1346. SetMouseMode(MM_FREE, true);
  1347. // Restore flags to reflect correct mouse state.
  1348. mouseMode_ = mm;
  1349. #endif
  1350. SendInputFocusEvent();
  1351. }
  1352. void Input::ResetState()
  1353. {
  1354. keyDown_.Clear();
  1355. keyPress_.Clear();
  1356. scancodeDown_.Clear();
  1357. scancodePress_.Clear();
  1358. /// \todo Check if resetting joystick state on input focus loss is even necessary
  1359. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1360. i->second_.Reset();
  1361. ResetTouches();
  1362. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  1363. SetMouseButton(MOUSEB_LEFT, false);
  1364. SetMouseButton(MOUSEB_RIGHT, false);
  1365. SetMouseButton(MOUSEB_MIDDLE, false);
  1366. mouseMove_ = IntVector2::ZERO;
  1367. mouseMoveWheel_ = 0;
  1368. mouseButtonPress_ = 0;
  1369. }
  1370. void Input::ResetTouches()
  1371. {
  1372. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  1373. {
  1374. TouchState& state = i->second_;
  1375. using namespace TouchEnd;
  1376. VariantMap& eventData = GetEventDataMap();
  1377. eventData[P_TOUCHID] = state.touchID_;
  1378. eventData[P_X] = state.position_.x_;
  1379. eventData[P_Y] = state.position_.y_;
  1380. SendEvent(E_TOUCHEND, eventData);
  1381. }
  1382. touches_.Clear();
  1383. touchIDMap_.Clear();
  1384. availableTouchIDs_.Clear();
  1385. for (int i = 0; i < TOUCHID_MAX; i++)
  1386. availableTouchIDs_.Push(i);
  1387. }
  1388. unsigned Input::GetTouchIndexFromID(int touchID)
  1389. {
  1390. HashMap<int, int>::ConstIterator i = touchIDMap_.Find(touchID);
  1391. if (i != touchIDMap_.End())
  1392. {
  1393. return (unsigned)i->second_;
  1394. }
  1395. unsigned index = PopTouchIndex();
  1396. touchIDMap_[touchID] = index;
  1397. return index;
  1398. }
  1399. unsigned Input::PopTouchIndex()
  1400. {
  1401. if (availableTouchIDs_.Empty())
  1402. return 0;
  1403. unsigned index = (unsigned)availableTouchIDs_.Front();
  1404. availableTouchIDs_.PopFront();
  1405. return index;
  1406. }
  1407. void Input::PushTouchIndex(int touchID)
  1408. {
  1409. HashMap<int, int>::ConstIterator ci = touchIDMap_.Find(touchID);
  1410. if (ci == touchIDMap_.End())
  1411. return;
  1412. int index = touchIDMap_[touchID];
  1413. touchIDMap_.Erase(touchID);
  1414. // Sorted insertion
  1415. bool inserted = false;
  1416. for (List<int>::Iterator i = availableTouchIDs_.Begin(); i != availableTouchIDs_.End(); ++i)
  1417. {
  1418. if (*i == index)
  1419. {
  1420. // This condition can occur when TOUCHID_MAX is reached.
  1421. inserted = true;
  1422. break;
  1423. }
  1424. if (*i > index)
  1425. {
  1426. availableTouchIDs_.Insert(i, index);
  1427. inserted = true;
  1428. break;
  1429. }
  1430. }
  1431. // If empty, or the lowest value then insert at end.
  1432. if (!inserted)
  1433. availableTouchIDs_.Push(index);
  1434. }
  1435. void Input::SendInputFocusEvent()
  1436. {
  1437. using namespace InputFocus;
  1438. VariantMap& eventData = GetEventDataMap();
  1439. eventData[P_FOCUS] = HasFocus();
  1440. eventData[P_MINIMIZED] = IsMinimized();
  1441. SendEvent(E_INPUTFOCUS, eventData);
  1442. }
  1443. void Input::SetMouseButton(int button, bool newState)
  1444. {
  1445. if (newState)
  1446. {
  1447. if (!(mouseButtonDown_ & button))
  1448. mouseButtonPress_ |= button;
  1449. mouseButtonDown_ |= button;
  1450. }
  1451. else
  1452. {
  1453. if (!(mouseButtonDown_ & button))
  1454. return;
  1455. mouseButtonDown_ &= ~button;
  1456. }
  1457. using namespace MouseButtonDown;
  1458. VariantMap& eventData = GetEventDataMap();
  1459. eventData[P_BUTTON] = button;
  1460. eventData[P_BUTTONS] = mouseButtonDown_;
  1461. eventData[P_QUALIFIERS] = GetQualifiers();
  1462. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  1463. }
  1464. void Input::SetKey(int key, int scancode, bool newState)
  1465. {
  1466. bool repeat = false;
  1467. if (newState)
  1468. {
  1469. scancodeDown_.Insert(scancode);
  1470. scancodePress_.Insert(scancode);
  1471. if (!keyDown_.Contains(key))
  1472. {
  1473. keyDown_.Insert(key);
  1474. keyPress_.Insert(key);
  1475. }
  1476. else
  1477. repeat = true;
  1478. }
  1479. else
  1480. {
  1481. scancodeDown_.Erase(scancode);
  1482. if (!keyDown_.Erase(key))
  1483. return;
  1484. }
  1485. using namespace KeyDown;
  1486. VariantMap& eventData = GetEventDataMap();
  1487. eventData[P_KEY] = key;
  1488. eventData[P_SCANCODE] = scancode;
  1489. eventData[P_BUTTONS] = mouseButtonDown_;
  1490. eventData[P_QUALIFIERS] = GetQualifiers();
  1491. if (newState)
  1492. eventData[P_REPEAT] = repeat;
  1493. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  1494. if ((key == KEY_RETURN || key == KEY_RETURN2 || key == KEY_KP_ENTER) && newState && !repeat && toggleFullscreen_ &&
  1495. (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  1496. graphics_->ToggleFullscreen();
  1497. }
  1498. void Input::SetMouseWheel(int delta)
  1499. {
  1500. if (delta)
  1501. {
  1502. mouseMoveWheel_ += delta;
  1503. using namespace MouseWheel;
  1504. VariantMap& eventData = GetEventDataMap();
  1505. eventData[P_WHEEL] = delta;
  1506. eventData[P_BUTTONS] = mouseButtonDown_;
  1507. eventData[P_QUALIFIERS] = GetQualifiers();
  1508. SendEvent(E_MOUSEWHEEL, eventData);
  1509. }
  1510. }
  1511. void Input::SetMousePosition(const IntVector2& position)
  1512. {
  1513. if (!graphics_)
  1514. return;
  1515. SDL_WarpMouseInWindow(graphics_->GetImpl()->GetWindow(), position.x_, position.y_);
  1516. }
  1517. void Input::CenterMousePosition()
  1518. {
  1519. const IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  1520. if (GetMousePosition() != center)
  1521. {
  1522. SetMousePosition(center);
  1523. lastMousePosition_ = center;
  1524. }
  1525. }
  1526. void Input::SuppressNextMouseMove()
  1527. {
  1528. suppressNextMouseMove_ = true;
  1529. mouseMove_ = IntVector2::ZERO;
  1530. }
  1531. void Input::UnsuppressMouseMove()
  1532. {
  1533. suppressNextMouseMove_ = false;
  1534. mouseMove_ = IntVector2::ZERO;
  1535. lastMousePosition_ = GetMousePosition();
  1536. }
  1537. void Input::HandleSDLEvent(void* sdlEvent)
  1538. {
  1539. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  1540. // While not having input focus, skip key/mouse/touch/joystick events, except for the "click to focus" mechanism
  1541. if (!inputFocus_ && evt.type >= SDL_KEYDOWN && evt.type <= SDL_MULTIGESTURE)
  1542. {
  1543. #ifdef REQUIRE_CLICK_TO_FOCUS
  1544. // Require the click to be at least 1 pixel inside the window to disregard clicks in the title bar
  1545. if (evt.type == SDL_MOUSEBUTTONDOWN && evt.button.x > 0 && evt.button.y > 0 && evt.button.x < graphics_->GetWidth() - 1 &&
  1546. evt.button.y < graphics_->GetHeight() - 1)
  1547. {
  1548. focusedThisFrame_ = true;
  1549. // Do not cause the click to actually go throughfin
  1550. return;
  1551. }
  1552. else if (evt.type == SDL_FINGERDOWN)
  1553. {
  1554. // When focusing by touch, call GainFocus() immediately as it resets the state; a touch has sustained state
  1555. // which should be kept
  1556. GainFocus();
  1557. }
  1558. else
  1559. #endif
  1560. return;
  1561. }
  1562. switch (evt.type)
  1563. {
  1564. case SDL_KEYDOWN:
  1565. #ifdef __EMSCRIPTEN__
  1566. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, true);
  1567. #else
  1568. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, true);
  1569. #endif
  1570. break;
  1571. case SDL_KEYUP:
  1572. #ifdef __EMSCRIPTEN__
  1573. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, false);
  1574. #else
  1575. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, false);
  1576. #endif
  1577. break;
  1578. case SDL_TEXTINPUT:
  1579. {
  1580. textInput_ = &evt.text.text[0];
  1581. unsigned unicode = textInput_.AtUTF8(0);
  1582. if (unicode)
  1583. {
  1584. using namespace TextInput;
  1585. VariantMap textInputEventData;
  1586. textInputEventData[P_TEXT] = textInput_;
  1587. textInputEventData[P_BUTTONS] = mouseButtonDown_;
  1588. textInputEventData[P_QUALIFIERS] = GetQualifiers();
  1589. SendEvent(E_TEXTINPUT, textInputEventData);
  1590. }
  1591. }
  1592. break;
  1593. case SDL_MOUSEBUTTONDOWN:
  1594. if (!touchEmulation_)
  1595. SetMouseButton(1 << (evt.button.button - 1), true);
  1596. else
  1597. {
  1598. int x, y;
  1599. SDL_GetMouseState(&x, &y);
  1600. SDL_Event event;
  1601. event.type = SDL_FINGERDOWN;
  1602. event.tfinger.touchId = 0;
  1603. event.tfinger.fingerId = evt.button.button - 1;
  1604. event.tfinger.pressure = 1.0f;
  1605. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1606. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1607. event.tfinger.dx = 0;
  1608. event.tfinger.dy = 0;
  1609. SDL_PushEvent(&event);
  1610. }
  1611. break;
  1612. case SDL_MOUSEBUTTONUP:
  1613. if (!touchEmulation_)
  1614. SetMouseButton(1 << (evt.button.button - 1), false);
  1615. else
  1616. {
  1617. int x, y;
  1618. SDL_GetMouseState(&x, &y);
  1619. SDL_Event event;
  1620. event.type = SDL_FINGERUP;
  1621. event.tfinger.touchId = 0;
  1622. event.tfinger.fingerId = evt.button.button - 1;
  1623. event.tfinger.pressure = 0.0f;
  1624. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1625. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1626. event.tfinger.dx = 0;
  1627. event.tfinger.dy = 0;
  1628. SDL_PushEvent(&event);
  1629. }
  1630. break;
  1631. case SDL_MOUSEMOTION:
  1632. #ifndef __EMSCRIPTEN__
  1633. if ((sdlMouseRelative_ || mouseVisible_ || mouseMode_ == MM_FREE) && !touchEmulation_)
  1634. #else
  1635. if ((mouseVisible_ || emscriptenPointerLock_ || mouseMode_ == MM_FREE) && !touchEmulation_)
  1636. #endif
  1637. {
  1638. #ifdef __EMSCRIPTEN__
  1639. if (emscriptenExitingPointerLock_)
  1640. {
  1641. SuppressNextMouseMove();
  1642. break;
  1643. }
  1644. #endif
  1645. mouseMove_.x_ += evt.motion.xrel;
  1646. mouseMove_.y_ += evt.motion.yrel;
  1647. if (!suppressNextMouseMove_)
  1648. {
  1649. using namespace MouseMove;
  1650. VariantMap& eventData = GetEventDataMap();
  1651. eventData[P_X] = evt.motion.x;
  1652. eventData[P_Y] = evt.motion.y;
  1653. eventData[P_DX] = evt.motion.xrel;
  1654. eventData[P_DY] = evt.motion.yrel;
  1655. eventData[P_BUTTONS] = mouseButtonDown_;
  1656. eventData[P_QUALIFIERS] = GetQualifiers();
  1657. SendEvent(E_MOUSEMOVE, eventData);
  1658. }
  1659. }
  1660. // Only the left mouse button "finger" moves along with the mouse movement
  1661. else if (touchEmulation_ && touches_.Contains(0))
  1662. {
  1663. int x, y;
  1664. SDL_GetMouseState(&x, &y);
  1665. SDL_Event event;
  1666. event.type = SDL_FINGERMOTION;
  1667. event.tfinger.touchId = 0;
  1668. event.tfinger.fingerId = 0;
  1669. event.tfinger.pressure = 1.0f;
  1670. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1671. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1672. event.tfinger.dx = (float)evt.motion.xrel / (float)graphics_->GetWidth();
  1673. event.tfinger.dy = (float)evt.motion.yrel / (float)graphics_->GetHeight();
  1674. SDL_PushEvent(&event);
  1675. }
  1676. break;
  1677. case SDL_MOUSEWHEEL:
  1678. if (!touchEmulation_)
  1679. SetMouseWheel(evt.wheel.y);
  1680. break;
  1681. case SDL_FINGERDOWN:
  1682. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1683. {
  1684. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffff);
  1685. TouchState& state = touches_[touchID];
  1686. state.touchID_ = touchID;
  1687. state.lastPosition_ = state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1688. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1689. state.delta_ = IntVector2::ZERO;
  1690. state.pressure_ = evt.tfinger.pressure;
  1691. using namespace TouchBegin;
  1692. VariantMap& eventData = GetEventDataMap();
  1693. eventData[P_TOUCHID] = touchID;
  1694. eventData[P_X] = state.position_.x_;
  1695. eventData[P_Y] = state.position_.y_;
  1696. eventData[P_PRESSURE] = state.pressure_;
  1697. SendEvent(E_TOUCHBEGIN, eventData);
  1698. // Finger touch may move the mouse cursor. Suppress next mouse move when cursor hidden to prevent jumps
  1699. if (!mouseVisible_)
  1700. SuppressNextMouseMove();
  1701. }
  1702. break;
  1703. case SDL_FINGERUP:
  1704. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1705. {
  1706. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffff);
  1707. TouchState& state = touches_[touchID];
  1708. using namespace TouchEnd;
  1709. VariantMap& eventData = GetEventDataMap();
  1710. // Do not trust the position in the finger up event. Instead use the last position stored in the
  1711. // touch structure
  1712. eventData[P_TOUCHID] = touchID;
  1713. eventData[P_X] = state.position_.x_;
  1714. eventData[P_Y] = state.position_.y_;
  1715. SendEvent(E_TOUCHEND, eventData);
  1716. // Add touch index back to list of available touch Ids
  1717. PushTouchIndex(evt.tfinger.fingerId & 0x7ffffff);
  1718. touches_.Erase(touchID);
  1719. }
  1720. break;
  1721. case SDL_FINGERMOTION:
  1722. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1723. {
  1724. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffff);
  1725. // We don't want this event to create a new touches_ event if it doesn't exist (touchEmulation)
  1726. if (touchEmulation_ && !touches_.Contains(touchID))
  1727. break;
  1728. TouchState& state = touches_[touchID];
  1729. state.touchID_ = touchID;
  1730. state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1731. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1732. state.delta_ = state.position_ - state.lastPosition_;
  1733. state.pressure_ = evt.tfinger.pressure;
  1734. using namespace TouchMove;
  1735. VariantMap& eventData = GetEventDataMap();
  1736. eventData[P_TOUCHID] = touchID;
  1737. eventData[P_X] = state.position_.x_;
  1738. eventData[P_Y] = state.position_.y_;
  1739. eventData[P_DX] = (int)(evt.tfinger.dx * graphics_->GetWidth());
  1740. eventData[P_DY] = (int)(evt.tfinger.dy * graphics_->GetHeight());
  1741. eventData[P_PRESSURE] = state.pressure_;
  1742. SendEvent(E_TOUCHMOVE, eventData);
  1743. // Finger touch may move the mouse cursor. Suppress next mouse move when cursor hidden to prevent jumps
  1744. if (!mouseVisible_)
  1745. SuppressNextMouseMove();
  1746. }
  1747. break;
  1748. case SDL_DOLLARRECORD:
  1749. {
  1750. using namespace GestureRecorded;
  1751. VariantMap& eventData = GetEventDataMap();
  1752. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1753. SendEvent(E_GESTURERECORDED, eventData);
  1754. }
  1755. break;
  1756. case SDL_DOLLARGESTURE:
  1757. {
  1758. using namespace GestureInput;
  1759. VariantMap& eventData = GetEventDataMap();
  1760. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1761. eventData[P_CENTERX] = (int)(evt.dgesture.x * graphics_->GetWidth());
  1762. eventData[P_CENTERY] = (int)(evt.dgesture.y * graphics_->GetHeight());
  1763. eventData[P_NUMFINGERS] = (int)evt.dgesture.numFingers;
  1764. eventData[P_ERROR] = evt.dgesture.error;
  1765. SendEvent(E_GESTUREINPUT, eventData);
  1766. }
  1767. break;
  1768. case SDL_MULTIGESTURE:
  1769. {
  1770. using namespace MultiGesture;
  1771. VariantMap& eventData = GetEventDataMap();
  1772. eventData[P_CENTERX] = (int)(evt.mgesture.x * graphics_->GetWidth());
  1773. eventData[P_CENTERY] = (int)(evt.mgesture.y * graphics_->GetHeight());
  1774. eventData[P_NUMFINGERS] = (int)evt.mgesture.numFingers;
  1775. eventData[P_DTHETA] = M_RADTODEG * evt.mgesture.dTheta;
  1776. eventData[P_DDIST] = evt.mgesture.dDist;
  1777. SendEvent(E_MULTIGESTURE, eventData);
  1778. }
  1779. break;
  1780. case SDL_JOYDEVICEADDED:
  1781. {
  1782. using namespace JoystickConnected;
  1783. SDL_JoystickID joystickID = OpenJoystick((unsigned)evt.jdevice.which);
  1784. VariantMap& eventData = GetEventDataMap();
  1785. eventData[P_JOYSTICKID] = joystickID;
  1786. SendEvent(E_JOYSTICKCONNECTED, eventData);
  1787. }
  1788. break;
  1789. case SDL_JOYDEVICEREMOVED:
  1790. {
  1791. using namespace JoystickDisconnected;
  1792. joysticks_.Erase(evt.jdevice.which);
  1793. VariantMap& eventData = GetEventDataMap();
  1794. eventData[P_JOYSTICKID] = evt.jdevice.which;
  1795. SendEvent(E_JOYSTICKDISCONNECTED, eventData);
  1796. }
  1797. break;
  1798. case SDL_JOYBUTTONDOWN:
  1799. {
  1800. using namespace JoystickButtonDown;
  1801. unsigned button = evt.jbutton.button;
  1802. SDL_JoystickID joystickID = evt.jbutton.which;
  1803. JoystickState& state = joysticks_[joystickID];
  1804. // Skip ordinary joystick event for a controller
  1805. if (!state.controller_)
  1806. {
  1807. VariantMap& eventData = GetEventDataMap();
  1808. eventData[P_JOYSTICKID] = joystickID;
  1809. eventData[P_BUTTON] = button;
  1810. if (button < state.buttons_.Size())
  1811. {
  1812. state.buttons_[button] = true;
  1813. state.buttonPress_[button] = true;
  1814. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1815. }
  1816. }
  1817. }
  1818. break;
  1819. case SDL_JOYBUTTONUP:
  1820. {
  1821. using namespace JoystickButtonUp;
  1822. unsigned button = evt.jbutton.button;
  1823. SDL_JoystickID joystickID = evt.jbutton.which;
  1824. JoystickState& state = joysticks_[joystickID];
  1825. if (!state.controller_)
  1826. {
  1827. VariantMap& eventData = GetEventDataMap();
  1828. eventData[P_JOYSTICKID] = joystickID;
  1829. eventData[P_BUTTON] = button;
  1830. if (button < state.buttons_.Size())
  1831. {
  1832. if (!state.controller_)
  1833. state.buttons_[button] = false;
  1834. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1835. }
  1836. }
  1837. }
  1838. break;
  1839. case SDL_JOYAXISMOTION:
  1840. {
  1841. using namespace JoystickAxisMove;
  1842. SDL_JoystickID joystickID = evt.jaxis.which;
  1843. JoystickState& state = joysticks_[joystickID];
  1844. if (!state.controller_)
  1845. {
  1846. VariantMap& eventData = GetEventDataMap();
  1847. eventData[P_JOYSTICKID] = joystickID;
  1848. eventData[P_AXIS] = evt.jaxis.axis;
  1849. eventData[P_POSITION] = Clamp((float)evt.jaxis.value / 32767.0f, -1.0f, 1.0f);
  1850. if (evt.jaxis.axis < state.axes_.Size())
  1851. {
  1852. // If the joystick is a controller, only use the controller axis mappings
  1853. // (we'll also get the controller event)
  1854. if (!state.controller_)
  1855. state.axes_[evt.jaxis.axis] = eventData[P_POSITION].GetFloat();
  1856. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1857. }
  1858. }
  1859. }
  1860. break;
  1861. case SDL_JOYHATMOTION:
  1862. {
  1863. using namespace JoystickHatMove;
  1864. SDL_JoystickID joystickID = evt.jaxis.which;
  1865. JoystickState& state = joysticks_[joystickID];
  1866. VariantMap& eventData = GetEventDataMap();
  1867. eventData[P_JOYSTICKID] = joystickID;
  1868. eventData[P_HAT] = evt.jhat.hat;
  1869. eventData[P_POSITION] = evt.jhat.value;
  1870. if (evt.jhat.hat < state.hats_.Size())
  1871. {
  1872. state.hats_[evt.jhat.hat] = evt.jhat.value;
  1873. SendEvent(E_JOYSTICKHATMOVE, eventData);
  1874. }
  1875. }
  1876. break;
  1877. case SDL_CONTROLLERBUTTONDOWN:
  1878. {
  1879. using namespace JoystickButtonDown;
  1880. unsigned button = evt.cbutton.button;
  1881. SDL_JoystickID joystickID = evt.cbutton.which;
  1882. JoystickState& state = joysticks_[joystickID];
  1883. VariantMap& eventData = GetEventDataMap();
  1884. eventData[P_JOYSTICKID] = joystickID;
  1885. eventData[P_BUTTON] = button;
  1886. if (button < state.buttons_.Size())
  1887. {
  1888. state.buttons_[button] = true;
  1889. state.buttonPress_[button] = true;
  1890. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1891. }
  1892. }
  1893. break;
  1894. case SDL_CONTROLLERBUTTONUP:
  1895. {
  1896. using namespace JoystickButtonUp;
  1897. unsigned button = evt.cbutton.button;
  1898. SDL_JoystickID joystickID = evt.cbutton.which;
  1899. JoystickState& state = joysticks_[joystickID];
  1900. VariantMap& eventData = GetEventDataMap();
  1901. eventData[P_JOYSTICKID] = joystickID;
  1902. eventData[P_BUTTON] = button;
  1903. if (button < state.buttons_.Size())
  1904. {
  1905. state.buttons_[button] = false;
  1906. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1907. }
  1908. }
  1909. break;
  1910. case SDL_CONTROLLERAXISMOTION:
  1911. {
  1912. using namespace JoystickAxisMove;
  1913. SDL_JoystickID joystickID = evt.caxis.which;
  1914. JoystickState& state = joysticks_[joystickID];
  1915. VariantMap& eventData = GetEventDataMap();
  1916. eventData[P_JOYSTICKID] = joystickID;
  1917. eventData[P_AXIS] = evt.caxis.axis;
  1918. eventData[P_POSITION] = Clamp((float)evt.caxis.value / 32767.0f, -1.0f, 1.0f);
  1919. if (evt.caxis.axis < state.axes_.Size())
  1920. {
  1921. state.axes_[evt.caxis.axis] = eventData[P_POSITION].GetFloat();
  1922. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1923. }
  1924. }
  1925. break;
  1926. case SDL_WINDOWEVENT:
  1927. {
  1928. switch (evt.window.event)
  1929. {
  1930. case SDL_WINDOWEVENT_MINIMIZED:
  1931. minimized_ = true;
  1932. SendInputFocusEvent();
  1933. break;
  1934. case SDL_WINDOWEVENT_MAXIMIZED:
  1935. case SDL_WINDOWEVENT_RESTORED:
  1936. #if defined(IOS) || defined (__ANDROID__)
  1937. // On iOS we never lose the GL context, but may have done GPU object changes that could not be applied yet. Apply them now
  1938. // On Android the old GL context may be lost already, restore GPU objects to the new GL context
  1939. graphics_->Restore();
  1940. #endif
  1941. minimized_ = false;
  1942. SendInputFocusEvent();
  1943. break;
  1944. case SDL_WINDOWEVENT_RESIZED:
  1945. inResize_ = true;
  1946. graphics_->OnWindowResized();
  1947. inResize_ = false;
  1948. break;
  1949. case SDL_WINDOWEVENT_MOVED:
  1950. graphics_->OnWindowMoved();
  1951. break;
  1952. default: break;
  1953. }
  1954. }
  1955. break;
  1956. case SDL_DROPFILE:
  1957. {
  1958. using namespace DropFile;
  1959. VariantMap& eventData = GetEventDataMap();
  1960. eventData[P_FILENAME] = GetInternalPath(String(evt.drop.file));
  1961. SDL_free(evt.drop.file);
  1962. SendEvent(E_DROPFILE, eventData);
  1963. }
  1964. break;
  1965. case SDL_QUIT:
  1966. SendEvent(E_EXITREQUESTED);
  1967. break;
  1968. default: break;
  1969. }
  1970. }
  1971. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1972. {
  1973. if (!initialized_)
  1974. Initialize();
  1975. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  1976. // mouse move event. Also get new window ID if it changed
  1977. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  1978. windowID_ = SDL_GetWindowID(window);
  1979. // If screen mode happens due to mouse drag resize, do not recenter the mouse as that would lead to erratic window sizes
  1980. if (!mouseVisible_ && mouseMode_ != MM_FREE && !inResize_)
  1981. {
  1982. CenterMousePosition();
  1983. focusedThisFrame_ = true;
  1984. }
  1985. else
  1986. lastMousePosition_ = GetMousePosition();
  1987. // Resize screen joysticks to new screen size
  1988. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1989. {
  1990. UIElement* screenjoystick = i->second_.screenJoystick_;
  1991. if (screenjoystick)
  1992. screenjoystick->SetSize(graphics_->GetWidth(), graphics_->GetHeight());
  1993. }
  1994. if (graphics_->GetFullscreen())
  1995. focusedThisFrame_ = true;
  1996. // After setting a new screen mode we should not be minimized
  1997. minimized_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0;
  1998. // Remember that screen mode changed in case we lose focus (needed on Linux)
  1999. if (!inResize_)
  2000. screenModeChanged_ = true;
  2001. }
  2002. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  2003. {
  2004. // Update input right at the beginning of the frame
  2005. Update();
  2006. }
  2007. #ifdef __EMSCRIPTEN__
  2008. void Input::HandleEndFrame(StringHash eventType, VariantMap& eventData)
  2009. {
  2010. if (suppressNextMouseMove_ && mouseMove_ != IntVector2::ZERO)
  2011. UnsuppressMouseMove();
  2012. ResetInputAccumulation();
  2013. }
  2014. #endif
  2015. void Input::HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData)
  2016. {
  2017. using namespace TouchBegin;
  2018. // Only interested in events from screen joystick(s)
  2019. TouchState& state = touches_[eventData[P_TOUCHID].GetInt()];
  2020. IntVector2 position(int(state.position_.x_ / GetSubsystem<UI>()->GetScale()), int(state.position_.y_ / GetSubsystem<UI>()->GetScale()));
  2021. UIElement* element = eventType == E_TOUCHBEGIN ? GetSubsystem<UI>()->GetElementAt(position) : state.touchedElement_;
  2022. if (!element)
  2023. return;
  2024. Variant variant = element->GetVar(VAR_SCREEN_JOYSTICK_ID);
  2025. if (variant.IsEmpty())
  2026. return;
  2027. SDL_JoystickID joystickID = variant.GetInt();
  2028. if (eventType == E_TOUCHEND)
  2029. state.touchedElement_.Reset();
  2030. else
  2031. state.touchedElement_ = element;
  2032. // Prepare a fake SDL event
  2033. SDL_Event evt;
  2034. const String& name = element->GetName();
  2035. if (name.StartsWith("Button"))
  2036. {
  2037. if (eventType == E_TOUCHMOVE)
  2038. return;
  2039. // Determine whether to inject a joystick event or keyboard/mouse event
  2040. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  2041. Variant mouseButtonBindingVar = element->GetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING);
  2042. if (keyBindingVar.IsEmpty() && mouseButtonBindingVar.IsEmpty())
  2043. {
  2044. evt.type = eventType == E_TOUCHBEGIN ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
  2045. evt.jbutton.which = joystickID;
  2046. evt.jbutton.button = (Uint8)ToUInt(name.Substring(6));
  2047. }
  2048. else
  2049. {
  2050. if (!keyBindingVar.IsEmpty())
  2051. {
  2052. evt.type = eventType == E_TOUCHBEGIN ? SDL_KEYDOWN : SDL_KEYUP;
  2053. evt.key.keysym.sym = ToLower(keyBindingVar.GetInt());
  2054. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2055. }
  2056. if (!mouseButtonBindingVar.IsEmpty())
  2057. {
  2058. // Mouse button are sent as extra events besides key events
  2059. // Disable touch emulation handling during this to prevent endless loop
  2060. bool oldTouchEmulation = touchEmulation_;
  2061. touchEmulation_ = false;
  2062. SDL_Event mouseEvent;
  2063. mouseEvent.type = eventType == E_TOUCHBEGIN ? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP;
  2064. mouseEvent.button.button = (Uint8)mouseButtonBindingVar.GetInt();
  2065. HandleSDLEvent(&mouseEvent);
  2066. touchEmulation_ = oldTouchEmulation;
  2067. }
  2068. }
  2069. }
  2070. else if (name.StartsWith("Hat"))
  2071. {
  2072. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  2073. if (keyBindingVar.IsEmpty())
  2074. {
  2075. evt.type = SDL_JOYHATMOTION;
  2076. evt.jaxis.which = joystickID;
  2077. evt.jhat.hat = (Uint8)ToUInt(name.Substring(3));
  2078. evt.jhat.value = HAT_CENTER;
  2079. if (eventType != E_TOUCHEND)
  2080. {
  2081. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  2082. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2083. evt.jhat.value |= HAT_UP;
  2084. if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2085. evt.jhat.value |= HAT_DOWN;
  2086. if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2087. evt.jhat.value |= HAT_LEFT;
  2088. if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2089. evt.jhat.value |= HAT_RIGHT;
  2090. }
  2091. }
  2092. else
  2093. {
  2094. // Hat is binded by 4 integers representing keysyms for 'w', 's', 'a', 'd' or something similar
  2095. IntRect keyBinding = keyBindingVar.GetIntRect();
  2096. if (eventType == E_TOUCHEND)
  2097. {
  2098. evt.type = SDL_KEYUP;
  2099. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  2100. if (!evt.key.keysym.sym)
  2101. return;
  2102. element->SetVar(VAR_LAST_KEYSYM, 0);
  2103. }
  2104. else
  2105. {
  2106. evt.type = SDL_KEYDOWN;
  2107. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  2108. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2109. evt.key.keysym.sym = keyBinding.left_; // The integers are encoded in WSAD order to l-t-r-b
  2110. else if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2111. evt.key.keysym.sym = keyBinding.top_;
  2112. else if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2113. evt.key.keysym.sym = keyBinding.right_;
  2114. else if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2115. evt.key.keysym.sym = keyBinding.bottom_;
  2116. else
  2117. return;
  2118. if (eventType == E_TOUCHMOVE && evt.key.keysym.sym != element->GetVar(VAR_LAST_KEYSYM).GetInt())
  2119. {
  2120. // Dragging past the directional boundary will cause an additional key up event for previous key symbol
  2121. SDL_Event keyEvent;
  2122. keyEvent.type = SDL_KEYUP;
  2123. keyEvent.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  2124. if (keyEvent.key.keysym.sym)
  2125. {
  2126. keyEvent.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2127. HandleSDLEvent(&keyEvent);
  2128. }
  2129. element->SetVar(VAR_LAST_KEYSYM, 0);
  2130. }
  2131. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2132. element->SetVar(VAR_LAST_KEYSYM, evt.key.keysym.sym);
  2133. }
  2134. }
  2135. }
  2136. else
  2137. return;
  2138. // Handle the fake SDL event to turn it into Urho3D genuine event
  2139. HandleSDLEvent(&evt);
  2140. }
  2141. }