Input.cpp 87 KB

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