InputSourceGameController.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 "../GameEngine.h"
  14. #include "../gui/CursorHandler.h"
  15. #include "../gui/EventDispatcher.h"
  16. #include "../gui/ShortcutHandler.h"
  17. #include "../render/IScreenHandler.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. ENGINE->events().dispatchShortcutPressed(shortcutsVector);
  130. pressedAxes.insert(axisID);
  131. }
  132. }
  133. else
  134. {
  135. if(pressedAxes.count(axisID))
  136. {
  137. ENGINE->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 = ENGINE->shortcuts().translateJoystickAxis(axisName);
  148. auto buttonActions = ENGINE->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. if(ENGINE->cursor().getShowType() == Cursor::ShowType::HARDWARE)
  172. {
  173. int scalingFactor = ENGINE->screenHandler().getScalingFactor();
  174. const Point & cursorPosition = ENGINE->getCursorPosition();
  175. ENGINE->cursor().changeCursor(Cursor::ShowType::SOFTWARE);
  176. ENGINE->cursor().cursorMove(cursorPosition.x * scalingFactor, cursorPosition.y * scalingFactor);
  177. ENGINE->input().setCursorPosition(cursorPosition);
  178. }
  179. }
  180. void InputSourceGameController::handleEventButtonDown(const SDL_ControllerButtonEvent & button)
  181. {
  182. std::string buttonName = SDL_GameControllerGetStringForButton(static_cast<SDL_GameControllerButton>(button.button));
  183. const auto & shortcutsVector = ENGINE->shortcuts().translateJoystickButton(buttonName);
  184. ENGINE->events().dispatchShortcutPressed(shortcutsVector);
  185. }
  186. void InputSourceGameController::handleEventButtonUp(const SDL_ControllerButtonEvent & button)
  187. {
  188. std::string buttonName = SDL_GameControllerGetStringForButton(static_cast<SDL_GameControllerButton>(button.button));
  189. const auto & shortcutsVector = ENGINE->shortcuts().translateJoystickButton(buttonName);
  190. ENGINE->events().dispatchShortcutReleased(shortcutsVector);
  191. }
  192. void InputSourceGameController::doCursorMove(int deltaX, int deltaY)
  193. {
  194. if(deltaX == 0 && deltaY == 0)
  195. return;
  196. const Point & screenSize = ENGINE->screenDimensions();
  197. const Point & cursorPosition = ENGINE->getCursorPosition();
  198. int scalingFactor = ENGINE->screenHandler().getScalingFactor();
  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. ENGINE->input().setCursorPosition(targetPosition);
  203. ENGINE->cursor().cursorMove(ENGINE->getCursorPosition().x * scalingFactor, ENGINE->getCursorPosition().y * scalingFactor);
  204. }
  205. int InputSourceGameController::getMoveDis(float planDis)
  206. {
  207. if(planDis >= 0)
  208. return std::floor(planDis);
  209. else
  210. return std::ceil(planDis);
  211. }
  212. void InputSourceGameController::handleUpdate()
  213. {
  214. std::chrono::steady_clock::time_point nowMs = std::chrono::steady_clock::now();
  215. if(lastCheckTime == std::chrono::steady_clock::time_point())
  216. {
  217. lastCheckTime = nowMs;
  218. return;
  219. }
  220. int32_t deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(nowMs - lastCheckTime).count();
  221. handleCursorUpdate(deltaTime);
  222. handleScrollUpdate(deltaTime);
  223. lastCheckTime = nowMs;
  224. }
  225. static double scaleAxis(double value, double power)
  226. {
  227. if (value > 0)
  228. return std::pow(value, power);
  229. else
  230. return -std::pow(-value, power);
  231. }
  232. void InputSourceGameController::handleCursorUpdate(int32_t deltaTimeMs)
  233. {
  234. float deltaTimeSeconds = static_cast<float>(deltaTimeMs) / 1000;
  235. if(vstd::isAlmostZero(cursorAxisValueX))
  236. cursorPlanDisX = 0;
  237. else
  238. cursorPlanDisX += deltaTimeSeconds * configAxisSpeed * scaleAxis(cursorAxisValueX, configAxisScale);
  239. if (vstd::isAlmostZero(cursorAxisValueY))
  240. cursorPlanDisY = 0;
  241. else
  242. cursorPlanDisY += deltaTimeSeconds * configAxisSpeed * scaleAxis(cursorAxisValueY, configAxisScale);
  243. int moveDisX = getMoveDis(cursorPlanDisX);
  244. int moveDisY = getMoveDis(cursorPlanDisY);
  245. cursorPlanDisX -= moveDisX;
  246. cursorPlanDisY -= moveDisY;
  247. doCursorMove(moveDisX, moveDisY);
  248. }
  249. void InputSourceGameController::handleScrollUpdate(int32_t deltaTimeMs)
  250. {
  251. if(!scrollAxisMoved && isScrollAxisReleased())
  252. {
  253. return;
  254. }
  255. else if(!scrollAxisMoved && !isScrollAxisReleased())
  256. {
  257. scrollAxisMoved = true;
  258. scrollCurrent = scrollStart = ENGINE->input().getCursorPosition();
  259. ENGINE->events().dispatchGesturePanningStarted(scrollStart);
  260. }
  261. else if(scrollAxisMoved && isScrollAxisReleased())
  262. {
  263. ENGINE->events().dispatchGesturePanningEnded(scrollStart, scrollCurrent);
  264. scrollAxisMoved = false;
  265. scrollPlanDisX = scrollPlanDisY = 0;
  266. return;
  267. }
  268. float deltaTimeSeconds = static_cast<float>(deltaTimeMs) / 1000;
  269. scrollPlanDisX += deltaTimeSeconds * configAxisSpeed * scaleAxis(scrollAxisValueX, configAxisScale);
  270. scrollPlanDisY += deltaTimeSeconds * configAxisSpeed * scaleAxis(scrollAxisValueY, configAxisScale);
  271. int moveDisX = getMoveDis(scrollPlanDisX);
  272. int moveDisY = getMoveDis(scrollPlanDisY);
  273. if(moveDisX != 0 || moveDisY != 0)
  274. {
  275. scrollPlanDisX -= moveDisX;
  276. scrollPlanDisY -= moveDisY;
  277. scrollCurrent.x += moveDisX;
  278. scrollCurrent.y += moveDisY;
  279. Point distance(moveDisX, moveDisY);
  280. ENGINE->events().dispatchGesturePanning(scrollStart, scrollCurrent, distance);
  281. }
  282. }
  283. bool InputSourceGameController::isScrollAxisReleased() const
  284. {
  285. return vstd::isAlmostZero(scrollAxisValueX) && vstd::isAlmostZero(scrollAxisValueY);
  286. }