Input.cpp 69 KB

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