Input.cpp 89 KB

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