BsInputHandlerOIS.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #include "BsInputHandlerOIS.h"
  2. #include "BsVector2I.h"
  3. #include "OIS/OISException.h"
  4. #include "BsRenderWindow.h"
  5. #include "BsTime.h"
  6. #include "BsMath.h"
  7. #include "BsDebug.h"
  8. namespace BansheeEngine
  9. {
  10. const UINT32 InputHandlerOIS::MOUSE_DPI = 800;
  11. const float InputHandlerOIS::MOUSE_MAX = 0.05f;
  12. const float InputHandlerOIS::MOUSE_MAX_TIME = 0.020f; // 20 ms
  13. const float InputHandlerOIS::MOUSE_MAX_SAMPLING_RATE = 0.006f; // 6ms
  14. GamepadEventListener::GamepadEventListener(InputHandlerOIS* parentHandler, UINT32 joystickIdx)
  15. :mParentHandler(parentHandler), mGamepadIdx(joystickIdx)
  16. { }
  17. bool GamepadEventListener::buttonPressed(const OIS::JoyStickEvent& arg, int button)
  18. {
  19. ButtonCode bc = InputHandlerOIS::gamepadButtonToButtonCode(button);
  20. // Note: No timestamps for gamepad buttons, but they shouldn't be used for anything anyway
  21. mParentHandler->onButtonDown(mGamepadIdx, bc, 0);
  22. return true;
  23. }
  24. bool GamepadEventListener::buttonReleased(const OIS::JoyStickEvent& arg, int button)
  25. {
  26. ButtonCode bc = InputHandlerOIS::gamepadButtonToButtonCode(button);
  27. // Note: No timestamps for gamepad buttons, but they shouldn't be used for anything anyway
  28. mParentHandler->onButtonUp(mGamepadIdx, bc, 0);
  29. return true;
  30. }
  31. bool GamepadEventListener::axisMoved(const OIS::JoyStickEvent& arg, int axis)
  32. {
  33. // Move axis values into [-1.0f, 1.0f] range
  34. float axisRange = Math::abs((float)OIS::JoyStick::MAX_AXIS) + Math::abs((float)OIS::JoyStick::MIN_AXIS);
  35. INT32 axisRel = arg.state.mAxes[axis].rel;
  36. INT32 axisAbs = arg.state.mAxes[axis].abs;
  37. RawAxisState axisState;
  38. axisState.rel = ((axisRel + Math::abs((float)OIS::JoyStick::MIN_AXIS)) / axisRange) * 2.0f - 1.0f;
  39. axisState.abs = ((axisAbs + Math::abs((float)OIS::JoyStick::MIN_AXIS)) / axisRange) * 2.0f - 1.0f;
  40. mParentHandler->onAxisMoved(mGamepadIdx, axisState, (UINT32)axis);
  41. return true;
  42. }
  43. InputHandlerOIS::InputHandlerOIS(unsigned int hWnd)
  44. :mInputManager(nullptr), mKeyboard(nullptr), mMouse(nullptr), mTimestampClockOffset(0),
  45. mLastMouseUpdateFrame(0), mMouseSampleCounter(0.0f)
  46. {
  47. mMouseSampleAccumulator[0] = 0;
  48. mMouseSampleAccumulator[1] = 0;
  49. mTotalMouseSamplingTime[0] = 1.0f / 125.0f; // Use 125Hz as initial pooling rate for mice
  50. mTotalMouseSamplingTime[1] = 1.0f / 125.0f;
  51. mTotalMouseNumSamples[0] = 1;
  52. mTotalMouseNumSamples[1] = 1;
  53. mMouseSmoothedAxis[0] = 0.0f;
  54. mMouseSmoothedAxis[1] = 0.0f;
  55. mMouseZeroTime[0] = 0.0f;
  56. mMouseZeroTime[1] = 0.0f;
  57. OIS::ParamList pl;
  58. std::ostringstream windowHndStr;
  59. windowHndStr << hWnd;
  60. pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
  61. #if defined BS_PLATFORM == BS_PLATFORM_WIN32
  62. pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND" )));
  63. pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
  64. pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND")));
  65. pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE")));
  66. #elif defined BS_PLATFORM == BS_PLATFORM_LINUX || BS_PLATFORM == BS_PLATFORM_APPLE
  67. pl.insert(std::make_pair(std::string("x11_mouse_grab"), std::string("false")));
  68. pl.insert(std::make_pair(std::string("x11_mouse_hide"), std::string("false")));
  69. pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false")));
  70. pl.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
  71. #endif
  72. try
  73. {
  74. mInputManager = OIS::InputManager::createInputSystem(pl);
  75. }
  76. catch(OIS::Exception &e)
  77. {
  78. std::cout << e.eText << std::endl;
  79. }
  80. if (mInputManager->getNumberOfDevices(OIS::OISKeyboard) > 0)
  81. {
  82. mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
  83. mKeyboard->setEventCallback(this);
  84. }
  85. if (mInputManager->getNumberOfDevices(OIS::OISMouse) > 0)
  86. {
  87. mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));
  88. mMouse->setEventCallback(this);
  89. }
  90. UINT32 numGamepads = mInputManager->getNumberOfDevices(OIS::OISJoyStick);
  91. for (UINT32 i = 0; i < numGamepads; i++)
  92. {
  93. mGamepads.push_back(GamepadData());
  94. GamepadData& gamepadData = mGamepads.back();
  95. gamepadData.gamepad = static_cast<OIS::JoyStick*>(mInputManager->createInputObject(OIS::OISJoyStick, true));
  96. gamepadData.listener = bs_new<GamepadEventListener>(this, i);
  97. gamepadData.gamepad->setEventCallback(gamepadData.listener);
  98. }
  99. // OIS reports times since system start but we use time since program start
  100. mTimestampClockOffset = gTime().getStartTimeMs();
  101. }
  102. InputHandlerOIS::~InputHandlerOIS()
  103. {
  104. if(mInputManager)
  105. {
  106. if(mMouse != nullptr)
  107. mInputManager->destroyInputObject(mMouse);
  108. if(mKeyboard != nullptr)
  109. mInputManager->destroyInputObject(mKeyboard);
  110. for (auto& gamepadData : mGamepads)
  111. {
  112. mInputManager->destroyInputObject(gamepadData.gamepad);
  113. bs_delete(gamepadData.listener);
  114. }
  115. OIS::InputManager::destroyInputSystem(mInputManager);
  116. mInputManager = nullptr;
  117. }
  118. }
  119. float InputHandlerOIS::smoothMouse(float value, UINT32 idx)
  120. {
  121. UINT32 sampleCount = 1;
  122. float deltaTime = gTime().getFrameDelta();
  123. if (deltaTime < 0.25f)
  124. {
  125. float secondsPerSample = mTotalMouseSamplingTime[idx] / mTotalMouseNumSamples[idx];
  126. if (value == 0.0f)
  127. {
  128. mMouseZeroTime[idx] += deltaTime;
  129. if (mMouseZeroTime[idx] < secondsPerSample)
  130. value = mMouseSmoothedAxis[idx] * deltaTime / secondsPerSample;
  131. else
  132. mMouseSmoothedAxis[idx] = 0;
  133. }
  134. else
  135. {
  136. mMouseZeroTime[idx] = 0;
  137. if (mMouseSmoothedAxis[idx] != 0)
  138. {
  139. if (deltaTime < secondsPerSample * (sampleCount + 1))
  140. value = value * deltaTime / (secondsPerSample * sampleCount);
  141. else
  142. sampleCount = Math::roundToInt(deltaTime / secondsPerSample);
  143. }
  144. mMouseSmoothedAxis[idx] = value / sampleCount;
  145. }
  146. }
  147. else
  148. {
  149. mMouseSmoothedAxis[idx] = 0.0f;
  150. mMouseZeroTime[idx] = 0.0f;
  151. }
  152. return value;
  153. }
  154. void InputHandlerOIS::_update()
  155. {
  156. if (mMouse != nullptr)
  157. mMouse->capture();
  158. if (mKeyboard != nullptr)
  159. mKeyboard->capture();
  160. for (auto& gamepadData : mGamepads)
  161. {
  162. gamepadData.gamepad->capture();
  163. }
  164. // Limit mouse sampling to a certain rate to avoid jitter at extremely high frame rates.
  165. // (As the application might request samples faster than they are produced)
  166. mMouseSampleCounter += gTime().getFrameDelta();
  167. if (mMouseSampleCounter < MOUSE_MAX_SAMPLING_RATE)
  168. return;
  169. float rawXValue = 0.0f;
  170. float rawYValue = 0.0f;
  171. // Smooth mouse axes if needed
  172. if (mMouseSmoothingEnabled)
  173. {
  174. rawXValue = smoothMouse((float)mMouseSampleAccumulator[0], 0);
  175. rawYValue = smoothMouse((float)mMouseSampleAccumulator[1], 1);
  176. }
  177. else
  178. {
  179. rawXValue = (float)mMouseSampleAccumulator[0];
  180. rawYValue = (float)mMouseSampleAccumulator[1];
  181. }
  182. mMouseSampleAccumulator[0] = 0;
  183. mMouseSampleAccumulator[1] = 0;
  184. // Scale by time so that we are framerate independant: rawXValue = rawXValue * (MOUSE_MAX_TIME / gTime().getFrameDelta());
  185. // Scale to valid [-1.0, 1.0] range: rawXValue / (MOUSE_DPI * MOUSE_MAX)
  186. // This is just the combination of the two:
  187. float axisScale = ((MOUSE_DPI * MOUSE_MAX) / MOUSE_MAX_TIME) * mMouseSampleCounter;
  188. RawAxisState xState;
  189. xState.rel = -Math::clamp(rawXValue / axisScale, -1.0f, 1.0f);
  190. xState.abs = xState.rel; // Abs value irrelevant for mouse
  191. onAxisMoved(0, xState, (UINT32)InputAxis::MouseX);
  192. RawAxisState yState;
  193. yState.rel = -Math::clamp(rawYValue / axisScale, -1.0f, 1.0f);
  194. yState.abs = yState.rel; // Abs value irrelevant for mouse
  195. onAxisMoved(0, yState, (UINT32)InputAxis::MouseY);
  196. mMouseSampleCounter = 0.0f;
  197. }
  198. void InputHandlerOIS::_inputWindowChanged(const RenderWindow& win)
  199. {
  200. UINT64 hWnd = 0;
  201. win.getCustomAttribute("WINDOW", &hWnd);
  202. std::string normalString = toString(hWnd).c_str();
  203. mKeyboard->setCaptureContext(normalString);
  204. mMouse->setCaptureContext(normalString);
  205. }
  206. bool InputHandlerOIS::keyPressed(const OIS::KeyEvent &arg)
  207. {
  208. onButtonDown(0, keyCodeToButtonCode(arg.key), arg.timestamp - mTimestampClockOffset);
  209. return true;
  210. }
  211. bool InputHandlerOIS::keyReleased(const OIS::KeyEvent& arg)
  212. {
  213. onButtonUp(0, keyCodeToButtonCode(arg.key), arg.timestamp - mTimestampClockOffset);
  214. return true;
  215. }
  216. bool InputHandlerOIS::mouseMoved(const OIS::MouseEvent& arg)
  217. {
  218. mMouseSampleAccumulator[0] += arg.state.X.rel;
  219. mMouseSampleAccumulator[1] += arg.state.Y.rel;
  220. mTotalMouseNumSamples[0] += Math::roundToInt(Math::abs((float)arg.state.X.rel));
  221. mTotalMouseNumSamples[1] += Math::roundToInt(Math::abs((float)arg.state.Y.rel));
  222. // Update sample times used for determining sampling rate. But only if something was
  223. // actually sampled, and only if this isn't the first non-zero sample.
  224. if (mLastMouseUpdateFrame != gTime().getCurrentFrameNumber())
  225. {
  226. if (arg.state.X.rel != 0 && !Math::approxEquals(mMouseSmoothedAxis[0], 0.0f))
  227. mTotalMouseSamplingTime[0] += gTime().getFrameDelta();
  228. if (arg.state.Y.rel != 0 && !Math::approxEquals(mMouseSmoothedAxis[1], 0.0f))
  229. mTotalMouseSamplingTime[1] += gTime().getFrameDelta();
  230. mLastMouseUpdateFrame = gTime().getCurrentFrameNumber();
  231. }
  232. RawAxisState zState;
  233. zState.abs = (float)arg.state.Z.abs;
  234. zState.rel = (float)arg.state.Z.rel;
  235. onAxisMoved(0, zState, (UINT32)InputAxis::MouseZ);
  236. return true;
  237. }
  238. bool InputHandlerOIS::mousePressed(const OIS::MouseEvent& arg, OIS::MouseButtonID id)
  239. {
  240. onButtonDown(0, mouseButtonToButtonCode(id), arg.timestamp - mTimestampClockOffset);
  241. return true;
  242. }
  243. bool InputHandlerOIS::mouseReleased(const OIS::MouseEvent& arg, OIS::MouseButtonID id)
  244. {
  245. onButtonUp(0, mouseButtonToButtonCode(id), arg.timestamp - mTimestampClockOffset);
  246. return true;
  247. }
  248. ButtonCode InputHandlerOIS::keyCodeToButtonCode(OIS::KeyCode keyCode)
  249. {
  250. return (ButtonCode)keyCode;
  251. }
  252. ButtonCode InputHandlerOIS::mouseButtonToButtonCode(OIS::MouseButtonID mouseBtn)
  253. {
  254. return (ButtonCode)(((int)mouseBtn + BC_NumKeys) | 0x80000000);
  255. }
  256. ButtonCode InputHandlerOIS::gamepadButtonToButtonCode(INT32 joystickCode)
  257. {
  258. switch (joystickCode)
  259. {
  260. case 0:
  261. return BC_GAMEPAD_DPAD_UP;
  262. case 1:
  263. return BC_GAMEPAD_DPAD_DOWN;
  264. case 2:
  265. return BC_GAMEPAD_DPAD_LEFT;
  266. case 3:
  267. return BC_GAMEPAD_DPAD_RIGHT;
  268. case 4:
  269. return BC_GAMEPAD_START;
  270. case 5:
  271. return BC_GAMEPAD_BACK;
  272. case 6:
  273. return BC_GAMEPAD_LS;
  274. case 7:
  275. return BC_GAMEPAD_RS;
  276. case 8:
  277. return BC_GAMEPAD_LB;
  278. case 9:
  279. return BC_GAMEPAD_RB;
  280. case 10:
  281. return BC_GAMEPAD_BTN1;
  282. case 11:
  283. return BC_GAMEPAD_LS;
  284. case 12:
  285. return BC_GAMEPAD_A;
  286. case 13:
  287. return BC_GAMEPAD_B;
  288. case 14:
  289. return BC_GAMEPAD_X;
  290. case 15:
  291. return BC_GAMEPAD_Y;
  292. }
  293. return (ButtonCode)(BC_GAMEPAD_BTN1 + (joystickCode - 15));
  294. }
  295. }