Input.cpp 84 KB

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