Input.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Context.h"
  24. #include "CoreEvents.h"
  25. #include "Graphics.h"
  26. #include "GraphicsEvents.h"
  27. #include "GraphicsImpl.h"
  28. #include "Input.h"
  29. #include "Log.h"
  30. #include "Mutex.h"
  31. #include "ProcessUtils.h"
  32. #include "Profiler.h"
  33. #include "StringUtils.h"
  34. #include <cstring>
  35. #include <SDL.h>
  36. #include "DebugNew.h"
  37. static HashMap<unsigned, Input*> inputInstances;
  38. /// Return the Input subsystem instance corresponding to an SDL window ID.
  39. Input* GetInputInstance(unsigned windowID)
  40. {
  41. #if !defined(ANDROID) && !defined(IOS)
  42. return windowID ? inputInstances[windowID] : 0;
  43. #else
  44. // On mobile devices only a single Urho3D instance within a process is supported, and the window ID can not be relied on.
  45. return inputInstances.Size() ? inputInstances.Begin()->second_ : 0;
  46. #endif
  47. }
  48. /// Convert SDL keycode if necessary
  49. int ConvertSDLKeyCode(int keySym, int scanCode)
  50. {
  51. if (scanCode == SDL_SCANCODE_AC_BACK)
  52. return KEY_ESC;
  53. else
  54. return SDL_toupper(keySym);
  55. }
  56. OBJECTTYPESTATIC(Input);
  57. Input::Input(Context* context) :
  58. Object(context),
  59. windowID_(0),
  60. toggleFullscreen_(true),
  61. active_(false),
  62. minimized_(false),
  63. activated_(false),
  64. suppressNextMouseMove_(false),
  65. initialized_(false)
  66. {
  67. // Zero the initial state
  68. mouseButtonDown_ = 0;
  69. ResetState();
  70. SubscribeToEvent(E_SCREENMODE, HANDLER(Input, HandleScreenMode));
  71. SubscribeToEvent(E_BEGINFRAME, HANDLER(Input, HandleBeginFrame));
  72. // Try to initialize right now, but skip if screen mode is not yet set
  73. Initialize();
  74. }
  75. Input::~Input()
  76. {
  77. // Remove input instance mapping
  78. if (initialized_)
  79. {
  80. MutexLock lock(GetStaticMutex());
  81. inputInstances.Erase(windowID_);
  82. }
  83. }
  84. void Input::Update()
  85. {
  86. PROFILE(UpdateInput);
  87. if (!graphics_ || !graphics_->IsInitialized())
  88. return;
  89. // Reset input accumulation for this frame
  90. keyPress_.Clear();
  91. mouseButtonPress_ = 0;
  92. mouseMove_ = IntVector2::ZERO;
  93. mouseMoveWheel_ = 0;
  94. // Reset touch delta movement
  95. for (Map<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  96. {
  97. TouchState& state = i->second_;
  98. state.lastPosition_ = state.position_;
  99. state.delta_ = IntVector2::ZERO;
  100. }
  101. {
  102. MutexLock lock(GetStaticMutex());
  103. // Pump SDL events
  104. SDL_Event evt;
  105. SDL_PumpEvents();
  106. while (SDL_PollEvent(&evt))
  107. {
  108. // Dispatch event to the appropriate Input instance. However SDL_QUIT can not at the moment be handled for multiple
  109. // instances properly (other threads' graphics devices can not be closed from this thread), so we handle it only
  110. // for own instance
  111. if (evt.type != SDL_QUIT)
  112. HandleSDLEvent(&evt);
  113. else
  114. graphics_->Close();
  115. }
  116. }
  117. // Check for activation and inactivation from SDL window flags. Must nullcheck the window pointer because it may have
  118. // been closed due to input events
  119. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  120. if (window)
  121. {
  122. unsigned flags = SDL_GetWindowFlags(window);
  123. bool oldMinimized = minimized_;
  124. minimized_ = (flags & SDL_WINDOW_MINIMIZED) != 0;
  125. flags &= (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS);
  126. if (!active_ && graphics_->GetFullscreen() && flags == (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS))
  127. activated_ = true;
  128. else if (active_ && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  129. MakeInactive();
  130. else if (minimized_ != oldMinimized)
  131. SendActivationEvent();
  132. // Activate input now if necessary
  133. if (activated_)
  134. MakeActive();
  135. }
  136. else
  137. return;
  138. // Check for mouse move
  139. if (active_)
  140. {
  141. IntVector2 mousePos = GetCursorPosition();
  142. mouseMove_ = mousePos - lastCursorPosition_;
  143. // Recenter the mouse cursor manually
  144. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  145. SetCursorPosition(center);
  146. lastCursorPosition_ = center;
  147. if (mouseMove_ != IntVector2::ZERO && suppressNextMouseMove_)
  148. {
  149. mouseMove_ = IntVector2::ZERO;
  150. suppressNextMouseMove_ = false;
  151. }
  152. // Send mouse move event if necessary
  153. if (mouseMove_ != IntVector2::ZERO)
  154. {
  155. using namespace MouseMove;
  156. VariantMap eventData;
  157. eventData[P_DX] = mouseMove_.x_;
  158. eventData[P_DY] = mouseMove_.y_;
  159. eventData[P_BUTTONS] = mouseButtonDown_;
  160. eventData[P_QUALIFIERS] = GetQualifiers();
  161. SendEvent(E_MOUSEMOVE, eventData);
  162. }
  163. }
  164. }
  165. void Input::SetToggleFullscreen(bool enable)
  166. {
  167. toggleFullscreen_ = enable;
  168. }
  169. bool Input::GetKeyDown(int key) const
  170. {
  171. return keyDown_.Contains(key);
  172. }
  173. bool Input::GetKeyPress(int key) const
  174. {
  175. return keyPress_.Contains(key);
  176. }
  177. bool Input::GetMouseButtonDown(int button) const
  178. {
  179. return (mouseButtonDown_ & button) != 0;
  180. }
  181. bool Input::GetMouseButtonPress(int button) const
  182. {
  183. return (mouseButtonPress_ & button) != 0;
  184. }
  185. bool Input::GetQualifierDown(int qualifier) const
  186. {
  187. if (qualifier == QUAL_SHIFT)
  188. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  189. if (qualifier == QUAL_CTRL)
  190. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  191. if (qualifier == QUAL_ALT)
  192. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  193. return false;
  194. }
  195. bool Input::GetQualifierPress(int qualifier) const
  196. {
  197. if (qualifier == QUAL_SHIFT)
  198. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  199. if (qualifier == QUAL_CTRL)
  200. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  201. if (qualifier == QUAL_ALT)
  202. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  203. return false;
  204. }
  205. int Input::GetQualifiers() const
  206. {
  207. int ret = 0;
  208. if (GetQualifierDown(QUAL_SHIFT))
  209. ret |= QUAL_SHIFT;
  210. if (GetQualifierDown(QUAL_CTRL))
  211. ret |= QUAL_CTRL;
  212. if (GetQualifierDown(QUAL_ALT))
  213. ret |= QUAL_ALT;
  214. return ret;
  215. }
  216. TouchState Input::GetTouch(unsigned index) const
  217. {
  218. unsigned cmpIndex = 0;
  219. for (Map<int, TouchState>::ConstIterator i = touches_.Begin(); i != touches_.End(); ++i)
  220. {
  221. /// \todo Do not make a value copy
  222. if (cmpIndex == index)
  223. return i->second_;
  224. else
  225. ++cmpIndex;
  226. }
  227. return TouchState();
  228. }
  229. bool Input::IsMinimized() const
  230. {
  231. // Return minimized state also when inactive in fullscreen
  232. if (!active_ && graphics_ && graphics_->GetFullscreen())
  233. return true;
  234. else
  235. return minimized_;
  236. }
  237. void Input::Initialize()
  238. {
  239. Graphics* graphics = GetSubsystem<Graphics>();
  240. if (!graphics || !graphics->IsInitialized())
  241. return;
  242. graphics_ = graphics;
  243. // Set the initial activation
  244. activated_ = true;
  245. initialized_ = true;
  246. {
  247. MutexLock lock(GetStaticMutex());
  248. // Store window ID to direct SDL events to the correct instance
  249. windowID_ = SDL_GetWindowID(graphics_->GetImpl()->GetWindow());
  250. inputInstances[windowID_] = this;
  251. }
  252. LOGINFO("Initialized input");
  253. }
  254. void Input::MakeActive()
  255. {
  256. if (!graphics_ || !graphics_->IsInitialized())
  257. return;
  258. ResetState();
  259. active_ = true;
  260. activated_ = false;
  261. // Re-establish mouse cursor hiding as necessary
  262. SDL_ShowCursor(SDL_FALSE);
  263. suppressNextMouseMove_ = true;
  264. SendActivationEvent();
  265. }
  266. void Input::MakeInactive()
  267. {
  268. if (!graphics_ || !graphics_->IsInitialized())
  269. return;
  270. ResetState();
  271. active_ = false;
  272. activated_ = false;
  273. // Show the mouse cursor when inactive
  274. SDL_ShowCursor(SDL_TRUE);
  275. SendActivationEvent();
  276. }
  277. void Input::ResetState()
  278. {
  279. keyDown_.Clear();
  280. keyPress_.Clear();
  281. // When clearing touch states, send the corresponding touch end events
  282. for (Map<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  283. {
  284. TouchState& state = i->second_;
  285. using namespace TouchEnd;
  286. VariantMap eventData;
  287. eventData[P_TOUCHID] = state.touchID_;
  288. eventData[P_X] = state.position_.x_;
  289. eventData[P_Y] = state.position_.y_;
  290. SendEvent(E_TOUCHEND, eventData);
  291. }
  292. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  293. SetMouseButton(MOUSEB_LEFT, false);
  294. SetMouseButton(MOUSEB_RIGHT, false);
  295. SetMouseButton(MOUSEB_MIDDLE, false);
  296. mouseMove_ = IntVector2::ZERO;
  297. mouseMoveWheel_ = 0;
  298. mouseButtonPress_ = 0;
  299. }
  300. void Input::SendActivationEvent()
  301. {
  302. using namespace Activation;
  303. VariantMap eventData;
  304. eventData[P_ACTIVE] = IsActive();
  305. eventData[P_MINIMIZED] = IsMinimized();
  306. SendEvent(E_ACTIVATION, eventData);
  307. }
  308. void Input::SetMouseButton(int button, bool newState)
  309. {
  310. // After deactivation in windowed mode, activate by a left-click inside the window
  311. if (initialized_ && !graphics_->GetFullscreen())
  312. {
  313. if (!active_ && newState && button == MOUSEB_LEFT)
  314. activated_ = true;
  315. }
  316. // If we are not active yet, do not react to the mouse button down
  317. if (newState && !active_)
  318. return;
  319. if (newState)
  320. {
  321. if (!(mouseButtonDown_ & button))
  322. mouseButtonPress_ |= button;
  323. mouseButtonDown_ |= button;
  324. }
  325. else
  326. {
  327. if (!(mouseButtonDown_ & button))
  328. return;
  329. mouseButtonDown_ &= ~button;
  330. }
  331. using namespace MouseButtonDown;
  332. VariantMap eventData;
  333. eventData[P_BUTTON] = button;
  334. eventData[P_BUTTONS] = mouseButtonDown_;
  335. eventData[P_QUALIFIERS] = GetQualifiers();
  336. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  337. }
  338. void Input::SetKey(int key, bool newState)
  339. {
  340. // If we are not active yet, do not react to the key down
  341. if (newState && !active_)
  342. return;
  343. bool repeat = false;
  344. if (newState)
  345. {
  346. if (!keyDown_.Contains(key))
  347. {
  348. keyDown_.Insert(key);
  349. keyPress_.Insert(key);
  350. }
  351. else
  352. repeat = true;
  353. }
  354. else
  355. {
  356. if (!keyDown_.Erase(key))
  357. return;
  358. }
  359. using namespace KeyDown;
  360. VariantMap eventData;
  361. eventData[P_KEY] = key;
  362. eventData[P_BUTTONS] = mouseButtonDown_;
  363. eventData[P_QUALIFIERS] = GetQualifiers();
  364. if (newState)
  365. eventData[P_REPEAT] = repeat;
  366. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  367. if (key == KEY_RETURN && newState && !repeat && toggleFullscreen_ && (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  368. graphics_->ToggleFullscreen();
  369. }
  370. void Input::SetMouseWheel(int delta)
  371. {
  372. // If we are not active yet, do not react to the wheel
  373. if (!active_)
  374. return;
  375. if (delta)
  376. {
  377. mouseMoveWheel_ += delta;
  378. using namespace MouseWheel;
  379. VariantMap eventData;
  380. eventData[P_WHEEL] = delta;
  381. eventData[P_BUTTONS] = mouseButtonDown_;
  382. eventData[P_QUALIFIERS] = GetQualifiers();
  383. SendEvent(E_MOUSEWHEEL, eventData);
  384. }
  385. }
  386. void Input::SetCursorPosition(const IntVector2& position)
  387. {
  388. if (!graphics_)
  389. return;
  390. SDL_WarpMouseInWindow(graphics_->GetImpl()->GetWindow(), position.x_, position.y_);
  391. }
  392. IntVector2 Input::GetCursorPosition() const
  393. {
  394. IntVector2 ret = lastCursorPosition_;
  395. if (!graphics_ || !graphics_->IsInitialized())
  396. return ret;
  397. SDL_GetMouseState(&ret.x_, &ret.y_);
  398. return ret;
  399. }
  400. void Input::HandleSDLEvent(void* sdlEvent)
  401. {
  402. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  403. Input* input = 0;
  404. switch (evt.type)
  405. {
  406. case SDL_KEYDOWN:
  407. // Convert to uppercase to match Win32 virtual key codes
  408. input = GetInputInstance(evt.key.windowID);
  409. if (input)
  410. input->SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), true);
  411. break;
  412. case SDL_KEYUP:
  413. input = GetInputInstance(evt.key.windowID);
  414. if (input)
  415. input->SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), false);
  416. break;
  417. case SDL_TEXTINPUT:
  418. input = GetInputInstance(evt.text.windowID);
  419. if (input && evt.text.text[0])
  420. {
  421. String text(&evt.text.text[0]);
  422. unsigned unicode = text.AtUTF8(0);
  423. if (unicode)
  424. {
  425. using namespace Char;
  426. VariantMap keyEventData;
  427. keyEventData[P_CHAR] = unicode;
  428. keyEventData[P_BUTTONS] = input->mouseButtonDown_;
  429. keyEventData[P_QUALIFIERS] = input->GetQualifiers();
  430. input->SendEvent(E_CHAR, keyEventData);
  431. }
  432. }
  433. break;
  434. case SDL_MOUSEBUTTONDOWN:
  435. input = GetInputInstance(evt.button.windowID);
  436. if (input)
  437. input->SetMouseButton(1 << (evt.button.button - 1), true);
  438. break;
  439. case SDL_MOUSEBUTTONUP:
  440. input = GetInputInstance(evt.button.windowID);
  441. if (input)
  442. input->SetMouseButton(1 << (evt.button.button - 1), false);
  443. break;
  444. case SDL_MOUSEWHEEL:
  445. input = GetInputInstance(evt.wheel.windowID);
  446. if (input)
  447. input->SetMouseWheel(evt.wheel.y);
  448. break;
  449. case SDL_FINGERDOWN:
  450. input = GetInputInstance(evt.tfinger.windowID);
  451. if (input)
  452. {
  453. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  454. TouchState& state = input->touches_[touchID];
  455. state.touchID_ = touchID;
  456. state.lastPosition_ = state.position_ = IntVector2(evt.tfinger.x * input->graphics_->GetWidth() / 32768,
  457. evt.tfinger.y * input->graphics_->GetHeight() / 32768);
  458. state.delta_ = IntVector2::ZERO;
  459. state.pressure_ = evt.tfinger.pressure;
  460. using namespace TouchBegin;
  461. VariantMap eventData;
  462. eventData[P_TOUCHID] = touchID;
  463. eventData[P_X] = state.position_.x_;
  464. eventData[P_Y] = state.position_.y_;
  465. eventData[P_PRESSURE] = state.pressure_;
  466. input->SendEvent(E_TOUCHBEGIN, eventData);
  467. }
  468. break;
  469. case SDL_FINGERUP:
  470. input = GetInputInstance(evt.tfinger.windowID);
  471. if (input)
  472. {
  473. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  474. input->touches_.Erase(touchID);
  475. using namespace TouchEnd;
  476. VariantMap eventData;
  477. eventData[P_TOUCHID] = touchID;
  478. eventData[P_X] = evt.tfinger.x * input->graphics_->GetWidth() / 32768;
  479. eventData[P_Y] = evt.tfinger.y * input->graphics_->GetHeight() / 32768;
  480. input->SendEvent(E_TOUCHEND, eventData);
  481. }
  482. break;
  483. case SDL_FINGERMOTION:
  484. input = GetInputInstance(evt.tfinger.windowID);
  485. if (input)
  486. {
  487. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  488. TouchState& state = input->touches_[touchID];
  489. state.touchID_ = touchID;
  490. state.position_ = IntVector2(evt.tfinger.x * input->graphics_->GetWidth() / 32768,
  491. evt.tfinger.y * input->graphics_->GetHeight() / 32768);
  492. state.delta_ = state.position_ - state.lastPosition_;
  493. state.pressure_ = evt.tfinger.pressure;
  494. using namespace TouchMove;
  495. VariantMap eventData;
  496. eventData[P_TOUCHID] = touchID;
  497. eventData[P_X] = state.position_.x_;
  498. eventData[P_Y] = state.position_.y_;
  499. eventData[P_DX] = evt.tfinger.dx * input->graphics_->GetWidth() / 32768;
  500. eventData[P_DY] = evt.tfinger.dy * input->graphics_->GetHeight() / 32768;
  501. eventData[P_PRESSURE] = state.pressure_;
  502. input->SendEvent(E_TOUCHMOVE, eventData);
  503. }
  504. break;
  505. case SDL_WINDOWEVENT:
  506. input = GetInputInstance(evt.window.windowID);
  507. if (input)
  508. {
  509. switch (evt.window.event)
  510. {
  511. case SDL_WINDOWEVENT_CLOSE:
  512. input->GetSubsystem<Graphics>()->Close();
  513. break;
  514. #ifdef ANDROID
  515. case SDL_WINDOWEVENT_SURFACE_LOST:
  516. // Mark GPU objects lost
  517. input->graphics_->Release(false, false);
  518. break;
  519. case SDL_WINDOWEVENT_SURFACE_CREATED:
  520. // Restore GPU objects
  521. input->graphics_->Restore();
  522. break;
  523. #endif
  524. }
  525. }
  526. break;
  527. }
  528. }
  529. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  530. {
  531. // Reset input state on subsequent initializations
  532. if (!initialized_)
  533. Initialize();
  534. else
  535. ResetState();
  536. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  537. // mouse move event. Also get the new window ID in case it changed
  538. unsigned newWindowID = SDL_GetWindowID(graphics_->GetImpl()->GetWindow());
  539. if (newWindowID != windowID_)
  540. {
  541. MutexLock lock(GetStaticMutex());
  542. inputInstances.Erase(windowID_);
  543. inputInstances[newWindowID] = this;
  544. windowID_ = newWindowID;
  545. }
  546. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  547. SetCursorPosition(center);
  548. lastCursorPosition_ = center;
  549. activated_ = true;
  550. }
  551. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  552. {
  553. // Update input right at the beginning of the frame
  554. if (initialized_)
  555. Update();
  556. }