InputSourceGameController.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /*
  2. * InputSourceGameController.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "InputSourceGameController.h"
  12. #include "InputHandler.h"
  13. #include "../CGameInfo.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../gui/CursorHandler.h"
  16. #include "../gui/EventDispatcher.h"
  17. #include "../gui/ShortcutHandler.h"
  18. #include "../../lib/CConfigHandler.h"
  19. void InputSourceGameController::gameControllerDeleter(SDL_GameController * gameController)
  20. {
  21. if(gameController)
  22. SDL_GameControllerClose(gameController);
  23. }
  24. InputSourceGameController::InputSourceGameController():
  25. cursorAxisValueX(0),
  26. cursorAxisValueY(0),
  27. cursorPlanDisX(0.0),
  28. cursorPlanDisY(0.0),
  29. scrollAxisMoved(false),
  30. scrollStart(Point(0,0)),
  31. scrollCurrent(Point(0,0)),
  32. scrollAxisValueX(0),
  33. scrollAxisValueY(0),
  34. scrollPlanDisX(0.0),
  35. scrollPlanDisY(0.0),
  36. configTriggerThreshold(settings["input"]["controllerTriggerThreshold"].Float()),
  37. configAxisDeadZone(settings["input"]["controllerAxisDeadZone"].Float()),
  38. configAxisFullZone(settings["input"]["controllerAxisFullZone"].Float()),
  39. configAxisSpeed(settings["input"]["controllerAxisSpeed"].Float()),
  40. configAxisScale(settings["input"]["controllerAxisScale"].Float())
  41. {
  42. tryOpenAllGameControllers();
  43. }
  44. void InputSourceGameController::tryOpenAllGameControllers()
  45. {
  46. for(int i = 0; i < SDL_NumJoysticks(); ++i)
  47. if(SDL_IsGameController(i))
  48. openGameController(i);
  49. else
  50. logGlobal->warn("Joystick %d is an unsupported game controller!", i);
  51. }
  52. void InputSourceGameController::openGameController(int index)
  53. {
  54. SDL_GameController * controller = SDL_GameControllerOpen(index);
  55. if(!controller)
  56. {
  57. logGlobal->error("Fail to open game controller %d!", index);
  58. return;
  59. }
  60. GameControllerPtr controllerPtr(controller, &gameControllerDeleter);
  61. // Need to save joystick index for event. Joystick index may not be equal to index sometimes.
  62. int joystickIndex = getJoystickIndex(controllerPtr.get());
  63. if(joystickIndex < 0)
  64. {
  65. logGlobal->error("Fail to get joystick index of game controller %d!", index);
  66. return;
  67. }
  68. if(gameControllerMap.find(joystickIndex) != gameControllerMap.end())
  69. {
  70. logGlobal->warn("Game controller with joystick index %d is already opened.", joystickIndex);
  71. return;
  72. }
  73. gameControllerMap.try_emplace(joystickIndex, std::move(controllerPtr));
  74. }
  75. int InputSourceGameController::getJoystickIndex(SDL_GameController * controller)
  76. {
  77. SDL_Joystick * joystick = SDL_GameControllerGetJoystick(controller);
  78. if(!joystick)
  79. return -1;
  80. SDL_JoystickID instanceID = SDL_JoystickInstanceID(joystick);
  81. if(instanceID < 0)
  82. return -1;
  83. return instanceID;
  84. }
  85. void InputSourceGameController::handleEventDeviceAdded(const SDL_ControllerDeviceEvent & device)
  86. {
  87. if(gameControllerMap.find(device.which) != gameControllerMap.end())
  88. {
  89. logGlobal->warn("Game controller %d is already opened.", device.which);
  90. return;
  91. }
  92. openGameController(device.which);
  93. }
  94. void InputSourceGameController::handleEventDeviceRemoved(const SDL_ControllerDeviceEvent & device)
  95. {
  96. if(gameControllerMap.find(device.which) == gameControllerMap.end())
  97. {
  98. logGlobal->warn("Game controller %d is not opened before.", device.which);
  99. return;
  100. }
  101. gameControllerMap.erase(device.which);
  102. }
  103. void InputSourceGameController::handleEventDeviceRemapped(const SDL_ControllerDeviceEvent & device)
  104. {
  105. if(gameControllerMap.find(device.which) == gameControllerMap.end())
  106. {
  107. logGlobal->warn("Game controller %d is not opened.", device.which);
  108. return;
  109. }
  110. gameControllerMap.erase(device.which);
  111. openGameController(device.which);
  112. }
  113. double InputSourceGameController::getRealAxisValue(int value) const
  114. {
  115. double ratio = static_cast<double>(value) / SDL_JOYSTICK_AXIS_MAX;
  116. double greenZone = configAxisFullZone - configAxisDeadZone;
  117. if (std::abs(ratio) < configAxisDeadZone)
  118. return 0;
  119. double scaledValue = (ratio - configAxisDeadZone) / greenZone;
  120. double clampedValue = std::clamp(scaledValue, -1.0, +1.0);
  121. return clampedValue;
  122. }
  123. void InputSourceGameController::dispatchAxisShortcuts(const std::vector<EShortcut> & shortcutsVector, SDL_GameControllerAxis axisID, int axisValue)
  124. {
  125. if(getRealAxisValue(axisValue) > configTriggerThreshold)
  126. {
  127. if(!pressedAxes.count(axisID))
  128. {
  129. GH.events().dispatchShortcutPressed(shortcutsVector);
  130. pressedAxes.insert(axisID);
  131. }
  132. }
  133. else
  134. {
  135. if(pressedAxes.count(axisID))
  136. {
  137. GH.events().dispatchShortcutReleased(shortcutsVector);
  138. pressedAxes.erase(axisID);
  139. }
  140. }
  141. }
  142. void InputSourceGameController::handleEventAxisMotion(const SDL_ControllerAxisEvent & axis)
  143. {
  144. tryToConvertCursor();
  145. SDL_GameControllerAxis axisID = static_cast<SDL_GameControllerAxis>(axis.axis);
  146. std::string axisName = SDL_GameControllerGetStringForAxis(axisID);
  147. auto axisActions = GH.shortcuts().translateJoystickAxis(axisName);
  148. auto buttonActions = GH.shortcuts().translateJoystickButton(axisName);
  149. for(const auto & action : axisActions)
  150. {
  151. switch(action)
  152. {
  153. case EShortcut::MOUSE_CURSOR_X:
  154. cursorAxisValueX = getRealAxisValue(axis.value);
  155. break;
  156. case EShortcut::MOUSE_CURSOR_Y:
  157. cursorAxisValueY = getRealAxisValue(axis.value);
  158. break;
  159. case EShortcut::MOUSE_SWIPE_X:
  160. scrollAxisValueX = getRealAxisValue(axis.value);
  161. break;
  162. case EShortcut::MOUSE_SWIPE_Y:
  163. scrollAxisValueY = getRealAxisValue(axis.value);
  164. break;
  165. }
  166. }
  167. dispatchAxisShortcuts(buttonActions, axisID, axis.value);
  168. }
  169. void InputSourceGameController::tryToConvertCursor()
  170. {
  171. assert(CCS);
  172. assert(CCS->curh);
  173. if(CCS->curh->getShowType() == Cursor::ShowType::HARDWARE)
  174. {
  175. const Point & cursorPosition = GH.getCursorPosition();
  176. CCS->curh->changeCursor(Cursor::ShowType::SOFTWARE);
  177. CCS->curh->cursorMove(cursorPosition.x, cursorPosition.y);
  178. GH.input().setCursorPosition(cursorPosition);
  179. }
  180. }
  181. void InputSourceGameController::handleEventButtonDown(const SDL_ControllerButtonEvent & button)
  182. {
  183. std::string buttonName = SDL_GameControllerGetStringForButton(static_cast<SDL_GameControllerButton>(button.button));
  184. const auto & shortcutsVector = GH.shortcuts().translateJoystickButton(buttonName);
  185. GH.events().dispatchShortcutPressed(shortcutsVector);
  186. }
  187. void InputSourceGameController::handleEventButtonUp(const SDL_ControllerButtonEvent & button)
  188. {
  189. std::string buttonName = SDL_GameControllerGetStringForButton(static_cast<SDL_GameControllerButton>(button.button));
  190. const auto & shortcutsVector = GH.shortcuts().translateJoystickButton(buttonName);
  191. GH.events().dispatchShortcutReleased(shortcutsVector);
  192. }
  193. void InputSourceGameController::doCursorMove(int deltaX, int deltaY)
  194. {
  195. if(deltaX == 0 && deltaY == 0)
  196. return;
  197. const Point & screenSize = GH.screenDimensions();
  198. const Point & cursorPosition = GH.getCursorPosition();
  199. int newX = std::min(std::max(cursorPosition.x + deltaX, 0), screenSize.x);
  200. int newY = std::min(std::max(cursorPosition.y + deltaY, 0), screenSize.y);
  201. Point targetPosition{newX, newY};
  202. GH.input().setCursorPosition(targetPosition);
  203. if(CCS && CCS->curh)
  204. CCS->curh->cursorMove(GH.getCursorPosition().x, GH.getCursorPosition().y);
  205. }
  206. int InputSourceGameController::getMoveDis(float planDis)
  207. {
  208. if(planDis >= 0)
  209. return std::floor(planDis);
  210. else
  211. return std::ceil(planDis);
  212. }
  213. void InputSourceGameController::handleUpdate()
  214. {
  215. std::chrono::steady_clock::time_point nowMs = std::chrono::steady_clock::now();
  216. if(lastCheckTime == std::chrono::steady_clock::time_point())
  217. {
  218. lastCheckTime = nowMs;
  219. return;
  220. }
  221. int32_t deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(nowMs - lastCheckTime).count();
  222. handleCursorUpdate(deltaTime);
  223. handleScrollUpdate(deltaTime);
  224. lastCheckTime = nowMs;
  225. }
  226. static double scaleAxis(double value, double power)
  227. {
  228. if (value > 0)
  229. return std::pow(value, power);
  230. else
  231. return -std::pow(-value, power);
  232. }
  233. void InputSourceGameController::handleCursorUpdate(int32_t deltaTimeMs)
  234. {
  235. float deltaTimeSeconds = static_cast<float>(deltaTimeMs) / 1000;
  236. if(vstd::isAlmostZero(cursorAxisValueX))
  237. cursorPlanDisX = 0;
  238. else
  239. cursorPlanDisX += deltaTimeSeconds * configAxisSpeed * scaleAxis(cursorAxisValueX, configAxisScale);
  240. if (vstd::isAlmostZero(cursorAxisValueY))
  241. cursorPlanDisY = 0;
  242. else
  243. cursorPlanDisY += deltaTimeSeconds * configAxisSpeed * scaleAxis(cursorAxisValueY, configAxisScale);
  244. int moveDisX = getMoveDis(cursorPlanDisX);
  245. int moveDisY = getMoveDis(cursorPlanDisY);
  246. cursorPlanDisX -= moveDisX;
  247. cursorPlanDisY -= moveDisY;
  248. doCursorMove(moveDisX, moveDisY);
  249. }
  250. void InputSourceGameController::handleScrollUpdate(int32_t deltaTimeMs)
  251. {
  252. if(!scrollAxisMoved && isScrollAxisReleased())
  253. {
  254. return;
  255. }
  256. else if(!scrollAxisMoved && !isScrollAxisReleased())
  257. {
  258. scrollAxisMoved = true;
  259. scrollCurrent = scrollStart = GH.input().getCursorPosition();
  260. GH.events().dispatchGesturePanningStarted(scrollStart);
  261. }
  262. else if(scrollAxisMoved && isScrollAxisReleased())
  263. {
  264. GH.events().dispatchGesturePanningEnded(scrollStart, scrollCurrent);
  265. scrollAxisMoved = false;
  266. scrollPlanDisX = scrollPlanDisY = 0;
  267. return;
  268. }
  269. float deltaTimeSeconds = static_cast<float>(deltaTimeMs) / 1000;
  270. scrollPlanDisX += deltaTimeSeconds * configAxisSpeed * scaleAxis(scrollAxisValueX, configAxisScale);
  271. scrollPlanDisY += deltaTimeSeconds * configAxisSpeed * scaleAxis(scrollAxisValueY, configAxisScale);
  272. int moveDisX = getMoveDis(scrollPlanDisX);
  273. int moveDisY = getMoveDis(scrollPlanDisY);
  274. if(moveDisX != 0 || moveDisY != 0)
  275. {
  276. scrollPlanDisX -= moveDisX;
  277. scrollPlanDisY -= moveDisY;
  278. scrollCurrent.x += moveDisX;
  279. scrollCurrent.y += moveDisY;
  280. Point distance(moveDisX, moveDisY);
  281. GH.events().dispatchGesturePanning(scrollStart, scrollCurrent, distance);
  282. }
  283. }
  284. bool InputSourceGameController::isScrollAxisReleased() const
  285. {
  286. return vstd::isAlmostZero(scrollAxisValueX) && vstd::isAlmostZero(scrollAxisValueY);
  287. }