sdl_driver.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. // SPDX-FileCopyrightText: 2018 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "common/logging/log.h"
  4. #include "common/math_util.h"
  5. #include "common/param_package.h"
  6. #include "common/settings.h"
  7. #include "common/thread.h"
  8. #include "common/vector_math.h"
  9. #include "input_common/drivers/sdl_driver.h"
  10. namespace InputCommon {
  11. namespace {
  12. Common::UUID GetGUID(SDL_Joystick* joystick) {
  13. const SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
  14. std::array<u8, 16> data{};
  15. std::memcpy(data.data(), guid.data, sizeof(data));
  16. return Common::UUID{data};
  17. }
  18. } // Anonymous namespace
  19. static int SDLEventWatcher(void* user_data, SDL_Event* event) {
  20. auto* const sdl_state = static_cast<SDLDriver*>(user_data);
  21. sdl_state->HandleGameControllerEvent(*event);
  22. return 0;
  23. }
  24. class SDLJoystick {
  25. public:
  26. SDLJoystick(Common::UUID guid_, int port_, SDL_Joystick* joystick,
  27. SDL_GameController* game_controller)
  28. : guid{guid_}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose},
  29. sdl_controller{game_controller, &SDL_GameControllerClose} {
  30. EnableMotion();
  31. }
  32. void EnableMotion() {
  33. if (sdl_controller) {
  34. SDL_GameController* controller = sdl_controller.get();
  35. has_accel = SDL_GameControllerHasSensor(controller, SDL_SENSOR_ACCEL);
  36. has_gyro = SDL_GameControllerHasSensor(controller, SDL_SENSOR_GYRO);
  37. if (has_accel) {
  38. SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_ACCEL, SDL_TRUE);
  39. }
  40. if (has_gyro) {
  41. SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_GYRO, SDL_TRUE);
  42. }
  43. }
  44. }
  45. bool HasGyro() const {
  46. return has_gyro;
  47. }
  48. bool HasAccel() const {
  49. return has_accel;
  50. }
  51. bool UpdateMotion(SDL_ControllerSensorEvent event) {
  52. constexpr float gravity_constant = 9.80665f;
  53. std::scoped_lock lock{mutex};
  54. const u64 time_difference = event.timestamp - last_motion_update;
  55. last_motion_update = event.timestamp;
  56. switch (event.sensor) {
  57. case SDL_SENSOR_ACCEL: {
  58. motion.accel_x = -event.data[0] / gravity_constant;
  59. motion.accel_y = event.data[2] / gravity_constant;
  60. motion.accel_z = -event.data[1] / gravity_constant;
  61. break;
  62. }
  63. case SDL_SENSOR_GYRO: {
  64. motion.gyro_x = event.data[0] / (Common::PI * 2);
  65. motion.gyro_y = -event.data[2] / (Common::PI * 2);
  66. motion.gyro_z = event.data[1] / (Common::PI * 2);
  67. break;
  68. }
  69. }
  70. // Ignore duplicated timestamps
  71. if (time_difference == 0) {
  72. return false;
  73. }
  74. motion.delta_timestamp = time_difference * 1000;
  75. return true;
  76. }
  77. const BasicMotion& GetMotion() const {
  78. return motion;
  79. }
  80. bool RumblePlay(const Common::Input::VibrationStatus vibration) {
  81. constexpr u32 rumble_max_duration_ms = 1000;
  82. if (sdl_controller) {
  83. return SDL_GameControllerRumble(
  84. sdl_controller.get(), static_cast<u16>(vibration.low_amplitude),
  85. static_cast<u16>(vibration.high_amplitude), rumble_max_duration_ms) != -1;
  86. } else if (sdl_joystick) {
  87. return SDL_JoystickRumble(sdl_joystick.get(), static_cast<u16>(vibration.low_amplitude),
  88. static_cast<u16>(vibration.high_amplitude),
  89. rumble_max_duration_ms) != -1;
  90. }
  91. return false;
  92. }
  93. bool HasHDRumble() const {
  94. if (sdl_controller) {
  95. const auto type = SDL_GameControllerGetType(sdl_controller.get());
  96. return (type == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO) ||
  97. (type == SDL_CONTROLLER_TYPE_PS5);
  98. }
  99. return false;
  100. }
  101. /**
  102. * The Pad identifier of the joystick
  103. */
  104. const PadIdentifier GetPadIdentifier() const {
  105. return {
  106. .guid = guid,
  107. .port = static_cast<std::size_t>(port),
  108. .pad = 0,
  109. };
  110. }
  111. /**
  112. * The guid of the joystick
  113. */
  114. const Common::UUID& GetGUID() const {
  115. return guid;
  116. }
  117. /**
  118. * The number of joystick from the same type that were connected before this joystick
  119. */
  120. int GetPort() const {
  121. return port;
  122. }
  123. SDL_Joystick* GetSDLJoystick() const {
  124. return sdl_joystick.get();
  125. }
  126. SDL_GameController* GetSDLGameController() const {
  127. return sdl_controller.get();
  128. }
  129. void SetSDLJoystick(SDL_Joystick* joystick, SDL_GameController* controller) {
  130. sdl_joystick.reset(joystick);
  131. sdl_controller.reset(controller);
  132. }
  133. bool IsJoyconLeft() const {
  134. const std::string controller_name = GetControllerName();
  135. if (std::strstr(controller_name.c_str(), "Joy-Con Left") != nullptr) {
  136. return true;
  137. }
  138. if (std::strstr(controller_name.c_str(), "Joy-Con (L)") != nullptr) {
  139. return true;
  140. }
  141. return false;
  142. }
  143. bool IsJoyconRight() const {
  144. const std::string controller_name = GetControllerName();
  145. if (std::strstr(controller_name.c_str(), "Joy-Con Right") != nullptr) {
  146. return true;
  147. }
  148. if (std::strstr(controller_name.c_str(), "Joy-Con (R)") != nullptr) {
  149. return true;
  150. }
  151. return false;
  152. }
  153. Common::Input::BatteryLevel GetBatteryLevel() {
  154. const auto level = SDL_JoystickCurrentPowerLevel(sdl_joystick.get());
  155. switch (level) {
  156. case SDL_JOYSTICK_POWER_EMPTY:
  157. return Common::Input::BatteryLevel::Empty;
  158. case SDL_JOYSTICK_POWER_LOW:
  159. return Common::Input::BatteryLevel::Low;
  160. case SDL_JOYSTICK_POWER_MEDIUM:
  161. return Common::Input::BatteryLevel::Medium;
  162. case SDL_JOYSTICK_POWER_FULL:
  163. case SDL_JOYSTICK_POWER_MAX:
  164. return Common::Input::BatteryLevel::Full;
  165. case SDL_JOYSTICK_POWER_WIRED:
  166. return Common::Input::BatteryLevel::Charging;
  167. case SDL_JOYSTICK_POWER_UNKNOWN:
  168. default:
  169. return Common::Input::BatteryLevel::None;
  170. }
  171. }
  172. std::string GetControllerName() const {
  173. if (sdl_controller) {
  174. switch (SDL_GameControllerGetType(sdl_controller.get())) {
  175. case SDL_CONTROLLER_TYPE_XBOX360:
  176. return "Xbox 360 Controller";
  177. case SDL_CONTROLLER_TYPE_XBOXONE:
  178. return "Xbox One Controller";
  179. case SDL_CONTROLLER_TYPE_PS3:
  180. return "DualShock 3 Controller";
  181. case SDL_CONTROLLER_TYPE_PS4:
  182. return "DualShock 4 Controller";
  183. case SDL_CONTROLLER_TYPE_PS5:
  184. return "DualSense Controller";
  185. default:
  186. break;
  187. }
  188. const auto name = SDL_GameControllerName(sdl_controller.get());
  189. if (name) {
  190. return name;
  191. }
  192. }
  193. if (sdl_joystick) {
  194. const auto name = SDL_JoystickName(sdl_joystick.get());
  195. if (name) {
  196. return name;
  197. }
  198. }
  199. return "Unknown";
  200. }
  201. private:
  202. Common::UUID guid;
  203. int port;
  204. std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
  205. std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller;
  206. mutable std::mutex mutex;
  207. u64 last_motion_update{};
  208. bool has_gyro{false};
  209. bool has_accel{false};
  210. BasicMotion motion;
  211. };
  212. std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickByGUID(const Common::UUID& guid, int port) {
  213. std::scoped_lock lock{joystick_map_mutex};
  214. const auto it = joystick_map.find(guid);
  215. if (it != joystick_map.end()) {
  216. while (it->second.size() <= static_cast<std::size_t>(port)) {
  217. auto joystick = std::make_shared<SDLJoystick>(guid, static_cast<int>(it->second.size()),
  218. nullptr, nullptr);
  219. it->second.emplace_back(std::move(joystick));
  220. }
  221. return it->second[static_cast<std::size_t>(port)];
  222. }
  223. auto joystick = std::make_shared<SDLJoystick>(guid, 0, nullptr, nullptr);
  224. return joystick_map[guid].emplace_back(std::move(joystick));
  225. }
  226. std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickByGUID(const std::string& guid, int port) {
  227. return GetSDLJoystickByGUID(Common::UUID{guid}, port);
  228. }
  229. std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickBySDLID(SDL_JoystickID sdl_id) {
  230. auto sdl_joystick = SDL_JoystickFromInstanceID(sdl_id);
  231. const auto guid = GetGUID(sdl_joystick);
  232. std::scoped_lock lock{joystick_map_mutex};
  233. const auto map_it = joystick_map.find(guid);
  234. if (map_it == joystick_map.end()) {
  235. return nullptr;
  236. }
  237. const auto vec_it = std::find_if(map_it->second.begin(), map_it->second.end(),
  238. [&sdl_joystick](const auto& joystick) {
  239. return joystick->GetSDLJoystick() == sdl_joystick;
  240. });
  241. if (vec_it == map_it->second.end()) {
  242. return nullptr;
  243. }
  244. return *vec_it;
  245. }
  246. void SDLDriver::InitJoystick(int joystick_index) {
  247. SDL_Joystick* sdl_joystick = SDL_JoystickOpen(joystick_index);
  248. SDL_GameController* sdl_gamecontroller = nullptr;
  249. if (SDL_IsGameController(joystick_index)) {
  250. sdl_gamecontroller = SDL_GameControllerOpen(joystick_index);
  251. }
  252. if (!sdl_joystick) {
  253. LOG_ERROR(Input, "Failed to open joystick {}", joystick_index);
  254. return;
  255. }
  256. const auto guid = GetGUID(sdl_joystick);
  257. std::scoped_lock lock{joystick_map_mutex};
  258. if (joystick_map.find(guid) == joystick_map.end()) {
  259. auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_gamecontroller);
  260. PreSetController(joystick->GetPadIdentifier());
  261. SetBattery(joystick->GetPadIdentifier(), joystick->GetBatteryLevel());
  262. joystick->EnableMotion();
  263. joystick_map[guid].emplace_back(std::move(joystick));
  264. return;
  265. }
  266. auto& joystick_guid_list = joystick_map[guid];
  267. const auto joystick_it =
  268. std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
  269. [](const auto& joystick) { return !joystick->GetSDLJoystick(); });
  270. if (joystick_it != joystick_guid_list.end()) {
  271. (*joystick_it)->SetSDLJoystick(sdl_joystick, sdl_gamecontroller);
  272. (*joystick_it)->EnableMotion();
  273. return;
  274. }
  275. const int port = static_cast<int>(joystick_guid_list.size());
  276. auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_gamecontroller);
  277. PreSetController(joystick->GetPadIdentifier());
  278. SetBattery(joystick->GetPadIdentifier(), joystick->GetBatteryLevel());
  279. joystick->EnableMotion();
  280. joystick_guid_list.emplace_back(std::move(joystick));
  281. }
  282. void SDLDriver::CloseJoystick(SDL_Joystick* sdl_joystick) {
  283. const auto guid = GetGUID(sdl_joystick);
  284. std::scoped_lock lock{joystick_map_mutex};
  285. // This call to guid is safe since the joystick is guaranteed to be in the map
  286. const auto& joystick_guid_list = joystick_map[guid];
  287. const auto joystick_it = std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
  288. [&sdl_joystick](const auto& joystick) {
  289. return joystick->GetSDLJoystick() == sdl_joystick;
  290. });
  291. if (joystick_it != joystick_guid_list.end()) {
  292. (*joystick_it)->SetSDLJoystick(nullptr, nullptr);
  293. }
  294. }
  295. void SDLDriver::HandleGameControllerEvent(const SDL_Event& event) {
  296. switch (event.type) {
  297. case SDL_JOYBUTTONUP: {
  298. if (const auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  299. const PadIdentifier identifier = joystick->GetPadIdentifier();
  300. SetButton(identifier, event.jbutton.button, false);
  301. }
  302. break;
  303. }
  304. case SDL_JOYBUTTONDOWN: {
  305. if (const auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  306. const PadIdentifier identifier = joystick->GetPadIdentifier();
  307. SetButton(identifier, event.jbutton.button, true);
  308. // Battery doesn't trigger an event so just update every button press
  309. SetBattery(identifier, joystick->GetBatteryLevel());
  310. }
  311. break;
  312. }
  313. case SDL_JOYHATMOTION: {
  314. if (const auto joystick = GetSDLJoystickBySDLID(event.jhat.which)) {
  315. const PadIdentifier identifier = joystick->GetPadIdentifier();
  316. SetHatButton(identifier, event.jhat.hat, event.jhat.value);
  317. }
  318. break;
  319. }
  320. case SDL_JOYAXISMOTION: {
  321. if (const auto joystick = GetSDLJoystickBySDLID(event.jaxis.which)) {
  322. const PadIdentifier identifier = joystick->GetPadIdentifier();
  323. SetAxis(identifier, event.jaxis.axis, event.jaxis.value / 32767.0f);
  324. }
  325. break;
  326. }
  327. case SDL_CONTROLLERSENSORUPDATE: {
  328. if (auto joystick = GetSDLJoystickBySDLID(event.csensor.which)) {
  329. if (joystick->UpdateMotion(event.csensor)) {
  330. const PadIdentifier identifier = joystick->GetPadIdentifier();
  331. SetMotion(identifier, 0, joystick->GetMotion());
  332. }
  333. }
  334. break;
  335. }
  336. case SDL_JOYDEVICEREMOVED:
  337. LOG_DEBUG(Input, "Controller removed with Instance_ID {}", event.jdevice.which);
  338. CloseJoystick(SDL_JoystickFromInstanceID(event.jdevice.which));
  339. break;
  340. case SDL_JOYDEVICEADDED:
  341. LOG_DEBUG(Input, "Controller connected with device index {}", event.jdevice.which);
  342. InitJoystick(event.jdevice.which);
  343. break;
  344. }
  345. }
  346. void SDLDriver::CloseJoysticks() {
  347. std::scoped_lock lock{joystick_map_mutex};
  348. joystick_map.clear();
  349. }
  350. SDLDriver::SDLDriver(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
  351. if (!Settings::values.enable_raw_input) {
  352. // Disable raw input. When enabled this setting causes SDL to die when a web applet opens
  353. SDL_SetHint(SDL_HINT_JOYSTICK_RAWINPUT, "0");
  354. }
  355. // Prevent SDL from adding undesired axis
  356. SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
  357. // Enable HIDAPI rumble. This prevents SDL from disabling motion on PS4 and PS5 controllers
  358. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, "1");
  359. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE, "1");
  360. SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
  361. // Use hidapi driver for joycons. This will allow joycons to be detected as a GameController and
  362. // not a generic one
  363. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, "1");
  364. // Disable hidapi driver for xbox. Already default on Windows, this causes conflict with native
  365. // driver on Linux.
  366. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_XBOX, "0");
  367. // If the frontend is going to manage the event loop, then we don't start one here
  368. start_thread = SDL_WasInit(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) == 0;
  369. if (start_thread && SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
  370. LOG_CRITICAL(Input, "SDL_Init failed with: {}", SDL_GetError());
  371. return;
  372. }
  373. SDL_AddEventWatch(&SDLEventWatcher, this);
  374. initialized = true;
  375. if (start_thread) {
  376. poll_thread = std::thread([this] {
  377. Common::SetCurrentThreadName("SDL_MainLoop");
  378. using namespace std::chrono_literals;
  379. while (initialized) {
  380. SDL_PumpEvents();
  381. std::this_thread::sleep_for(1ms);
  382. }
  383. });
  384. vibration_thread = std::thread([this] {
  385. Common::SetCurrentThreadName("SDL_Vibration");
  386. using namespace std::chrono_literals;
  387. while (initialized) {
  388. SendVibrations();
  389. std::this_thread::sleep_for(10ms);
  390. }
  391. });
  392. }
  393. // Because the events for joystick connection happens before we have our event watcher added, we
  394. // can just open all the joysticks right here
  395. for (int i = 0; i < SDL_NumJoysticks(); ++i) {
  396. InitJoystick(i);
  397. }
  398. }
  399. SDLDriver::~SDLDriver() {
  400. CloseJoysticks();
  401. SDL_DelEventWatch(&SDLEventWatcher, this);
  402. initialized = false;
  403. if (start_thread) {
  404. poll_thread.join();
  405. vibration_thread.join();
  406. SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
  407. }
  408. }
  409. std::vector<Common::ParamPackage> SDLDriver::GetInputDevices() const {
  410. std::vector<Common::ParamPackage> devices;
  411. std::unordered_map<int, std::shared_ptr<SDLJoystick>> joycon_pairs;
  412. for (const auto& [key, value] : joystick_map) {
  413. for (const auto& joystick : value) {
  414. if (!joystick->GetSDLJoystick()) {
  415. continue;
  416. }
  417. const std::string name =
  418. fmt::format("{} {}", joystick->GetControllerName(), joystick->GetPort());
  419. devices.emplace_back(Common::ParamPackage{
  420. {"engine", GetEngineName()},
  421. {"display", std::move(name)},
  422. {"guid", joystick->GetGUID().RawString()},
  423. {"port", std::to_string(joystick->GetPort())},
  424. });
  425. if (joystick->IsJoyconLeft()) {
  426. joycon_pairs.insert_or_assign(joystick->GetPort(), joystick);
  427. }
  428. }
  429. }
  430. // Add dual controllers
  431. for (const auto& [key, value] : joystick_map) {
  432. for (const auto& joystick : value) {
  433. if (joystick->IsJoyconRight()) {
  434. if (!joycon_pairs.contains(joystick->GetPort())) {
  435. continue;
  436. }
  437. const auto joystick2 = joycon_pairs.at(joystick->GetPort());
  438. const std::string name =
  439. fmt::format("{} {}", "Nintendo Dual Joy-Con", joystick->GetPort());
  440. devices.emplace_back(Common::ParamPackage{
  441. {"engine", GetEngineName()},
  442. {"display", std::move(name)},
  443. {"guid", joystick->GetGUID().RawString()},
  444. {"guid2", joystick2->GetGUID().RawString()},
  445. {"port", std::to_string(joystick->GetPort())},
  446. });
  447. }
  448. }
  449. }
  450. return devices;
  451. }
  452. Common::Input::VibrationError SDLDriver::SetRumble(
  453. const PadIdentifier& identifier, const Common::Input::VibrationStatus& vibration) {
  454. const auto joystick =
  455. GetSDLJoystickByGUID(identifier.guid.RawString(), static_cast<int>(identifier.port));
  456. const auto process_amplitude_exp = [](f32 amplitude, f32 factor) {
  457. return (amplitude + std::pow(amplitude, factor)) * 0.5f * 0xFFFF;
  458. };
  459. // Default exponential curve for rumble
  460. f32 factor = 0.35f;
  461. // If vibration is set as a linear output use a flatter value
  462. if (vibration.type == Common::Input::VibrationAmplificationType::Linear) {
  463. factor = 0.5f;
  464. }
  465. // Amplitude for HD rumble needs no modification
  466. if (joystick->HasHDRumble()) {
  467. factor = 1.0f;
  468. }
  469. const Common::Input::VibrationStatus new_vibration{
  470. .low_amplitude = process_amplitude_exp(vibration.low_amplitude, factor),
  471. .low_frequency = vibration.low_frequency,
  472. .high_amplitude = process_amplitude_exp(vibration.high_amplitude, factor),
  473. .high_frequency = vibration.high_frequency,
  474. .type = Common::Input::VibrationAmplificationType::Exponential,
  475. };
  476. if (vibration.type == Common::Input::VibrationAmplificationType::Test) {
  477. if (!joystick->RumblePlay(new_vibration)) {
  478. return Common::Input::VibrationError::Unknown;
  479. }
  480. return Common::Input::VibrationError::None;
  481. }
  482. vibration_queue.Push(VibrationRequest{
  483. .identifier = identifier,
  484. .vibration = new_vibration,
  485. });
  486. return Common::Input::VibrationError::None;
  487. }
  488. void SDLDriver::SendVibrations() {
  489. while (!vibration_queue.Empty()) {
  490. VibrationRequest request;
  491. vibration_queue.Pop(request);
  492. const auto joystick = GetSDLJoystickByGUID(request.identifier.guid.RawString(),
  493. static_cast<int>(request.identifier.port));
  494. joystick->RumblePlay(request.vibration);
  495. }
  496. }
  497. Common::ParamPackage SDLDriver::BuildAnalogParamPackageForButton(int port, const Common::UUID& guid,
  498. s32 axis, float value) const {
  499. Common::ParamPackage params{};
  500. params.Set("engine", GetEngineName());
  501. params.Set("port", port);
  502. params.Set("guid", guid.RawString());
  503. params.Set("axis", axis);
  504. params.Set("threshold", "0.5");
  505. params.Set("invert", value < 0 ? "-" : "+");
  506. return params;
  507. }
  508. Common::ParamPackage SDLDriver::BuildButtonParamPackageForButton(int port, const Common::UUID& guid,
  509. s32 button) const {
  510. Common::ParamPackage params{};
  511. params.Set("engine", GetEngineName());
  512. params.Set("port", port);
  513. params.Set("guid", guid.RawString());
  514. params.Set("button", button);
  515. return params;
  516. }
  517. Common::ParamPackage SDLDriver::BuildHatParamPackageForButton(int port, const Common::UUID& guid,
  518. s32 hat, u8 value) const {
  519. Common::ParamPackage params{};
  520. params.Set("engine", GetEngineName());
  521. params.Set("port", port);
  522. params.Set("guid", guid.RawString());
  523. params.Set("hat", hat);
  524. params.Set("direction", GetHatButtonName(value));
  525. return params;
  526. }
  527. Common::ParamPackage SDLDriver::BuildMotionParam(int port, const Common::UUID& guid) const {
  528. Common::ParamPackage params{};
  529. params.Set("engine", GetEngineName());
  530. params.Set("motion", 0);
  531. params.Set("port", port);
  532. params.Set("guid", guid.RawString());
  533. return params;
  534. }
  535. Common::ParamPackage SDLDriver::BuildParamPackageForBinding(
  536. int port, const Common::UUID& guid, const SDL_GameControllerButtonBind& binding) const {
  537. switch (binding.bindType) {
  538. case SDL_CONTROLLER_BINDTYPE_NONE:
  539. break;
  540. case SDL_CONTROLLER_BINDTYPE_AXIS:
  541. return BuildAnalogParamPackageForButton(port, guid, binding.value.axis);
  542. case SDL_CONTROLLER_BINDTYPE_BUTTON:
  543. return BuildButtonParamPackageForButton(port, guid, binding.value.button);
  544. case SDL_CONTROLLER_BINDTYPE_HAT:
  545. return BuildHatParamPackageForButton(port, guid, binding.value.hat.hat,
  546. static_cast<u8>(binding.value.hat.hat_mask));
  547. }
  548. return {};
  549. }
  550. Common::ParamPackage SDLDriver::BuildParamPackageForAnalog(PadIdentifier identifier, int axis_x,
  551. int axis_y, float offset_x,
  552. float offset_y) const {
  553. Common::ParamPackage params;
  554. params.Set("engine", GetEngineName());
  555. params.Set("port", static_cast<int>(identifier.port));
  556. params.Set("guid", identifier.guid.RawString());
  557. params.Set("axis_x", axis_x);
  558. params.Set("axis_y", axis_y);
  559. params.Set("offset_x", offset_x);
  560. params.Set("offset_y", offset_y);
  561. params.Set("invert_x", "+");
  562. params.Set("invert_y", "+");
  563. return params;
  564. }
  565. ButtonMapping SDLDriver::GetButtonMappingForDevice(const Common::ParamPackage& params) {
  566. if (!params.Has("guid") || !params.Has("port")) {
  567. return {};
  568. }
  569. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  570. auto* controller = joystick->GetSDLGameController();
  571. if (controller == nullptr) {
  572. return {};
  573. }
  574. // This list is missing ZL/ZR since those are not considered buttons in SDL GameController.
  575. // We will add those afterwards
  576. // This list also excludes Screenshot since theres not really a mapping for that
  577. ButtonBindings switch_to_sdl_button;
  578. if (SDL_GameControllerGetType(controller) == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO) {
  579. switch_to_sdl_button = GetNintendoButtonBinding(joystick);
  580. } else {
  581. switch_to_sdl_button = GetDefaultButtonBinding();
  582. }
  583. // Add the missing bindings for ZL/ZR
  584. static constexpr ZButtonBindings switch_to_sdl_axis{{
  585. {Settings::NativeButton::ZL, SDL_CONTROLLER_AXIS_TRIGGERLEFT},
  586. {Settings::NativeButton::ZR, SDL_CONTROLLER_AXIS_TRIGGERRIGHT},
  587. }};
  588. // Parameters contain two joysticks return dual
  589. if (params.Has("guid2")) {
  590. const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
  591. if (joystick2->GetSDLGameController() != nullptr) {
  592. return GetDualControllerMapping(joystick, joystick2, switch_to_sdl_button,
  593. switch_to_sdl_axis);
  594. }
  595. }
  596. return GetSingleControllerMapping(joystick, switch_to_sdl_button, switch_to_sdl_axis);
  597. }
  598. ButtonBindings SDLDriver::GetDefaultButtonBinding() const {
  599. return {
  600. std::pair{Settings::NativeButton::A, SDL_CONTROLLER_BUTTON_B},
  601. {Settings::NativeButton::B, SDL_CONTROLLER_BUTTON_A},
  602. {Settings::NativeButton::X, SDL_CONTROLLER_BUTTON_Y},
  603. {Settings::NativeButton::Y, SDL_CONTROLLER_BUTTON_X},
  604. {Settings::NativeButton::LStick, SDL_CONTROLLER_BUTTON_LEFTSTICK},
  605. {Settings::NativeButton::RStick, SDL_CONTROLLER_BUTTON_RIGHTSTICK},
  606. {Settings::NativeButton::L, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  607. {Settings::NativeButton::R, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  608. {Settings::NativeButton::Plus, SDL_CONTROLLER_BUTTON_START},
  609. {Settings::NativeButton::Minus, SDL_CONTROLLER_BUTTON_BACK},
  610. {Settings::NativeButton::DLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT},
  611. {Settings::NativeButton::DUp, SDL_CONTROLLER_BUTTON_DPAD_UP},
  612. {Settings::NativeButton::DRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT},
  613. {Settings::NativeButton::DDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN},
  614. {Settings::NativeButton::SL, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  615. {Settings::NativeButton::SR, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  616. {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
  617. {Settings::NativeButton::Screenshot, SDL_CONTROLLER_BUTTON_MISC1},
  618. };
  619. }
  620. ButtonBindings SDLDriver::GetNintendoButtonBinding(
  621. const std::shared_ptr<SDLJoystick>& joystick) const {
  622. // Default SL/SR mapping for pro controllers
  623. auto sl_button = SDL_CONTROLLER_BUTTON_LEFTSHOULDER;
  624. auto sr_button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;
  625. if (joystick->IsJoyconLeft()) {
  626. sl_button = SDL_CONTROLLER_BUTTON_PADDLE2;
  627. sr_button = SDL_CONTROLLER_BUTTON_PADDLE4;
  628. }
  629. if (joystick->IsJoyconRight()) {
  630. sl_button = SDL_CONTROLLER_BUTTON_PADDLE3;
  631. sr_button = SDL_CONTROLLER_BUTTON_PADDLE1;
  632. }
  633. return {
  634. std::pair{Settings::NativeButton::A, SDL_CONTROLLER_BUTTON_A},
  635. {Settings::NativeButton::B, SDL_CONTROLLER_BUTTON_B},
  636. {Settings::NativeButton::X, SDL_CONTROLLER_BUTTON_X},
  637. {Settings::NativeButton::Y, SDL_CONTROLLER_BUTTON_Y},
  638. {Settings::NativeButton::LStick, SDL_CONTROLLER_BUTTON_LEFTSTICK},
  639. {Settings::NativeButton::RStick, SDL_CONTROLLER_BUTTON_RIGHTSTICK},
  640. {Settings::NativeButton::L, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  641. {Settings::NativeButton::R, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  642. {Settings::NativeButton::Plus, SDL_CONTROLLER_BUTTON_START},
  643. {Settings::NativeButton::Minus, SDL_CONTROLLER_BUTTON_BACK},
  644. {Settings::NativeButton::DLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT},
  645. {Settings::NativeButton::DUp, SDL_CONTROLLER_BUTTON_DPAD_UP},
  646. {Settings::NativeButton::DRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT},
  647. {Settings::NativeButton::DDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN},
  648. {Settings::NativeButton::SL, sl_button},
  649. {Settings::NativeButton::SR, sr_button},
  650. {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
  651. {Settings::NativeButton::Screenshot, SDL_CONTROLLER_BUTTON_MISC1},
  652. };
  653. }
  654. ButtonMapping SDLDriver::GetSingleControllerMapping(
  655. const std::shared_ptr<SDLJoystick>& joystick, const ButtonBindings& switch_to_sdl_button,
  656. const ZButtonBindings& switch_to_sdl_axis) const {
  657. ButtonMapping mapping;
  658. mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());
  659. auto* controller = joystick->GetSDLGameController();
  660. for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
  661. const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
  662. mapping.insert_or_assign(
  663. switch_button,
  664. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  665. }
  666. for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
  667. const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
  668. mapping.insert_or_assign(
  669. switch_button,
  670. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  671. }
  672. return mapping;
  673. }
  674. ButtonMapping SDLDriver::GetDualControllerMapping(const std::shared_ptr<SDLJoystick>& joystick,
  675. const std::shared_ptr<SDLJoystick>& joystick2,
  676. const ButtonBindings& switch_to_sdl_button,
  677. const ZButtonBindings& switch_to_sdl_axis) const {
  678. ButtonMapping mapping;
  679. mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());
  680. auto* controller = joystick->GetSDLGameController();
  681. auto* controller2 = joystick2->GetSDLGameController();
  682. for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
  683. if (IsButtonOnLeftSide(switch_button)) {
  684. const auto& binding = SDL_GameControllerGetBindForButton(controller2, sdl_button);
  685. mapping.insert_or_assign(
  686. switch_button,
  687. BuildParamPackageForBinding(joystick2->GetPort(), joystick2->GetGUID(), binding));
  688. continue;
  689. }
  690. const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
  691. mapping.insert_or_assign(
  692. switch_button,
  693. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  694. }
  695. for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
  696. if (IsButtonOnLeftSide(switch_button)) {
  697. const auto& binding = SDL_GameControllerGetBindForAxis(controller2, sdl_axis);
  698. mapping.insert_or_assign(
  699. switch_button,
  700. BuildParamPackageForBinding(joystick2->GetPort(), joystick2->GetGUID(), binding));
  701. continue;
  702. }
  703. const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
  704. mapping.insert_or_assign(
  705. switch_button,
  706. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  707. }
  708. return mapping;
  709. }
  710. bool SDLDriver::IsButtonOnLeftSide(Settings::NativeButton::Values button) const {
  711. switch (button) {
  712. case Settings::NativeButton::DDown:
  713. case Settings::NativeButton::DLeft:
  714. case Settings::NativeButton::DRight:
  715. case Settings::NativeButton::DUp:
  716. case Settings::NativeButton::L:
  717. case Settings::NativeButton::LStick:
  718. case Settings::NativeButton::Minus:
  719. case Settings::NativeButton::Screenshot:
  720. case Settings::NativeButton::ZL:
  721. return true;
  722. default:
  723. return false;
  724. }
  725. }
  726. AnalogMapping SDLDriver::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
  727. if (!params.Has("guid") || !params.Has("port")) {
  728. return {};
  729. }
  730. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  731. const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
  732. auto* controller = joystick->GetSDLGameController();
  733. if (controller == nullptr) {
  734. return {};
  735. }
  736. AnalogMapping mapping = {};
  737. const auto& binding_left_x =
  738. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
  739. const auto& binding_left_y =
  740. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
  741. if (params.Has("guid2")) {
  742. const auto identifier = joystick2->GetPadIdentifier();
  743. PreSetController(identifier);
  744. PreSetAxis(identifier, binding_left_x.value.axis);
  745. PreSetAxis(identifier, binding_left_y.value.axis);
  746. const auto left_offset_x = -GetAxis(identifier, binding_left_x.value.axis);
  747. const auto left_offset_y = GetAxis(identifier, binding_left_y.value.axis);
  748. mapping.insert_or_assign(Settings::NativeAnalog::LStick,
  749. BuildParamPackageForAnalog(identifier, binding_left_x.value.axis,
  750. binding_left_y.value.axis,
  751. left_offset_x, left_offset_y));
  752. } else {
  753. const auto identifier = joystick->GetPadIdentifier();
  754. PreSetController(identifier);
  755. PreSetAxis(identifier, binding_left_x.value.axis);
  756. PreSetAxis(identifier, binding_left_y.value.axis);
  757. const auto left_offset_x = -GetAxis(identifier, binding_left_x.value.axis);
  758. const auto left_offset_y = GetAxis(identifier, binding_left_y.value.axis);
  759. mapping.insert_or_assign(Settings::NativeAnalog::LStick,
  760. BuildParamPackageForAnalog(identifier, binding_left_x.value.axis,
  761. binding_left_y.value.axis,
  762. left_offset_x, left_offset_y));
  763. }
  764. const auto& binding_right_x =
  765. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
  766. const auto& binding_right_y =
  767. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
  768. const auto identifier = joystick->GetPadIdentifier();
  769. PreSetController(identifier);
  770. PreSetAxis(identifier, binding_right_x.value.axis);
  771. PreSetAxis(identifier, binding_right_y.value.axis);
  772. const auto right_offset_x = -GetAxis(identifier, binding_right_x.value.axis);
  773. const auto right_offset_y = GetAxis(identifier, binding_right_y.value.axis);
  774. mapping.insert_or_assign(Settings::NativeAnalog::RStick,
  775. BuildParamPackageForAnalog(identifier, binding_right_x.value.axis,
  776. binding_right_y.value.axis, right_offset_x,
  777. right_offset_y));
  778. return mapping;
  779. }
  780. MotionMapping SDLDriver::GetMotionMappingForDevice(const Common::ParamPackage& params) {
  781. if (!params.Has("guid") || !params.Has("port")) {
  782. return {};
  783. }
  784. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  785. const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
  786. auto* controller = joystick->GetSDLGameController();
  787. if (controller == nullptr) {
  788. return {};
  789. }
  790. MotionMapping mapping = {};
  791. joystick->EnableMotion();
  792. if (joystick->HasGyro() || joystick->HasAccel()) {
  793. mapping.insert_or_assign(Settings::NativeMotion::MotionRight,
  794. BuildMotionParam(joystick->GetPort(), joystick->GetGUID()));
  795. }
  796. if (params.Has("guid2")) {
  797. joystick2->EnableMotion();
  798. if (joystick2->HasGyro() || joystick2->HasAccel()) {
  799. mapping.insert_or_assign(Settings::NativeMotion::MotionLeft,
  800. BuildMotionParam(joystick2->GetPort(), joystick2->GetGUID()));
  801. }
  802. } else {
  803. if (joystick->HasGyro() || joystick->HasAccel()) {
  804. mapping.insert_or_assign(Settings::NativeMotion::MotionLeft,
  805. BuildMotionParam(joystick->GetPort(), joystick->GetGUID()));
  806. }
  807. }
  808. return mapping;
  809. }
  810. Common::Input::ButtonNames SDLDriver::GetUIName(const Common::ParamPackage& params) const {
  811. if (params.Has("button")) {
  812. // TODO(German77): Find how to substitue the values for real button names
  813. return Common::Input::ButtonNames::Value;
  814. }
  815. if (params.Has("hat")) {
  816. return Common::Input::ButtonNames::Value;
  817. }
  818. if (params.Has("axis")) {
  819. return Common::Input::ButtonNames::Value;
  820. }
  821. if (params.Has("axis_x") && params.Has("axis_y") && params.Has("axis_z")) {
  822. return Common::Input::ButtonNames::Value;
  823. }
  824. if (params.Has("motion")) {
  825. return Common::Input::ButtonNames::Engine;
  826. }
  827. return Common::Input::ButtonNames::Invalid;
  828. }
  829. std::string SDLDriver::GetHatButtonName(u8 direction_value) const {
  830. switch (direction_value) {
  831. case SDL_HAT_UP:
  832. return "up";
  833. case SDL_HAT_DOWN:
  834. return "down";
  835. case SDL_HAT_LEFT:
  836. return "left";
  837. case SDL_HAT_RIGHT:
  838. return "right";
  839. default:
  840. return {};
  841. }
  842. }
  843. u8 SDLDriver::GetHatButtonId(const std::string& direction_name) const {
  844. Uint8 direction;
  845. if (direction_name == "up") {
  846. direction = SDL_HAT_UP;
  847. } else if (direction_name == "down") {
  848. direction = SDL_HAT_DOWN;
  849. } else if (direction_name == "left") {
  850. direction = SDL_HAT_LEFT;
  851. } else if (direction_name == "right") {
  852. direction = SDL_HAT_RIGHT;
  853. } else {
  854. direction = 0;
  855. }
  856. return direction;
  857. }
  858. bool SDLDriver::IsStickInverted(const Common::ParamPackage& params) {
  859. if (!params.Has("guid") || !params.Has("port")) {
  860. return false;
  861. }
  862. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  863. if (joystick == nullptr) {
  864. return false;
  865. }
  866. auto* controller = joystick->GetSDLGameController();
  867. if (controller == nullptr) {
  868. return false;
  869. }
  870. const auto& axis_x = params.Get("axis_x", 0);
  871. const auto& axis_y = params.Get("axis_y", 0);
  872. const auto& binding_left_x =
  873. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
  874. const auto& binding_right_x =
  875. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
  876. const auto& binding_left_y =
  877. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
  878. const auto& binding_right_y =
  879. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
  880. if (axis_x != binding_left_y.value.axis && axis_x != binding_right_y.value.axis) {
  881. return false;
  882. }
  883. if (axis_y != binding_left_x.value.axis && axis_y != binding_right_x.value.axis) {
  884. return false;
  885. }
  886. return true;
  887. }
  888. } // namespace InputCommon