Input.cpp 64 KB

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