Input.cpp 82 KB

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