Input.cpp 62 KB

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