Input.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. #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. // ATOMIC BEGIN
  29. // #include "../UI/Cursor.h"
  30. // ATOMIC END
  31. namespace Atomic
  32. {
  33. /// %Input Mouse Modes.
  34. enum MouseMode
  35. {
  36. MM_ABSOLUTE = 0,
  37. MM_RELATIVE,
  38. MM_WRAP,
  39. MM_FREE,
  40. MM_INVALID
  41. };
  42. class Deserializer;
  43. class Graphics;
  44. class Serializer;
  45. class UIWidget;
  46. class XMLFile;
  47. const IntVector2 MOUSE_POSITION_OFFSCREEN = IntVector2(M_MIN_INT, M_MIN_INT);
  48. /// %Input state for a finger touch.
  49. struct TouchState
  50. {
  51. /// Return last touched UI element, used by scripting integration.
  52. UIWidget* GetTouchedElement();
  53. /// Touch (finger) ID.
  54. int touchID_;
  55. /// Position in screen coordinates.
  56. IntVector2 position_;
  57. /// Last position in screen coordinates.
  58. IntVector2 lastPosition_;
  59. /// Movement since last frame.
  60. IntVector2 delta_;
  61. /// Finger pressure.
  62. float pressure_;
  63. // ATOMIC BEGIN
  64. /// Last touched UI widget
  65. WeakPtr<UIWidget> touchedWidget_;
  66. // ATOMIC END
  67. };
  68. /// %Input state for a joystick.
  69. // ATOMIC BEGIN
  70. class JoystickState : public RefCounted
  71. {
  72. ATOMIC_REFCOUNTED(JoystickState)
  73. // ATOMIC END
  74. public:
  75. /// Construct with defaults.
  76. JoystickState() :
  77. joystick_(0), joystickID_(0), controller_(0),
  78. // ATOMIC BEGIN
  79. haptic_(0),
  80. canRumble_(true),
  81. // ATOMIC END
  82. name_()
  83. {
  84. }
  85. /// Initialize the number of buttons, axes and hats and set them to neutral state.
  86. void Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats);
  87. /// Reset button, axis and hat states to neutral.
  88. void Reset();
  89. /// Return whether is a game controller. Game controllers will use standardized axis and button mappings.
  90. bool IsController() const { return controller_ != 0; }
  91. /// Return number of buttons.
  92. unsigned GetNumButtons() const { return buttons_.Size(); }
  93. /// Return number of axes.
  94. unsigned GetNumAxes() const { return axes_.Size(); }
  95. /// Return number of hats.
  96. unsigned GetNumHats() const { return hats_.Size(); }
  97. /// Check if a button is held down.
  98. bool GetButtonDown(unsigned index) const { return index < buttons_.Size() ? buttons_[index] : false; }
  99. /// Check if a button has been pressed on this frame.
  100. bool GetButtonPress(unsigned index) const { return index < buttonPress_.Size() ? buttonPress_[index] : false; }
  101. /// Return axis position.
  102. float GetAxisPosition(unsigned index) const { return index < axes_.Size() ? axes_[index] : 0.0f; }
  103. /// Return hat position.
  104. int GetHatPosition(unsigned index) const { return index < hats_.Size() ? hats_[index] : HAT_CENTER; }
  105. // ATOMIC BEGIN
  106. /// Haptic aka Rumble support
  107. bool StartRumble();
  108. void StopRumble();
  109. bool IsRumble();
  110. void DoRumble( float strength, unsigned int length);
  111. // ATOMIC END
  112. /// SDL joystick.
  113. SDL_Joystick* joystick_;
  114. /// SDL joystick instance ID.
  115. SDL_JoystickID joystickID_;
  116. /// SDL game controller.
  117. SDL_GameController* controller_;
  118. // ATOMIC BEGIN
  119. /// Haptic support
  120. SDL_Haptic *haptic_;
  121. bool canRumble_;
  122. /// UI element containing the screen joystick.
  123. // UIElement* screenJoystick_;
  124. // ATOMIC END
  125. /// Joystick name.
  126. String name_;
  127. /// Button up/down state.
  128. PODVector<bool> buttons_;
  129. /// Button pressed on this frame.
  130. PODVector<bool> buttonPress_;
  131. /// Axis position from -1 to 1.
  132. PODVector<float> axes_;
  133. /// POV hat bits.
  134. PODVector<int> hats_;
  135. };
  136. #ifdef __EMSCRIPTEN__
  137. class EmscriptenInput;
  138. #endif
  139. /// %Input subsystem. Converts operating system window messages to input state and events.
  140. class ATOMIC_API Input : public Object
  141. {
  142. ATOMIC_OBJECT(Input, Object);
  143. #ifdef __EMSCRIPTEN__
  144. friend class EmscriptenInput;
  145. #endif
  146. public:
  147. /// Construct.
  148. Input(Context* context);
  149. /// Destruct.
  150. virtual ~Input();
  151. /// Poll for window messages. Called by HandleBeginFrame().
  152. void Update();
  153. /// Set whether ALT-ENTER fullscreen toggle is enabled.
  154. void SetToggleFullscreen(bool enable);
  155. /// 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().
  156. void SetMouseVisible(bool enable, bool suppressEvent = false);
  157. /// Reset last mouse visibility that was not suppressed in SetMouseVisible.
  158. void ResetMouseVisible();
  159. /// Set whether the mouse is currently being grabbed by an operation.
  160. void SetMouseGrabbed(bool grab, bool suppressEvent = false);
  161. /// Reset the mouse grabbed to the last unsuppressed SetMouseGrabbed call
  162. void ResetMouseGrabbed();
  163. /// Set the mouse mode.
  164. /** Set the mouse mode behaviour.
  165. * MM_ABSOLUTE is the default behaviour, allowing the toggling of operating system cursor visibility and allowing the cursor to escape the window when visible.
  166. * When the operating system cursor is invisible in absolute mouse mode, the mouse is confined to the window.
  167. * 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).
  168. * SetMouseMode(MM_ABSOLUTE) will call SetMouseGrabbed(false).
  169. *
  170. * MM_RELATIVE sets the operating system cursor to invisible and confines the cursor to the window.
  171. * 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.
  172. * When the virtual cursor is also invisible, UI interaction will still function as normal (eg: drag events will trigger).
  173. * SetMouseMode(MM_RELATIVE) will call SetMouseGrabbed(true).
  174. *
  175. * 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.
  176. * SetMouseMode(MM_WRAP) will call SetMouseGrabbed(true).
  177. *
  178. * 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
  179. * outside the window, and perform custom rendering (with SetMouseVisible(false)) inside.
  180. */
  181. void SetMouseMode(MouseMode mode, bool suppressEvent = false);
  182. /// Reset the last mouse mode that wasn't suppressed in SetMouseMode
  183. void ResetMouseMode();
  184. /// Add screen joystick.
  185. /** Return the joystick instance ID when successful or negative on error.
  186. * If layout file is not given, use the default screen joystick layout.
  187. * If style file is not given, use the default style file from root UI element.
  188. *
  189. * This method should only be called in main thread.
  190. */
  191. SDL_JoystickID AddScreenJoystick(XMLFile* layoutFile = 0, XMLFile* styleFile = 0);
  192. /// Remove screen joystick by instance ID.
  193. /** Return true if successful.
  194. *
  195. * This method should only be called in main thread.
  196. */
  197. bool RemoveScreenJoystick(SDL_JoystickID id);
  198. /// Set whether the virtual joystick is visible.
  199. void SetScreenJoystickVisible(SDL_JoystickID id, bool enable);
  200. /// Show or hide on-screen keyboard on platforms that support it. When shown, keypresses from it are delivered as key events.
  201. void SetScreenKeyboardVisible(bool enable);
  202. /// 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.
  203. void SetTouchEmulation(bool enable);
  204. /// 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.
  205. bool RecordGesture();
  206. /// Save all in-memory touch gestures. Return true if successful.
  207. bool SaveGestures(Serializer& dest);
  208. /// Save a specific in-memory touch gesture to a file. Return true if successful.
  209. bool SaveGesture(Serializer& dest, unsigned gestureID);
  210. /// Load touch gestures from a file. Return number of loaded gestures, or 0 on failure.
  211. unsigned LoadGestures(Deserializer& source);
  212. /// Remove an in-memory gesture by ID. Return true if was found.
  213. bool RemoveGesture(unsigned gestureID);
  214. /// Remove all in-memory gestures.
  215. void RemoveAllGestures();
  216. /// Return keycode from key name.
  217. int GetKeyFromName(const String& name) const;
  218. /// Return keycode from scancode.
  219. int GetKeyFromScancode(int scancode) const;
  220. /// Return name of key from keycode.
  221. String GetKeyName(int key) const;
  222. /// Return scancode from keycode.
  223. int GetScancodeFromKey(int key) const;
  224. /// Return scancode from key name.
  225. int GetScancodeFromName(const String& name) const;
  226. /// Return name of key from scancode.
  227. String GetScancodeName(int scancode) const;
  228. /// Check if a key is held down.
  229. bool GetKeyDown(int key) const;
  230. /// Check if a key has been pressed on this frame.
  231. bool GetKeyPress(int key) const;
  232. /// Check if a key is held down by scancode.
  233. bool GetScancodeDown(int scancode) const;
  234. /// Check if a key has been pressed on this frame by scancode.
  235. bool GetScancodePress(int scancode) const;
  236. /// Check if a mouse button is held down.
  237. bool GetMouseButtonDown(int button) const;
  238. /// Check if a mouse button has been pressed on this frame.
  239. bool GetMouseButtonPress(int button) const;
  240. /// Check if a qualifier key is held down.
  241. bool GetQualifierDown(int qualifier) const;
  242. /// Check if a qualifier key has been pressed on this frame.
  243. bool GetQualifierPress(int qualifier) const;
  244. /// Return the currently held down qualifiers.
  245. int GetQualifiers() const;
  246. /// Return mouse position within window. Should only be used with a visible mouse cursor.
  247. IntVector2 GetMousePosition() const;
  248. /// Return mouse movement since last frame.
  249. const IntVector2& GetMouseMove() const;
  250. /// Return horizontal mouse movement since last frame.
  251. int GetMouseMoveX() const;
  252. /// Return vertical mouse movement since last frame.
  253. int GetMouseMoveY() const;
  254. /// Return mouse wheel movement since last frame.
  255. int GetMouseMoveWheel() const { return mouseMoveWheel_; }
  256. /// Return number of active finger touches.
  257. unsigned GetNumTouches() const { return touches_.Size(); }
  258. /// Return active finger touch by index.
  259. TouchState* GetTouch(unsigned index) const;
  260. /// Return number of connected joysticks.
  261. unsigned GetNumJoysticks() const { return joysticks_.Size(); }
  262. /// Return joystick state by ID, or null if does not exist.
  263. JoystickState* GetJoystick(SDL_JoystickID id);
  264. /// Return joystick state by index, or null if does not exist. 0 = first connected joystick.
  265. JoystickState* GetJoystickByIndex(unsigned index);
  266. /// Return joystick state by name, or null if does not exist.
  267. JoystickState* GetJoystickByName(const String& name);
  268. /// Return whether fullscreen toggle is enabled.
  269. bool GetToggleFullscreen() const { return toggleFullscreen_; }
  270. /// Return whether a virtual joystick is visible.
  271. bool IsScreenJoystickVisible(SDL_JoystickID id) const;
  272. /// Return whether on-screen keyboard is supported.
  273. bool GetScreenKeyboardSupport() const;
  274. /// Return whether on-screen keyboard is being shown.
  275. bool IsScreenKeyboardVisible() const;
  276. /// Return whether touch emulation is enabled.
  277. bool GetTouchEmulation() const { return touchEmulation_; }
  278. /// Return whether the operating system mouse cursor is visible.
  279. bool IsMouseVisible() const { return mouseVisible_; }
  280. /// Return whether the mouse is currently being grabbed by an operation.
  281. bool IsMouseGrabbed() const { return mouseGrabbed_; }
  282. /// Return whether the mouse is locked to the window
  283. bool IsMouseLocked() const;
  284. /// Return the mouse mode.
  285. MouseMode GetMouseMode() const { return mouseMode_; }
  286. /// Return whether application window has input focus.
  287. bool HasFocus() { return inputFocus_; }
  288. /// Return whether application window is minimized.
  289. bool IsMinimized() const;
  290. // ATOMIC BEGIN
  291. void SimulateButtonDown(int button);
  292. void SimulateButtonUp(int button);
  293. bool GetJoystickRumble(unsigned int id); /// return if rumble is supported on game controller
  294. void JoystickRumble(unsigned int id, float strength, unsigned int length); /// produce rumble
  295. void JoystickSimulateMouseMove(int xpos, int ypos); /// moves the on screen cursor
  296. void JoystickSimulateMouseButton(int button); /// simulated mouse press down & up
  297. int GetTouchID(unsigned index) { if (index >= touches_.Size()) return 0; return touches_[index].touchID_; }
  298. const IntVector2& GetTouchPosition(unsigned index) { if (index >= touches_.Size()) return IntVector2::ZERO; return touches_[index].position_; }
  299. const IntVector2& GetTouchLastPosition(unsigned index) { if (index >= touches_.Size()) return IntVector2::ZERO; return touches_[index].lastPosition_; }
  300. const IntVector2& GetTouchDelta(unsigned index) { if (index >= touches_.Size()) return IntVector2::ZERO; return touches_[index].delta_; }
  301. const float GetTouchPressure(unsigned index) { if (index >= touches_.Size()) return 0.0f; return touches_[index].pressure_; }
  302. UIWidget* GetTouchWidget(unsigned index) { if (index >= touches_.Size()) return 0; return touches_[index].touchedWidget_; }
  303. // ATOMIC END
  304. private:
  305. /// Initialize when screen mode initially set.
  306. void Initialize();
  307. /// Open a joystick and return its ID. Return -1 if no joystick.
  308. SDL_JoystickID OpenJoystick(unsigned index);
  309. /// Setup internal joystick structures.
  310. void ResetJoysticks();
  311. /// Prepare input state for application gaining input focus.
  312. void GainFocus();
  313. /// Prepare input state for application losing input focus.
  314. void LoseFocus();
  315. /// Clear input state.
  316. void ResetState();
  317. /// Clear touch states and send touch end events.
  318. void ResetTouches();
  319. /// Reset input accumulation.
  320. void ResetInputAccumulation();
  321. /// Get the index of a touch based on the touch ID.
  322. unsigned GetTouchIndexFromID(int touchID);
  323. /// Used internally to return and remove the next available touch index.
  324. unsigned PopTouchIndex();
  325. /// Push a touch index back into the list of available when finished with it.
  326. void PushTouchIndex(int touchID);
  327. /// Send an input focus or window minimization change event.
  328. void SendInputFocusEvent();
  329. /// Handle a mouse button change.
  330. void SetMouseButton(int button, bool newState);
  331. /// Handle a key change.
  332. void SetKey(int key, int scancode, bool newState);
  333. /// Handle mouse wheel change.
  334. void SetMouseWheel(int delta);
  335. /// Internal function to set the mouse cursor position.
  336. void SetMousePosition(const IntVector2& position);
  337. /// Center the mouse position.
  338. void CenterMousePosition();
  339. /// Suppress next mouse movement.
  340. void SuppressNextMouseMove();
  341. /// Unsuppress mouse movement.
  342. void UnsuppressMouseMove();
  343. /// Handle screen mode event.
  344. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  345. /// Handle frame start event.
  346. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  347. /// Handle touch events from the controls of screen joystick(s).
  348. void HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData);
  349. /// Handle SDL event.
  350. void HandleSDLEvent(void* sdlEvent);
  351. #ifndef __EMSCRIPTEN__
  352. /// Set SDL mouse mode relative.
  353. void SetMouseModeRelative(SDL_bool enable);
  354. /// Set SDL mouse mode absolute.
  355. void SetMouseModeAbsolute(SDL_bool enable);
  356. #else
  357. /// Set whether the operating system mouse cursor is visible (Emscripten platform only).
  358. void SetMouseVisibleEmscripten(bool enable, bool suppressEvent = false);
  359. /// Set mouse mode final resolution (Emscripten platform only).
  360. void SetMouseModeEmscriptenFinal(MouseMode mode, bool suppressEvent = false);
  361. /// SetMouseMode (Emscripten platform only).
  362. void SetMouseModeEmscripten(MouseMode mode, bool suppressEvent);
  363. /// Handle frame end event.
  364. void HandleEndFrame(StringHash eventType, VariantMap& eventData);
  365. #endif
  366. /// Graphics subsystem.
  367. WeakPtr<Graphics> graphics_;
  368. /// Key down state.
  369. HashSet<int> keyDown_;
  370. /// Key pressed state.
  371. HashSet<int> keyPress_;
  372. /// Key down state by scancode.
  373. HashSet<int> scancodeDown_;
  374. /// Key pressed state by scancode.
  375. HashSet<int> scancodePress_;
  376. /// Active finger touches.
  377. HashMap<int, TouchState> touches_;
  378. /// List that maps between event touch IDs and normalised touch IDs
  379. List<int> availableTouchIDs_;
  380. /// Mapping of touch indices
  381. HashMap<int, int> touchIDMap_;
  382. /// String for text input.
  383. String textInput_;
  384. // ATOMIC BEGIN
  385. /// Opened joysticks.
  386. HashMap<SDL_JoystickID, SharedPtr<JoystickState>> joysticks_;
  387. // ATOMIC END
  388. /// Mouse buttons' down state.
  389. unsigned mouseButtonDown_;
  390. /// Mouse buttons' pressed state.
  391. unsigned mouseButtonPress_;
  392. /// Last mouse position for calculating movement.
  393. IntVector2 lastMousePosition_;
  394. /// Last mouse position before being set to not visible.
  395. IntVector2 lastVisibleMousePosition_;
  396. /// Mouse movement since last frame.
  397. IntVector2 mouseMove_;
  398. /// Mouse wheel movement since last frame.
  399. int mouseMoveWheel_;
  400. /// SDL window ID.
  401. unsigned windowID_;
  402. /// Fullscreen toggle flag.
  403. bool toggleFullscreen_;
  404. /// Operating system mouse cursor visible flag.
  405. bool mouseVisible_;
  406. /// The last operating system mouse cursor visible flag set by end use call to SetMouseVisible.
  407. bool lastMouseVisible_;
  408. /// 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.
  409. bool mouseGrabbed_;
  410. /// The last mouse grabbed set by SetMouseGrabbed.
  411. bool lastMouseGrabbed_;
  412. /// Determines the mode of mouse behaviour.
  413. MouseMode mouseMode_;
  414. /// The last mouse mode set by SetMouseMode.
  415. MouseMode lastMouseMode_;
  416. #ifndef __EMSCRIPTEN__
  417. /// Flag to determine whether SDL mouse relative was used.
  418. bool sdlMouseRelative_;
  419. #endif
  420. /// Touch emulation mode flag.
  421. bool touchEmulation_;
  422. /// Input focus flag.
  423. bool inputFocus_;
  424. /// Minimized flag.
  425. bool minimized_;
  426. /// Gained focus on this frame flag.
  427. bool focusedThisFrame_;
  428. /// Next mouse move suppress flag.
  429. bool suppressNextMouseMove_;
  430. /// Handling a window resize event flag.
  431. bool inResize_;
  432. /// Flag for automatic focus (without click inside window) after screen mode change, needed on Linux.
  433. bool screenModeChanged_;
  434. /// Initialized flag.
  435. bool initialized_;
  436. #ifdef __EMSCRIPTEN__
  437. /// Emscripten Input glue instance.
  438. EmscriptenInput* emscriptenInput_;
  439. /// Flag used to detect mouse jump when exiting pointer-lock.
  440. bool emscriptenExitingPointerLock_;
  441. /// Flag used to detect mouse jump on initial mouse click when entering pointer-lock.
  442. bool emscriptenEnteredPointerLock_;
  443. /// Flag indicating current pointer-lock status.
  444. bool emscriptenPointerLock_;
  445. #endif
  446. };
  447. }