Input.cpp 19 KB

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