Input.cpp 82 KB

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