Input.cpp 84 KB

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