sdl_impl.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <atomic>
  6. #include <cmath>
  7. #include <functional>
  8. #include <iterator>
  9. #include <mutex>
  10. #include <string>
  11. #include <thread>
  12. #include <tuple>
  13. #include <unordered_map>
  14. #include <utility>
  15. #include <vector>
  16. #include <SDL.h>
  17. #include "common/assert.h"
  18. #include "common/logging/log.h"
  19. #include "common/math_util.h"
  20. #include "common/param_package.h"
  21. #include "common/threadsafe_queue.h"
  22. #include "core/frontend/input.h"
  23. #include "input_common/sdl/sdl_impl.h"
  24. namespace InputCommon {
  25. namespace SDL {
  26. static std::string GetGUID(SDL_Joystick* joystick) {
  27. SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
  28. char guid_str[33];
  29. SDL_JoystickGetGUIDString(guid, guid_str, sizeof(guid_str));
  30. return guid_str;
  31. }
  32. /// Creates a ParamPackage from an SDL_Event that can directly be used to create a ButtonDevice
  33. static Common::ParamPackage SDLEventToButtonParamPackage(SDLState& state, const SDL_Event& event);
  34. static int SDLEventWatcher(void* userdata, SDL_Event* event) {
  35. SDLState* sdl_state = reinterpret_cast<SDLState*>(userdata);
  36. // Don't handle the event if we are configuring
  37. if (sdl_state->polling) {
  38. sdl_state->event_queue.Push(*event);
  39. } else {
  40. sdl_state->HandleGameControllerEvent(*event);
  41. }
  42. return 0;
  43. }
  44. class SDLJoystick {
  45. public:
  46. SDLJoystick(std::string guid_, int port_, SDL_Joystick* joystick,
  47. decltype(&SDL_JoystickClose) deleter = &SDL_JoystickClose)
  48. : guid{std::move(guid_)}, port{port_}, sdl_joystick{joystick, deleter} {}
  49. void SetButton(int button, bool value) {
  50. std::lock_guard lock{mutex};
  51. state.buttons[button] = value;
  52. }
  53. bool GetButton(int button) const {
  54. std::lock_guard lock{mutex};
  55. return state.buttons.at(button);
  56. }
  57. void SetAxis(int axis, Sint16 value) {
  58. std::lock_guard lock{mutex};
  59. state.axes[axis] = value;
  60. }
  61. float GetAxis(int axis) const {
  62. std::lock_guard lock{mutex};
  63. return state.axes.at(axis) / 32767.0f;
  64. }
  65. std::tuple<float, float> GetAnalog(int axis_x, int axis_y) const {
  66. float x = GetAxis(axis_x);
  67. float y = GetAxis(axis_y);
  68. y = -y; // 3DS uses an y-axis inverse from SDL
  69. // Make sure the coordinates are in the unit circle,
  70. // otherwise normalize it.
  71. float r = x * x + y * y;
  72. if (r > 1.0f) {
  73. r = std::sqrt(r);
  74. x /= r;
  75. y /= r;
  76. }
  77. return std::make_tuple(x, y);
  78. }
  79. void SetHat(int hat, Uint8 direction) {
  80. std::lock_guard lock{mutex};
  81. state.hats[hat] = direction;
  82. }
  83. bool GetHatDirection(int hat, Uint8 direction) const {
  84. std::lock_guard lock{mutex};
  85. return (state.hats.at(hat) & direction) != 0;
  86. }
  87. /**
  88. * The guid of the joystick
  89. */
  90. const std::string& GetGUID() const {
  91. return guid;
  92. }
  93. /**
  94. * The number of joystick from the same type that were connected before this joystick
  95. */
  96. int GetPort() const {
  97. return port;
  98. }
  99. SDL_Joystick* GetSDLJoystick() const {
  100. return sdl_joystick.get();
  101. }
  102. void SetSDLJoystick(SDL_Joystick* joystick,
  103. decltype(&SDL_JoystickClose) deleter = &SDL_JoystickClose) {
  104. sdl_joystick =
  105. std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)>(joystick, deleter);
  106. }
  107. private:
  108. struct State {
  109. std::unordered_map<int, bool> buttons;
  110. std::unordered_map<int, Sint16> axes;
  111. std::unordered_map<int, Uint8> hats;
  112. } state;
  113. std::string guid;
  114. int port;
  115. std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
  116. mutable std::mutex mutex;
  117. };
  118. /**
  119. * Get the nth joystick with the corresponding GUID
  120. */
  121. std::shared_ptr<SDLJoystick> SDLState::GetSDLJoystickByGUID(const std::string& guid, int port) {
  122. std::lock_guard lock{joystick_map_mutex};
  123. const auto it = joystick_map.find(guid);
  124. if (it != joystick_map.end()) {
  125. while (it->second.size() <= port) {
  126. auto joystick = std::make_shared<SDLJoystick>(guid, it->second.size(), nullptr,
  127. [](SDL_Joystick*) {});
  128. it->second.emplace_back(std::move(joystick));
  129. }
  130. return it->second[port];
  131. }
  132. auto joystick = std::make_shared<SDLJoystick>(guid, 0, nullptr, [](SDL_Joystick*) {});
  133. return joystick_map[guid].emplace_back(std::move(joystick));
  134. }
  135. /**
  136. * Check how many identical joysticks (by guid) were connected before the one with sdl_id and so tie
  137. * it to a SDLJoystick with the same guid and that port
  138. */
  139. std::shared_ptr<SDLJoystick> SDLState::GetSDLJoystickBySDLID(SDL_JoystickID sdl_id) {
  140. auto sdl_joystick = SDL_JoystickFromInstanceID(sdl_id);
  141. const std::string guid = GetGUID(sdl_joystick);
  142. std::lock_guard lock{joystick_map_mutex};
  143. auto map_it = joystick_map.find(guid);
  144. if (map_it != joystick_map.end()) {
  145. auto vec_it = std::find_if(map_it->second.begin(), map_it->second.end(),
  146. [&sdl_joystick](const std::shared_ptr<SDLJoystick>& joystick) {
  147. return sdl_joystick == joystick->GetSDLJoystick();
  148. });
  149. if (vec_it != map_it->second.end()) {
  150. // This is the common case: There is already an existing SDL_Joystick maped to a
  151. // SDLJoystick. return the SDLJoystick
  152. return *vec_it;
  153. }
  154. // Search for a SDLJoystick without a mapped SDL_Joystick...
  155. auto nullptr_it = std::find_if(map_it->second.begin(), map_it->second.end(),
  156. [](const std::shared_ptr<SDLJoystick>& joystick) {
  157. return !joystick->GetSDLJoystick();
  158. });
  159. if (nullptr_it != map_it->second.end()) {
  160. // ... and map it
  161. (*nullptr_it)->SetSDLJoystick(sdl_joystick);
  162. return *nullptr_it;
  163. }
  164. // There is no SDLJoystick without a mapped SDL_Joystick
  165. // Create a new SDLJoystick
  166. auto joystick = std::make_shared<SDLJoystick>(guid, map_it->second.size(), sdl_joystick);
  167. return map_it->second.emplace_back(std::move(joystick));
  168. }
  169. auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick);
  170. return joystick_map[guid].emplace_back(std::move(joystick));
  171. }
  172. void SDLState::InitJoystick(int joystick_index) {
  173. SDL_Joystick* sdl_joystick = SDL_JoystickOpen(joystick_index);
  174. if (!sdl_joystick) {
  175. LOG_ERROR(Input, "failed to open joystick {}", joystick_index);
  176. return;
  177. }
  178. const std::string guid = GetGUID(sdl_joystick);
  179. std::lock_guard lock{joystick_map_mutex};
  180. if (joystick_map.find(guid) == joystick_map.end()) {
  181. auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick);
  182. joystick_map[guid].emplace_back(std::move(joystick));
  183. return;
  184. }
  185. auto& joystick_guid_list = joystick_map[guid];
  186. const auto it = std::find_if(
  187. joystick_guid_list.begin(), joystick_guid_list.end(),
  188. [](const std::shared_ptr<SDLJoystick>& joystick) { return !joystick->GetSDLJoystick(); });
  189. if (it != joystick_guid_list.end()) {
  190. (*it)->SetSDLJoystick(sdl_joystick);
  191. return;
  192. }
  193. auto joystick = std::make_shared<SDLJoystick>(guid, joystick_guid_list.size(), sdl_joystick);
  194. joystick_guid_list.emplace_back(std::move(joystick));
  195. }
  196. void SDLState::CloseJoystick(SDL_Joystick* sdl_joystick) {
  197. std::string guid = GetGUID(sdl_joystick);
  198. std::shared_ptr<SDLJoystick> joystick;
  199. {
  200. std::lock_guard lock{joystick_map_mutex};
  201. // This call to guid is safe since the joystick is guaranteed to be in the map
  202. auto& joystick_guid_list = joystick_map[guid];
  203. const auto joystick_it =
  204. std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
  205. [&sdl_joystick](const std::shared_ptr<SDLJoystick>& joystick) {
  206. return joystick->GetSDLJoystick() == sdl_joystick;
  207. });
  208. joystick = *joystick_it;
  209. }
  210. // Destruct SDL_Joystick outside the lock guard because SDL can internally call event calback
  211. // which locks the mutex again
  212. joystick->SetSDLJoystick(nullptr, [](SDL_Joystick*) {});
  213. }
  214. void SDLState::HandleGameControllerEvent(const SDL_Event& event) {
  215. switch (event.type) {
  216. case SDL_JOYBUTTONUP: {
  217. if (auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  218. joystick->SetButton(event.jbutton.button, false);
  219. }
  220. break;
  221. }
  222. case SDL_JOYBUTTONDOWN: {
  223. if (auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  224. joystick->SetButton(event.jbutton.button, true);
  225. }
  226. break;
  227. }
  228. case SDL_JOYHATMOTION: {
  229. if (auto joystick = GetSDLJoystickBySDLID(event.jhat.which)) {
  230. joystick->SetHat(event.jhat.hat, event.jhat.value);
  231. }
  232. break;
  233. }
  234. case SDL_JOYAXISMOTION: {
  235. if (auto joystick = GetSDLJoystickBySDLID(event.jaxis.which)) {
  236. joystick->SetAxis(event.jaxis.axis, event.jaxis.value);
  237. }
  238. break;
  239. }
  240. case SDL_JOYDEVICEREMOVED:
  241. LOG_DEBUG(Input, "Controller removed with Instance_ID {}", event.jdevice.which);
  242. CloseJoystick(SDL_JoystickFromInstanceID(event.jdevice.which));
  243. break;
  244. case SDL_JOYDEVICEADDED:
  245. LOG_DEBUG(Input, "Controller connected with device index {}", event.jdevice.which);
  246. InitJoystick(event.jdevice.which);
  247. break;
  248. }
  249. }
  250. void SDLState::CloseJoysticks() {
  251. std::lock_guard lock{joystick_map_mutex};
  252. joystick_map.clear();
  253. }
  254. class SDLButton final : public Input::ButtonDevice {
  255. public:
  256. explicit SDLButton(std::shared_ptr<SDLJoystick> joystick_, int button_)
  257. : joystick(std::move(joystick_)), button(button_) {}
  258. bool GetStatus() const override {
  259. return joystick->GetButton(button);
  260. }
  261. private:
  262. std::shared_ptr<SDLJoystick> joystick;
  263. int button;
  264. };
  265. class SDLDirectionButton final : public Input::ButtonDevice {
  266. public:
  267. explicit SDLDirectionButton(std::shared_ptr<SDLJoystick> joystick_, int hat_, Uint8 direction_)
  268. : joystick(std::move(joystick_)), hat(hat_), direction(direction_) {}
  269. bool GetStatus() const override {
  270. return joystick->GetHatDirection(hat, direction);
  271. }
  272. private:
  273. std::shared_ptr<SDLJoystick> joystick;
  274. int hat;
  275. Uint8 direction;
  276. };
  277. class SDLAxisButton final : public Input::ButtonDevice {
  278. public:
  279. explicit SDLAxisButton(std::shared_ptr<SDLJoystick> joystick_, int axis_, float threshold_,
  280. bool trigger_if_greater_)
  281. : joystick(std::move(joystick_)), axis(axis_), threshold(threshold_),
  282. trigger_if_greater(trigger_if_greater_) {}
  283. bool GetStatus() const override {
  284. float axis_value = joystick->GetAxis(axis);
  285. if (trigger_if_greater)
  286. return axis_value > threshold;
  287. return axis_value < threshold;
  288. }
  289. private:
  290. std::shared_ptr<SDLJoystick> joystick;
  291. int axis;
  292. float threshold;
  293. bool trigger_if_greater;
  294. };
  295. class SDLAnalog final : public Input::AnalogDevice {
  296. public:
  297. SDLAnalog(std::shared_ptr<SDLJoystick> joystick_, int axis_x_, int axis_y_, float deadzone_)
  298. : joystick(std::move(joystick_)), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_) {}
  299. std::tuple<float, float> GetStatus() const override {
  300. const auto [x, y] = joystick->GetAnalog(axis_x, axis_y);
  301. const float r = std::sqrt((x * x) + (y * y));
  302. if (r > deadzone) {
  303. return std::make_tuple(x / r * (r - deadzone) / (1 - deadzone),
  304. y / r * (r - deadzone) / (1 - deadzone));
  305. }
  306. return std::make_tuple<float, float>(0.0f, 0.0f);
  307. }
  308. private:
  309. std::shared_ptr<SDLJoystick> joystick;
  310. const int axis_x;
  311. const int axis_y;
  312. const float deadzone;
  313. };
  314. /// A button device factory that creates button devices from SDL joystick
  315. class SDLButtonFactory final : public Input::Factory<Input::ButtonDevice> {
  316. public:
  317. explicit SDLButtonFactory(SDLState& state_) : state(state_) {}
  318. /**
  319. * Creates a button device from a joystick button
  320. * @param params contains parameters for creating the device:
  321. * - "guid": the guid of the joystick to bind
  322. * - "port": the nth joystick of the same type to bind
  323. * - "button"(optional): the index of the button to bind
  324. * - "hat"(optional): the index of the hat to bind as direction buttons
  325. * - "axis"(optional): the index of the axis to bind
  326. * - "direction"(only used for hat): the direction name of the hat to bind. Can be "up",
  327. * "down", "left" or "right"
  328. * - "threshold"(only used for axis): a float value in (-1.0, 1.0) which the button is
  329. * triggered if the axis value crosses
  330. * - "direction"(only used for axis): "+" means the button is triggered when the axis
  331. * value is greater than the threshold; "-" means the button is triggered when the axis
  332. * value is smaller than the threshold
  333. */
  334. std::unique_ptr<Input::ButtonDevice> Create(const Common::ParamPackage& params) override {
  335. const std::string guid = params.Get("guid", "0");
  336. const int port = params.Get("port", 0);
  337. auto joystick = state.GetSDLJoystickByGUID(guid, port);
  338. if (params.Has("hat")) {
  339. const int hat = params.Get("hat", 0);
  340. const std::string direction_name = params.Get("direction", "");
  341. Uint8 direction;
  342. if (direction_name == "up") {
  343. direction = SDL_HAT_UP;
  344. } else if (direction_name == "down") {
  345. direction = SDL_HAT_DOWN;
  346. } else if (direction_name == "left") {
  347. direction = SDL_HAT_LEFT;
  348. } else if (direction_name == "right") {
  349. direction = SDL_HAT_RIGHT;
  350. } else {
  351. direction = 0;
  352. }
  353. // This is necessary so accessing GetHat with hat won't crash
  354. joystick->SetHat(hat, SDL_HAT_CENTERED);
  355. return std::make_unique<SDLDirectionButton>(joystick, hat, direction);
  356. }
  357. if (params.Has("axis")) {
  358. const int axis = params.Get("axis", 0);
  359. const float threshold = params.Get("threshold", 0.5f);
  360. const std::string direction_name = params.Get("direction", "");
  361. bool trigger_if_greater;
  362. if (direction_name == "+") {
  363. trigger_if_greater = true;
  364. } else if (direction_name == "-") {
  365. trigger_if_greater = false;
  366. } else {
  367. trigger_if_greater = true;
  368. LOG_ERROR(Input, "Unknown direction {}", direction_name);
  369. }
  370. // This is necessary so accessing GetAxis with axis won't crash
  371. joystick->SetAxis(axis, 0);
  372. return std::make_unique<SDLAxisButton>(joystick, axis, threshold, trigger_if_greater);
  373. }
  374. const int button = params.Get("button", 0);
  375. // This is necessary so accessing GetButton with button won't crash
  376. joystick->SetButton(button, false);
  377. return std::make_unique<SDLButton>(joystick, button);
  378. }
  379. private:
  380. SDLState& state;
  381. };
  382. /// An analog device factory that creates analog devices from SDL joystick
  383. class SDLAnalogFactory final : public Input::Factory<Input::AnalogDevice> {
  384. public:
  385. explicit SDLAnalogFactory(SDLState& state_) : state(state_) {}
  386. /**
  387. * Creates analog device from joystick axes
  388. * @param params contains parameters for creating the device:
  389. * - "guid": the guid of the joystick to bind
  390. * - "port": the nth joystick of the same type
  391. * - "axis_x": the index of the axis to be bind as x-axis
  392. * - "axis_y": the index of the axis to be bind as y-axis
  393. */
  394. std::unique_ptr<Input::AnalogDevice> Create(const Common::ParamPackage& params) override {
  395. const std::string guid = params.Get("guid", "0");
  396. const int port = params.Get("port", 0);
  397. const int axis_x = params.Get("axis_x", 0);
  398. const int axis_y = params.Get("axis_y", 1);
  399. float deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, .99f);
  400. auto joystick = state.GetSDLJoystickByGUID(guid, port);
  401. // This is necessary so accessing GetAxis with axis_x and axis_y won't crash
  402. joystick->SetAxis(axis_x, 0);
  403. joystick->SetAxis(axis_y, 0);
  404. return std::make_unique<SDLAnalog>(joystick, axis_x, axis_y, deadzone);
  405. }
  406. private:
  407. SDLState& state;
  408. };
  409. SDLState::SDLState() {
  410. using namespace Input;
  411. RegisterFactory<ButtonDevice>("sdl", std::make_shared<SDLButtonFactory>(*this));
  412. RegisterFactory<AnalogDevice>("sdl", std::make_shared<SDLAnalogFactory>(*this));
  413. // If the frontend is going to manage the event loop, then we dont start one here
  414. start_thread = !SDL_WasInit(SDL_INIT_JOYSTICK);
  415. if (start_thread && SDL_Init(SDL_INIT_JOYSTICK) < 0) {
  416. LOG_CRITICAL(Input, "SDL_Init(SDL_INIT_JOYSTICK) failed with: {}", SDL_GetError());
  417. return;
  418. }
  419. if (SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1") == SDL_FALSE) {
  420. LOG_ERROR(Input, "Failed to set Hint for background events", SDL_GetError());
  421. }
  422. SDL_AddEventWatch(&SDLEventWatcher, this);
  423. initialized = true;
  424. if (start_thread) {
  425. poll_thread = std::thread([this] {
  426. using namespace std::chrono_literals;
  427. while (initialized) {
  428. SDL_PumpEvents();
  429. std::this_thread::sleep_for(10ms);
  430. }
  431. });
  432. }
  433. // Because the events for joystick connection happens before we have our event watcher added, we
  434. // can just open all the joysticks right here
  435. for (int i = 0; i < SDL_NumJoysticks(); ++i) {
  436. InitJoystick(i);
  437. }
  438. }
  439. SDLState::~SDLState() {
  440. using namespace Input;
  441. UnregisterFactory<ButtonDevice>("sdl");
  442. UnregisterFactory<AnalogDevice>("sdl");
  443. CloseJoysticks();
  444. SDL_DelEventWatch(&SDLEventWatcher, this);
  445. initialized = false;
  446. if (start_thread) {
  447. poll_thread.join();
  448. SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
  449. }
  450. }
  451. Common::ParamPackage SDLEventToButtonParamPackage(SDLState& state, const SDL_Event& event) {
  452. Common::ParamPackage params({{"engine", "sdl"}});
  453. switch (event.type) {
  454. case SDL_JOYAXISMOTION: {
  455. auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
  456. params.Set("port", joystick->GetPort());
  457. params.Set("guid", joystick->GetGUID());
  458. params.Set("axis", event.jaxis.axis);
  459. if (event.jaxis.value > 0) {
  460. params.Set("direction", "+");
  461. params.Set("threshold", "0.5");
  462. } else {
  463. params.Set("direction", "-");
  464. params.Set("threshold", "-0.5");
  465. }
  466. break;
  467. }
  468. case SDL_JOYBUTTONUP: {
  469. auto joystick = state.GetSDLJoystickBySDLID(event.jbutton.which);
  470. params.Set("port", joystick->GetPort());
  471. params.Set("guid", joystick->GetGUID());
  472. params.Set("button", event.jbutton.button);
  473. break;
  474. }
  475. case SDL_JOYHATMOTION: {
  476. auto joystick = state.GetSDLJoystickBySDLID(event.jhat.which);
  477. params.Set("port", joystick->GetPort());
  478. params.Set("guid", joystick->GetGUID());
  479. params.Set("hat", event.jhat.hat);
  480. switch (event.jhat.value) {
  481. case SDL_HAT_UP:
  482. params.Set("direction", "up");
  483. break;
  484. case SDL_HAT_DOWN:
  485. params.Set("direction", "down");
  486. break;
  487. case SDL_HAT_LEFT:
  488. params.Set("direction", "left");
  489. break;
  490. case SDL_HAT_RIGHT:
  491. params.Set("direction", "right");
  492. break;
  493. default:
  494. return {};
  495. }
  496. break;
  497. }
  498. }
  499. return params;
  500. }
  501. namespace Polling {
  502. class SDLPoller : public InputCommon::Polling::DevicePoller {
  503. public:
  504. explicit SDLPoller(SDLState& state_) : state(state_) {}
  505. void Start() override {
  506. state.event_queue.Clear();
  507. state.polling = true;
  508. }
  509. void Stop() override {
  510. state.polling = false;
  511. }
  512. protected:
  513. SDLState& state;
  514. };
  515. class SDLButtonPoller final : public SDLPoller {
  516. public:
  517. explicit SDLButtonPoller(SDLState& state_) : SDLPoller(state_) {}
  518. Common::ParamPackage GetNextInput() override {
  519. SDL_Event event;
  520. while (state.event_queue.Pop(event)) {
  521. switch (event.type) {
  522. case SDL_JOYAXISMOTION:
  523. if (std::abs(event.jaxis.value / 32767.0) < 0.5) {
  524. break;
  525. }
  526. case SDL_JOYBUTTONUP:
  527. case SDL_JOYHATMOTION:
  528. return SDLEventToButtonParamPackage(state, event);
  529. }
  530. }
  531. return {};
  532. }
  533. };
  534. class SDLAnalogPoller final : public SDLPoller {
  535. public:
  536. explicit SDLAnalogPoller(SDLState& state_) : SDLPoller(state_) {}
  537. void Start() override {
  538. SDLPoller::Start();
  539. // Reset stored axes
  540. analog_xaxis = -1;
  541. analog_yaxis = -1;
  542. analog_axes_joystick = -1;
  543. }
  544. Common::ParamPackage GetNextInput() override {
  545. SDL_Event event;
  546. while (state.event_queue.Pop(event)) {
  547. if (event.type != SDL_JOYAXISMOTION || std::abs(event.jaxis.value / 32767.0) < 0.5) {
  548. continue;
  549. }
  550. // An analog device needs two axes, so we need to store the axis for later and wait for
  551. // a second SDL event. The axes also must be from the same joystick.
  552. int axis = event.jaxis.axis;
  553. if (analog_xaxis == -1) {
  554. analog_xaxis = axis;
  555. analog_axes_joystick = event.jaxis.which;
  556. } else if (analog_yaxis == -1 && analog_xaxis != axis &&
  557. analog_axes_joystick == event.jaxis.which) {
  558. analog_yaxis = axis;
  559. }
  560. }
  561. Common::ParamPackage params;
  562. if (analog_xaxis != -1 && analog_yaxis != -1) {
  563. auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
  564. params.Set("engine", "sdl");
  565. params.Set("port", joystick->GetPort());
  566. params.Set("guid", joystick->GetGUID());
  567. params.Set("axis_x", analog_xaxis);
  568. params.Set("axis_y", analog_yaxis);
  569. analog_xaxis = -1;
  570. analog_yaxis = -1;
  571. analog_axes_joystick = -1;
  572. return params;
  573. }
  574. return params;
  575. }
  576. private:
  577. int analog_xaxis = -1;
  578. int analog_yaxis = -1;
  579. SDL_JoystickID analog_axes_joystick = -1;
  580. };
  581. } // namespace Polling
  582. SDLState::Pollers SDLState::GetPollers(InputCommon::Polling::DeviceType type) {
  583. Pollers pollers;
  584. switch (type) {
  585. case InputCommon::Polling::DeviceType::Analog:
  586. pollers.emplace_back(std::make_unique<Polling::SDLAnalogPoller>(*this));
  587. break;
  588. case InputCommon::Polling::DeviceType::Button:
  589. pollers.emplace_back(std::make_unique<Polling::SDLButtonPoller>(*this));
  590. break;
  591. }
  592. return pollers;
  593. }
  594. } // namespace SDL
  595. } // namespace InputCommon