Input.cpp 64 KB

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