Input.cpp 71 KB

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