Input.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashSet.h"
  24. #include "../Core/Mutex.h"
  25. #include "../Core/Object.h"
  26. #include "../Container/List.h"
  27. #include "../Input/InputEvents.h"
  28. #include "../UI/Cursor.h"
  29. namespace Urho3D
  30. {
  31. /// %Input Mouse Modes.
  32. enum MouseMode
  33. {
  34. MM_ABSOLUTE = 0,
  35. MM_RELATIVE,
  36. MM_WRAP,
  37. MM_FREE,
  38. MM_INVALID
  39. };
  40. class Deserializer;
  41. class Graphics;
  42. class Serializer;
  43. class UIElement;
  44. class XMLFile;
  45. const IntVector2 MOUSE_POSITION_OFFSCREEN = IntVector2(M_MIN_INT, M_MIN_INT);
  46. /// %Input state for a finger touch.
  47. struct TouchState
  48. {
  49. /// Return last touched UI element, used by scripting integration.
  50. UIElement* GetTouchedElement();
  51. /// Touch (finger) ID.
  52. int touchID_;
  53. /// Position in screen coordinates.
  54. IntVector2 position_;
  55. /// Last position in screen coordinates.
  56. IntVector2 lastPosition_;
  57. /// Movement since last frame.
  58. IntVector2 delta_;
  59. /// Finger pressure.
  60. float pressure_;
  61. /// Last touched UI element from screen joystick.
  62. WeakPtr<UIElement> touchedElement_;
  63. };
  64. /// %Input state for a joystick.
  65. struct JoystickState
  66. {
  67. /// Construct with defaults.
  68. JoystickState() :
  69. joystick_(nullptr), controller_(nullptr), screenJoystick_(nullptr)
  70. {
  71. }
  72. /// Initialize the number of buttons, axes and hats and set them to neutral state.
  73. void Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats);
  74. /// Reset button, axis and hat states to neutral.
  75. void Reset();
  76. /// Return whether is a game controller. Game controllers will use standardized axis and button mappings.
  77. bool IsController() const { return controller_ != nullptr; }
  78. /// Return number of buttons.
  79. unsigned GetNumButtons() const { return buttons_.Size(); }
  80. /// Return number of axes.
  81. unsigned GetNumAxes() const { return axes_.Size(); }
  82. /// Return number of hats.
  83. unsigned GetNumHats() const { return hats_.Size(); }
  84. /// Check if a button is held down.
  85. bool GetButtonDown(unsigned index) const { return index < buttons_.Size() ? buttons_[index] : false; }
  86. /// Check if a button has been pressed on this frame.
  87. bool GetButtonPress(unsigned index) const { return index < buttonPress_.Size() ? buttonPress_[index] : false; }
  88. /// Return axis position.
  89. float GetAxisPosition(unsigned index) const { return index < axes_.Size() ? axes_[index] : 0.0f; }
  90. /// Return hat position.
  91. int GetHatPosition(unsigned index) const { return index < hats_.Size() ? hats_[index] : HAT_CENTER; }
  92. /// SDL joystick.
  93. SDL_Joystick* joystick_;
  94. /// SDL joystick instance ID.
  95. SDL_JoystickID joystickID_;
  96. /// SDL game controller.
  97. SDL_GameController* controller_;
  98. /// UI element containing the screen joystick.
  99. UIElement* screenJoystick_;
  100. /// Joystick name.
  101. String name_;
  102. /// Button up/down state.
  103. PODVector<bool> buttons_;
  104. /// Button pressed on this frame.
  105. PODVector<bool> buttonPress_;
  106. /// Axis position from -1 to 1.
  107. PODVector<float> axes_;
  108. /// POV hat bits.
  109. PODVector<int> hats_;
  110. };
  111. #ifdef __EMSCRIPTEN__
  112. class EmscriptenInput;
  113. #endif
  114. /// %Input subsystem. Converts operating system window messages to input state and events.
  115. class URHO3D_API Input : public Object
  116. {
  117. URHO3D_OBJECT(Input, Object);
  118. #ifdef __EMSCRIPTEN__
  119. friend class EmscriptenInput;
  120. #endif
  121. public:
  122. /// Construct.
  123. Input(Context* context);
  124. /// Destruct.
  125. virtual ~Input() override;
  126. /// Poll for window messages. Called by HandleBeginFrame().
  127. void Update();
  128. /// Set whether ALT-ENTER fullscreen toggle is enabled.
  129. void SetToggleFullscreen(bool enable);
  130. /// Set whether the operating system mouse cursor is visible. When not visible (default), is kept centered to prevent leaving the window. Mouse visibility event can be suppressed-- this also recalls any unsuppressed SetMouseVisible which can be returned by ResetMouseVisible().
  131. void SetMouseVisible(bool enable, bool suppressEvent = false);
  132. /// Reset last mouse visibility that was not suppressed in SetMouseVisible.
  133. void ResetMouseVisible();
  134. /// Set whether the mouse is currently being grabbed by an operation.
  135. void SetMouseGrabbed(bool grab, bool suppressEvent = false);
  136. /// Reset the mouse grabbed to the last unsuppressed SetMouseGrabbed call
  137. void ResetMouseGrabbed();
  138. /// Set the mouse mode.
  139. /** Set the mouse mode behaviour.
  140. * MM_ABSOLUTE is the default behaviour, allowing the toggling of operating system cursor visibility and allowing the cursor to escape the window when visible.
  141. * When the operating system cursor is invisible in absolute mouse mode, the mouse is confined to the window.
  142. * If the operating system and UI cursors are both invisible, interaction with the Urho UI will be limited (eg: drag move / drag end events will not trigger).
  143. * SetMouseMode(MM_ABSOLUTE) will call SetMouseGrabbed(false).
  144. *
  145. * MM_RELATIVE sets the operating system cursor to invisible and confines the cursor to the window.
  146. * The operating system cursor cannot be set to be visible in this mode via SetMouseVisible(), however changes are tracked and will be restored when another mouse mode is set.
  147. * When the virtual cursor is also invisible, UI interaction will still function as normal (eg: drag events will trigger).
  148. * SetMouseMode(MM_RELATIVE) will call SetMouseGrabbed(true).
  149. *
  150. * MM_WRAP grabs the mouse from the operating system and confines the operating system cursor to the window, wrapping the cursor when it is near the edges.
  151. * SetMouseMode(MM_WRAP) will call SetMouseGrabbed(true).
  152. *
  153. * MM_FREE does not grab/confine the mouse cursor even when it is hidden. This can be used for cases where the cursor should render using the operating system
  154. * outside the window, and perform custom rendering (with SetMouseVisible(false)) inside.
  155. */
  156. void SetMouseMode(MouseMode mode, bool suppressEvent = false);
  157. /// Reset the last mouse mode that wasn't suppressed in SetMouseMode
  158. void ResetMouseMode();
  159. /// Add screen joystick.
  160. /** Return the joystick instance ID when successful or negative on error.
  161. * If layout file is not given, use the default screen joystick layout.
  162. * If style file is not given, use the default style file from root UI element.
  163. *
  164. * This method should only be called in main thread.
  165. */
  166. SDL_JoystickID AddScreenJoystick(XMLFile* layoutFile = nullptr, XMLFile* styleFile = nullptr);
  167. /// Remove screen joystick by instance ID.
  168. /** Return true if successful.
  169. *
  170. * This method should only be called in main thread.
  171. */
  172. bool RemoveScreenJoystick(SDL_JoystickID id);
  173. /// Set whether the virtual joystick is visible.
  174. void SetScreenJoystickVisible(SDL_JoystickID id, bool enable);
  175. /// Show or hide on-screen keyboard on platforms that support it. When shown, keypresses from it are delivered as key events.
  176. void SetScreenKeyboardVisible(bool enable);
  177. /// Set touch emulation by mouse. Only available on desktop platforms. When enabled, actual mouse events are no longer sent and the mouse cursor is forced visible.
  178. void SetTouchEmulation(bool enable);
  179. /// Begin recording a touch gesture. Return true if successful. The E_GESTURERECORDED event (which contains the ID for the new gesture) will be sent when recording finishes.
  180. bool RecordGesture();
  181. /// Save all in-memory touch gestures. Return true if successful.
  182. bool SaveGestures(Serializer& dest);
  183. /// Save a specific in-memory touch gesture to a file. Return true if successful.
  184. bool SaveGesture(Serializer& dest, unsigned gestureID);
  185. /// Load touch gestures from a file. Return number of loaded gestures, or 0 on failure.
  186. unsigned LoadGestures(Deserializer& source);
  187. /// Remove an in-memory gesture by ID. Return true if was found.
  188. bool RemoveGesture(unsigned gestureID);
  189. /// Remove all in-memory gestures.
  190. void RemoveAllGestures();
  191. /// Set the mouse cursor position. Uses the backbuffer (Graphics width/height) coordinates.
  192. void SetMousePosition(const IntVector2& position);
  193. /// Center the mouse position.
  194. void CenterMousePosition();
  195. /// Return keycode from key name.
  196. int GetKeyFromName(const String& name) const;
  197. /// Return keycode from scancode.
  198. int GetKeyFromScancode(int scancode) const;
  199. /// Return name of key from keycode.
  200. String GetKeyName(int key) const;
  201. /// Return scancode from keycode.
  202. int GetScancodeFromKey(int key) const;
  203. /// Return scancode from key name.
  204. int GetScancodeFromName(const String& name) const;
  205. /// Return name of key from scancode.
  206. String GetScancodeName(int scancode) const;
  207. /// Check if a key is held down.
  208. bool GetKeyDown(int key) const;
  209. /// Check if a key has been pressed on this frame.
  210. bool GetKeyPress(int key) const;
  211. /// Check if a key is held down by scancode.
  212. bool GetScancodeDown(int scancode) const;
  213. /// Check if a key has been pressed on this frame by scancode.
  214. bool GetScancodePress(int scancode) const;
  215. /// Check if a mouse button is held down.
  216. bool GetMouseButtonDown(int button) const;
  217. /// Check if a mouse button has been pressed on this frame.
  218. bool GetMouseButtonPress(int button) const;
  219. /// Check if a qualifier key is held down.
  220. bool GetQualifierDown(int qualifier) const;
  221. /// Check if a qualifier key has been pressed on this frame.
  222. bool GetQualifierPress(int qualifier) const;
  223. /// Return the currently held down qualifiers.
  224. int GetQualifiers() const;
  225. /// Return mouse position within window. Should only be used with a visible mouse cursor. Uses the backbuffer (Graphics width/height) coordinates.
  226. IntVector2 GetMousePosition() const;
  227. /// Return mouse movement since last frame.
  228. IntVector2 GetMouseMove() const;
  229. /// Return horizontal mouse movement since last frame.
  230. int GetMouseMoveX() const;
  231. /// Return vertical mouse movement since last frame.
  232. int GetMouseMoveY() const;
  233. /// Return mouse wheel movement since last frame.
  234. int GetMouseMoveWheel() const { return mouseMoveWheel_; }
  235. /// Return input coordinate scaling. Should return non-unity on High DPI display.
  236. Vector2 GetInputScale() const { return inputScale_; }
  237. /// Return number of active finger touches.
  238. unsigned GetNumTouches() const { return touches_.Size(); }
  239. /// Return active finger touch by index.
  240. TouchState* GetTouch(unsigned index) const;
  241. /// Return number of connected joysticks.
  242. unsigned GetNumJoysticks() const { return joysticks_.Size(); }
  243. /// Return joystick state by ID, or null if does not exist.
  244. JoystickState* GetJoystick(SDL_JoystickID id);
  245. /// Return joystick state by index, or null if does not exist. 0 = first connected joystick.
  246. JoystickState* GetJoystickByIndex(unsigned index);
  247. /// Return joystick state by name, or null if does not exist.
  248. JoystickState* GetJoystickByName(const String& name);
  249. /// Return whether fullscreen toggle is enabled.
  250. bool GetToggleFullscreen() const { return toggleFullscreen_; }
  251. /// Return whether a virtual joystick is visible.
  252. bool IsScreenJoystickVisible(SDL_JoystickID id) const;
  253. /// Return whether on-screen keyboard is supported.
  254. bool GetScreenKeyboardSupport() const;
  255. /// Return whether on-screen keyboard is being shown.
  256. bool IsScreenKeyboardVisible() const;
  257. /// Return whether touch emulation is enabled.
  258. bool GetTouchEmulation() const { return touchEmulation_; }
  259. /// Return whether the operating system mouse cursor is visible.
  260. bool IsMouseVisible() const { return mouseVisible_; }
  261. /// Return whether the mouse is currently being grabbed by an operation.
  262. bool IsMouseGrabbed() const { return mouseGrabbed_; }
  263. /// Return whether the mouse is locked to the window
  264. bool IsMouseLocked() const;
  265. /// Return the mouse mode.
  266. MouseMode GetMouseMode() const { return mouseMode_; }
  267. /// Return whether application window has input focus.
  268. bool HasFocus() { return inputFocus_; }
  269. /// Return whether application window is minimized.
  270. bool IsMinimized() const;
  271. private:
  272. /// Initialize when screen mode initially set.
  273. void Initialize();
  274. /// Open a joystick and return its ID. Return -1 if no joystick.
  275. SDL_JoystickID OpenJoystick(unsigned index);
  276. /// Setup internal joystick structures.
  277. void ResetJoysticks();
  278. /// Prepare input state for application gaining input focus.
  279. void GainFocus();
  280. /// Prepare input state for application losing input focus.
  281. void LoseFocus();
  282. /// Clear input state.
  283. void ResetState();
  284. /// Clear touch states and send touch end events.
  285. void ResetTouches();
  286. /// Reset input accumulation.
  287. void ResetInputAccumulation();
  288. /// Get the index of a touch based on the touch ID.
  289. unsigned GetTouchIndexFromID(int touchID);
  290. /// Used internally to return and remove the next available touch index.
  291. unsigned PopTouchIndex();
  292. /// Push a touch index back into the list of available when finished with it.
  293. void PushTouchIndex(int touchID);
  294. /// Send an input focus or window minimization change event.
  295. void SendInputFocusEvent();
  296. /// Handle a mouse button change.
  297. void SetMouseButton(int button, bool newState);
  298. /// Handle a key change.
  299. void SetKey(int key, int scancode, bool newState);
  300. /// Handle mouse wheel change.
  301. void SetMouseWheel(int delta);
  302. /// Suppress next mouse movement.
  303. void SuppressNextMouseMove();
  304. /// Unsuppress mouse movement.
  305. void UnsuppressMouseMove();
  306. /// Handle screen mode event.
  307. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  308. /// Handle frame start event.
  309. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  310. /// Handle touch events from the controls of screen joystick(s).
  311. void HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData);
  312. /// Handle SDL event.
  313. void HandleSDLEvent(void* sdlEvent);
  314. #ifndef __EMSCRIPTEN__
  315. /// Set SDL mouse mode relative.
  316. void SetMouseModeRelative(SDL_bool enable);
  317. /// Set SDL mouse mode absolute.
  318. void SetMouseModeAbsolute(SDL_bool enable);
  319. #else
  320. /// Set whether the operating system mouse cursor is visible (Emscripten platform only).
  321. void SetMouseVisibleEmscripten(bool enable, bool suppressEvent = false);
  322. /// Set mouse mode final resolution (Emscripten platform only).
  323. void SetMouseModeEmscriptenFinal(MouseMode mode, bool suppressEvent = false);
  324. /// SetMouseMode (Emscripten platform only).
  325. void SetMouseModeEmscripten(MouseMode mode, bool suppressEvent);
  326. /// Handle frame end event.
  327. void HandleEndFrame(StringHash eventType, VariantMap& eventData);
  328. #endif
  329. /// Graphics subsystem.
  330. WeakPtr<Graphics> graphics_;
  331. /// Key down state.
  332. HashSet<int> keyDown_;
  333. /// Key pressed state.
  334. HashSet<int> keyPress_;
  335. /// Key down state by scancode.
  336. HashSet<int> scancodeDown_;
  337. /// Key pressed state by scancode.
  338. HashSet<int> scancodePress_;
  339. /// Active finger touches.
  340. HashMap<int, TouchState> touches_;
  341. /// List that maps between event touch IDs and normalised touch IDs
  342. List<int> availableTouchIDs_;
  343. /// Mapping of touch indices
  344. HashMap<int, int> touchIDMap_;
  345. /// String for text input.
  346. String textInput_;
  347. /// Opened joysticks.
  348. HashMap<SDL_JoystickID, JoystickState> joysticks_;
  349. /// Mouse buttons' down state.
  350. unsigned mouseButtonDown_;
  351. /// Mouse buttons' pressed state.
  352. unsigned mouseButtonPress_;
  353. /// Last mouse position for calculating movement.
  354. IntVector2 lastMousePosition_;
  355. /// Last mouse position before being set to not visible.
  356. IntVector2 lastVisibleMousePosition_;
  357. /// Mouse movement since last frame.
  358. IntVector2 mouseMove_;
  359. /// Mouse wheel movement since last frame.
  360. int mouseMoveWheel_;
  361. /// Input coordinate scaling. Non-unity when window and backbuffer have different sizes (e.g. Retina display.)
  362. Vector2 inputScale_;
  363. /// SDL window ID.
  364. unsigned windowID_;
  365. /// Fullscreen toggle flag.
  366. bool toggleFullscreen_;
  367. /// Operating system mouse cursor visible flag.
  368. bool mouseVisible_;
  369. /// The last operating system mouse cursor visible flag set by end use call to SetMouseVisible.
  370. bool lastMouseVisible_;
  371. /// Flag to indicate the mouse is being grabbed by an operation. Subsystems like UI that uses mouse should temporarily ignore the mouse hover or click events.
  372. bool mouseGrabbed_;
  373. /// The last mouse grabbed set by SetMouseGrabbed.
  374. bool lastMouseGrabbed_;
  375. /// Determines the mode of mouse behaviour.
  376. MouseMode mouseMode_;
  377. /// The last mouse mode set by SetMouseMode.
  378. MouseMode lastMouseMode_;
  379. #ifndef __EMSCRIPTEN__
  380. /// Flag to determine whether SDL mouse relative was used.
  381. bool sdlMouseRelative_;
  382. #endif
  383. /// Touch emulation mode flag.
  384. bool touchEmulation_;
  385. /// Input focus flag.
  386. bool inputFocus_;
  387. /// Minimized flag.
  388. bool minimized_;
  389. /// Gained focus on this frame flag.
  390. bool focusedThisFrame_;
  391. /// Next mouse move suppress flag.
  392. bool suppressNextMouseMove_;
  393. /// Whether mouse move is accumulated in backbuffer scale or not (when using events directly).
  394. bool mouseMoveScaled_;
  395. /// Initialized flag.
  396. bool initialized_;
  397. #ifdef __EMSCRIPTEN__
  398. /// Emscripten Input glue instance.
  399. UniquePtr<EmscriptenInput> emscriptenInput_;
  400. /// Flag used to detect mouse jump when exiting pointer-lock.
  401. bool emscriptenExitingPointerLock_;
  402. /// Flag used to detect mouse jump on initial mouse click when entering pointer-lock.
  403. bool emscriptenEnteredPointerLock_;
  404. /// Flag indicating current pointer-lock status.
  405. bool emscriptenPointerLock_;
  406. #endif
  407. };
  408. }