Input.cpp 71 KB

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