Input.cpp 69 KB

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