Input.cpp 64 KB

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