emulated_controller.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <common/scope_exit.h>
  5. #include "common/polyfill_ranges.h"
  6. #include "common/thread.h"
  7. #include "hid_core/frontend/emulated_controller.h"
  8. #include "hid_core/frontend/input_converter.h"
  9. #include "hid_core/hid_util.h"
  10. namespace Core::HID {
  11. constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
  12. constexpr s32 HID_TRIGGER_MAX = 0x7fff;
  13. constexpr u32 TURBO_BUTTON_DELAY = 4;
  14. // Use a common UUID for TAS and Virtual Gamepad
  15. constexpr Common::UUID TAS_UUID =
  16. Common::UUID{{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xA5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
  17. constexpr Common::UUID VIRTUAL_UUID =
  18. Common::UUID{{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
  19. EmulatedController::EmulatedController(NpadIdType npad_id_type_) : npad_id_type(npad_id_type_) {}
  20. EmulatedController::~EmulatedController() = default;
  21. NpadStyleIndex EmulatedController::MapSettingsTypeToNPad(Settings::ControllerType type) {
  22. switch (type) {
  23. case Settings::ControllerType::ProController:
  24. return NpadStyleIndex::Fullkey;
  25. case Settings::ControllerType::DualJoyconDetached:
  26. return NpadStyleIndex::JoyconDual;
  27. case Settings::ControllerType::LeftJoycon:
  28. return NpadStyleIndex::JoyconLeft;
  29. case Settings::ControllerType::RightJoycon:
  30. return NpadStyleIndex::JoyconRight;
  31. case Settings::ControllerType::Handheld:
  32. return NpadStyleIndex::Handheld;
  33. case Settings::ControllerType::GameCube:
  34. return NpadStyleIndex::GameCube;
  35. case Settings::ControllerType::Pokeball:
  36. return NpadStyleIndex::Pokeball;
  37. case Settings::ControllerType::NES:
  38. return NpadStyleIndex::NES;
  39. case Settings::ControllerType::SNES:
  40. return NpadStyleIndex::SNES;
  41. case Settings::ControllerType::N64:
  42. return NpadStyleIndex::N64;
  43. case Settings::ControllerType::SegaGenesis:
  44. return NpadStyleIndex::SegaGenesis;
  45. default:
  46. return NpadStyleIndex::Fullkey;
  47. }
  48. }
  49. Settings::ControllerType EmulatedController::MapNPadToSettingsType(NpadStyleIndex type) {
  50. switch (type) {
  51. case NpadStyleIndex::Fullkey:
  52. return Settings::ControllerType::ProController;
  53. case NpadStyleIndex::JoyconDual:
  54. return Settings::ControllerType::DualJoyconDetached;
  55. case NpadStyleIndex::JoyconLeft:
  56. return Settings::ControllerType::LeftJoycon;
  57. case NpadStyleIndex::JoyconRight:
  58. return Settings::ControllerType::RightJoycon;
  59. case NpadStyleIndex::Handheld:
  60. return Settings::ControllerType::Handheld;
  61. case NpadStyleIndex::GameCube:
  62. return Settings::ControllerType::GameCube;
  63. case NpadStyleIndex::Pokeball:
  64. return Settings::ControllerType::Pokeball;
  65. case NpadStyleIndex::NES:
  66. return Settings::ControllerType::NES;
  67. case NpadStyleIndex::SNES:
  68. return Settings::ControllerType::SNES;
  69. case NpadStyleIndex::N64:
  70. return Settings::ControllerType::N64;
  71. case NpadStyleIndex::SegaGenesis:
  72. return Settings::ControllerType::SegaGenesis;
  73. default:
  74. return Settings::ControllerType::ProController;
  75. }
  76. }
  77. void EmulatedController::ReloadFromSettings() {
  78. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  79. const auto& player = Settings::values.players.GetValue()[player_index];
  80. for (std::size_t index = 0; index < player.buttons.size(); ++index) {
  81. button_params[index] = Common::ParamPackage(player.buttons[index]);
  82. }
  83. for (std::size_t index = 0; index < player.analogs.size(); ++index) {
  84. stick_params[index] = Common::ParamPackage(player.analogs[index]);
  85. }
  86. for (std::size_t index = 0; index < player.motions.size(); ++index) {
  87. motion_params[index] = Common::ParamPackage(player.motions[index]);
  88. }
  89. controller.color_values = {};
  90. ReloadColorsFromSettings();
  91. ring_params[0] = Common::ParamPackage(Settings::values.ringcon_analogs);
  92. // Other or debug controller should always be a pro controller
  93. if (npad_id_type != NpadIdType::Other) {
  94. SetNpadStyleIndex(MapSettingsTypeToNPad(player.controller_type));
  95. original_npad_type = npad_type;
  96. } else {
  97. SetNpadStyleIndex(NpadStyleIndex::Fullkey);
  98. original_npad_type = npad_type;
  99. }
  100. SetPollingMode(EmulatedDeviceIndex::RightIndex, Common::Input::PollingMode::Active);
  101. Disconnect();
  102. if (player.connected) {
  103. Connect();
  104. }
  105. ReloadInput();
  106. }
  107. void EmulatedController::ReloadColorsFromSettings() {
  108. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  109. const auto& player = Settings::values.players.GetValue()[player_index];
  110. // Avoid updating colors if overridden by physical controller
  111. if (controller.color_values[LeftIndex].body != 0 &&
  112. controller.color_values[RightIndex].body != 0) {
  113. return;
  114. }
  115. controller.colors_state.fullkey = {
  116. .body = GetNpadColor(player.body_color_left),
  117. .button = GetNpadColor(player.button_color_left),
  118. };
  119. controller.colors_state.left = {
  120. .body = GetNpadColor(player.body_color_left),
  121. .button = GetNpadColor(player.button_color_left),
  122. };
  123. controller.colors_state.right = {
  124. .body = GetNpadColor(player.body_color_right),
  125. .button = GetNpadColor(player.button_color_right),
  126. };
  127. }
  128. void EmulatedController::LoadDevices() {
  129. // TODO(german77): Use more buttons to detect the correct device
  130. const auto& left_joycon = button_params[Settings::NativeButton::DRight];
  131. const auto& right_joycon = button_params[Settings::NativeButton::A];
  132. // Triggers for GC controllers
  133. trigger_params[LeftIndex] = button_params[Settings::NativeButton::ZL];
  134. trigger_params[RightIndex] = button_params[Settings::NativeButton::ZR];
  135. color_params[LeftIndex] = left_joycon;
  136. color_params[RightIndex] = right_joycon;
  137. color_params[LeftIndex].Set("color", true);
  138. color_params[RightIndex].Set("color", true);
  139. battery_params[LeftIndex] = left_joycon;
  140. battery_params[RightIndex] = right_joycon;
  141. battery_params[LeftIndex].Set("battery", true);
  142. battery_params[RightIndex].Set("battery", true);
  143. camera_params[0] = right_joycon;
  144. camera_params[0].Set("camera", true);
  145. nfc_params[1] = right_joycon;
  146. nfc_params[1].Set("nfc", true);
  147. // Only map virtual devices to the first controller
  148. if (npad_id_type == NpadIdType::Player1 || npad_id_type == NpadIdType::Handheld) {
  149. camera_params[1] = Common::ParamPackage{"engine:camera,camera:1"};
  150. ring_params[1] = Common::ParamPackage{"engine:joycon,axis_x:100,axis_y:101"};
  151. nfc_params[0] = Common::ParamPackage{"engine:virtual_amiibo,nfc:1"};
  152. }
  153. output_params[LeftIndex] = left_joycon;
  154. output_params[RightIndex] = right_joycon;
  155. output_params[2] = camera_params[1];
  156. output_params[3] = nfc_params[0];
  157. output_params[LeftIndex].Set("output", true);
  158. output_params[RightIndex].Set("output", true);
  159. output_params[2].Set("output", true);
  160. output_params[3].Set("output", true);
  161. LoadTASParams();
  162. LoadVirtualGamepadParams();
  163. std::ranges::transform(button_params, button_devices.begin(), Common::Input::CreateInputDevice);
  164. std::ranges::transform(stick_params, stick_devices.begin(), Common::Input::CreateInputDevice);
  165. std::ranges::transform(motion_params, motion_devices.begin(), Common::Input::CreateInputDevice);
  166. std::ranges::transform(trigger_params, trigger_devices.begin(),
  167. Common::Input::CreateInputDevice);
  168. std::ranges::transform(battery_params, battery_devices.begin(),
  169. Common::Input::CreateInputDevice);
  170. std::ranges::transform(color_params, color_devices.begin(), Common::Input::CreateInputDevice);
  171. std::ranges::transform(camera_params, camera_devices.begin(), Common::Input::CreateInputDevice);
  172. std::ranges::transform(ring_params, ring_analog_devices.begin(),
  173. Common::Input::CreateInputDevice);
  174. std::ranges::transform(nfc_params, nfc_devices.begin(), Common::Input::CreateInputDevice);
  175. std::ranges::transform(output_params, output_devices.begin(),
  176. Common::Input::CreateOutputDevice);
  177. // Initialize TAS devices
  178. std::ranges::transform(tas_button_params, tas_button_devices.begin(),
  179. Common::Input::CreateInputDevice);
  180. std::ranges::transform(tas_stick_params, tas_stick_devices.begin(),
  181. Common::Input::CreateInputDevice);
  182. // Initialize virtual gamepad devices
  183. std::ranges::transform(virtual_button_params, virtual_button_devices.begin(),
  184. Common::Input::CreateInputDevice);
  185. std::ranges::transform(virtual_stick_params, virtual_stick_devices.begin(),
  186. Common::Input::CreateInputDevice);
  187. std::ranges::transform(virtual_motion_params, virtual_motion_devices.begin(),
  188. Common::Input::CreateInputDevice);
  189. }
  190. void EmulatedController::LoadTASParams() {
  191. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  192. Common::ParamPackage common_params{};
  193. common_params.Set("engine", "tas");
  194. common_params.Set("port", static_cast<int>(player_index));
  195. for (auto& param : tas_button_params) {
  196. param = common_params;
  197. }
  198. for (auto& param : tas_stick_params) {
  199. param = common_params;
  200. }
  201. // TODO(german77): Replace this with an input profile or something better
  202. tas_button_params[Settings::NativeButton::A].Set("button", 0);
  203. tas_button_params[Settings::NativeButton::B].Set("button", 1);
  204. tas_button_params[Settings::NativeButton::X].Set("button", 2);
  205. tas_button_params[Settings::NativeButton::Y].Set("button", 3);
  206. tas_button_params[Settings::NativeButton::LStick].Set("button", 4);
  207. tas_button_params[Settings::NativeButton::RStick].Set("button", 5);
  208. tas_button_params[Settings::NativeButton::L].Set("button", 6);
  209. tas_button_params[Settings::NativeButton::R].Set("button", 7);
  210. tas_button_params[Settings::NativeButton::ZL].Set("button", 8);
  211. tas_button_params[Settings::NativeButton::ZR].Set("button", 9);
  212. tas_button_params[Settings::NativeButton::Plus].Set("button", 10);
  213. tas_button_params[Settings::NativeButton::Minus].Set("button", 11);
  214. tas_button_params[Settings::NativeButton::DLeft].Set("button", 12);
  215. tas_button_params[Settings::NativeButton::DUp].Set("button", 13);
  216. tas_button_params[Settings::NativeButton::DRight].Set("button", 14);
  217. tas_button_params[Settings::NativeButton::DDown].Set("button", 15);
  218. tas_button_params[Settings::NativeButton::SLLeft].Set("button", 16);
  219. tas_button_params[Settings::NativeButton::SRLeft].Set("button", 17);
  220. tas_button_params[Settings::NativeButton::Home].Set("button", 18);
  221. tas_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
  222. tas_button_params[Settings::NativeButton::SLRight].Set("button", 20);
  223. tas_button_params[Settings::NativeButton::SRRight].Set("button", 21);
  224. tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
  225. tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
  226. tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
  227. tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
  228. // set to optimal stick to avoid sanitizing the stick and tweaking the coordinates
  229. // making sure they play back in the game as originally written down in the script file
  230. tas_stick_params[Settings::NativeAnalog::LStick].Set("deadzone", 0.0f);
  231. tas_stick_params[Settings::NativeAnalog::LStick].Set("range", 1.0f);
  232. tas_stick_params[Settings::NativeAnalog::RStick].Set("deadzone", 0.0f);
  233. tas_stick_params[Settings::NativeAnalog::RStick].Set("range", 1.0f);
  234. }
  235. void EmulatedController::LoadVirtualGamepadParams() {
  236. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  237. Common::ParamPackage common_params{};
  238. common_params.Set("engine", "virtual_gamepad");
  239. common_params.Set("port", static_cast<int>(player_index));
  240. for (auto& param : virtual_button_params) {
  241. param = common_params;
  242. }
  243. for (auto& param : virtual_stick_params) {
  244. param = common_params;
  245. }
  246. for (auto& param : virtual_stick_params) {
  247. param = common_params;
  248. }
  249. for (auto& param : virtual_motion_params) {
  250. param = common_params;
  251. }
  252. // TODO(german77): Replace this with an input profile or something better
  253. virtual_button_params[Settings::NativeButton::A].Set("button", 0);
  254. virtual_button_params[Settings::NativeButton::B].Set("button", 1);
  255. virtual_button_params[Settings::NativeButton::X].Set("button", 2);
  256. virtual_button_params[Settings::NativeButton::Y].Set("button", 3);
  257. virtual_button_params[Settings::NativeButton::LStick].Set("button", 4);
  258. virtual_button_params[Settings::NativeButton::RStick].Set("button", 5);
  259. virtual_button_params[Settings::NativeButton::L].Set("button", 6);
  260. virtual_button_params[Settings::NativeButton::R].Set("button", 7);
  261. virtual_button_params[Settings::NativeButton::ZL].Set("button", 8);
  262. virtual_button_params[Settings::NativeButton::ZR].Set("button", 9);
  263. virtual_button_params[Settings::NativeButton::Plus].Set("button", 10);
  264. virtual_button_params[Settings::NativeButton::Minus].Set("button", 11);
  265. virtual_button_params[Settings::NativeButton::DLeft].Set("button", 12);
  266. virtual_button_params[Settings::NativeButton::DUp].Set("button", 13);
  267. virtual_button_params[Settings::NativeButton::DRight].Set("button", 14);
  268. virtual_button_params[Settings::NativeButton::DDown].Set("button", 15);
  269. virtual_button_params[Settings::NativeButton::SLLeft].Set("button", 16);
  270. virtual_button_params[Settings::NativeButton::SRLeft].Set("button", 17);
  271. virtual_button_params[Settings::NativeButton::Home].Set("button", 18);
  272. virtual_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
  273. virtual_button_params[Settings::NativeButton::SLRight].Set("button", 20);
  274. virtual_button_params[Settings::NativeButton::SRRight].Set("button", 21);
  275. virtual_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
  276. virtual_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
  277. virtual_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
  278. virtual_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
  279. virtual_stick_params[Settings::NativeAnalog::LStick].Set("deadzone", 0.0f);
  280. virtual_stick_params[Settings::NativeAnalog::LStick].Set("range", 1.0f);
  281. virtual_stick_params[Settings::NativeAnalog::RStick].Set("deadzone", 0.0f);
  282. virtual_stick_params[Settings::NativeAnalog::RStick].Set("range", 1.0f);
  283. virtual_motion_params[Settings::NativeMotion::MotionLeft].Set("motion", 0);
  284. virtual_motion_params[Settings::NativeMotion::MotionRight].Set("motion", 0);
  285. }
  286. void EmulatedController::ReloadInput() {
  287. // If you load any device here add the equivalent to the UnloadInput() function
  288. LoadDevices();
  289. for (std::size_t index = 0; index < button_devices.size(); ++index) {
  290. if (!button_devices[index]) {
  291. continue;
  292. }
  293. const auto uuid = Common::UUID{button_params[index].Get("guid", "")};
  294. button_devices[index]->SetCallback({
  295. .on_change =
  296. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  297. SetButton(callback, index, uuid);
  298. },
  299. });
  300. button_devices[index]->ForceUpdate();
  301. }
  302. for (std::size_t index = 0; index < stick_devices.size(); ++index) {
  303. if (!stick_devices[index]) {
  304. continue;
  305. }
  306. const auto uuid = Common::UUID{stick_params[index].Get("guid", "")};
  307. stick_devices[index]->SetCallback({
  308. .on_change =
  309. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  310. SetStick(callback, index, uuid);
  311. },
  312. });
  313. stick_devices[index]->ForceUpdate();
  314. }
  315. for (std::size_t index = 0; index < trigger_devices.size(); ++index) {
  316. if (!trigger_devices[index]) {
  317. continue;
  318. }
  319. const auto uuid = Common::UUID{trigger_params[index].Get("guid", "")};
  320. trigger_devices[index]->SetCallback({
  321. .on_change =
  322. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  323. SetTrigger(callback, index, uuid);
  324. },
  325. });
  326. trigger_devices[index]->ForceUpdate();
  327. }
  328. for (std::size_t index = 0; index < battery_devices.size(); ++index) {
  329. if (!battery_devices[index]) {
  330. continue;
  331. }
  332. battery_devices[index]->SetCallback({
  333. .on_change =
  334. [this, index](const Common::Input::CallbackStatus& callback) {
  335. SetBattery(callback, index);
  336. },
  337. });
  338. battery_devices[index]->ForceUpdate();
  339. }
  340. for (std::size_t index = 0; index < color_devices.size(); ++index) {
  341. if (!color_devices[index]) {
  342. continue;
  343. }
  344. color_devices[index]->SetCallback({
  345. .on_change =
  346. [this, index](const Common::Input::CallbackStatus& callback) {
  347. SetColors(callback, index);
  348. },
  349. });
  350. color_devices[index]->ForceUpdate();
  351. }
  352. for (std::size_t index = 0; index < motion_devices.size(); ++index) {
  353. if (!motion_devices[index]) {
  354. continue;
  355. }
  356. motion_devices[index]->SetCallback({
  357. .on_change =
  358. [this, index](const Common::Input::CallbackStatus& callback) {
  359. SetMotion(callback, index);
  360. },
  361. });
  362. // Restore motion state
  363. auto& emulated_motion = controller.motion_values[index].emulated;
  364. auto& motion = controller.motion_state[index];
  365. emulated_motion.ResetRotations();
  366. emulated_motion.ResetQuaternion();
  367. motion.accel = emulated_motion.GetAcceleration();
  368. motion.gyro = emulated_motion.GetGyroscope();
  369. motion.rotation = emulated_motion.GetRotations();
  370. motion.euler = emulated_motion.GetEulerAngles();
  371. motion.orientation = emulated_motion.GetOrientation();
  372. motion.is_at_rest = !emulated_motion.IsMoving(motion_sensitivity);
  373. }
  374. for (std::size_t index = 0; index < camera_devices.size(); ++index) {
  375. if (!camera_devices[index]) {
  376. continue;
  377. }
  378. camera_devices[index]->SetCallback({
  379. .on_change =
  380. [this](const Common::Input::CallbackStatus& callback) { SetCamera(callback); },
  381. });
  382. camera_devices[index]->ForceUpdate();
  383. }
  384. for (std::size_t index = 0; index < ring_analog_devices.size(); ++index) {
  385. if (!ring_analog_devices[index]) {
  386. continue;
  387. }
  388. ring_analog_devices[index]->SetCallback({
  389. .on_change =
  390. [this](const Common::Input::CallbackStatus& callback) { SetRingAnalog(callback); },
  391. });
  392. ring_analog_devices[index]->ForceUpdate();
  393. }
  394. for (std::size_t index = 0; index < nfc_devices.size(); ++index) {
  395. if (!nfc_devices[index]) {
  396. continue;
  397. }
  398. nfc_devices[index]->SetCallback({
  399. .on_change =
  400. [this](const Common::Input::CallbackStatus& callback) { SetNfc(callback); },
  401. });
  402. nfc_devices[index]->ForceUpdate();
  403. }
  404. // Register TAS devices. No need to force update
  405. for (std::size_t index = 0; index < tas_button_devices.size(); ++index) {
  406. if (!tas_button_devices[index]) {
  407. continue;
  408. }
  409. tas_button_devices[index]->SetCallback({
  410. .on_change =
  411. [this, index](const Common::Input::CallbackStatus& callback) {
  412. SetButton(callback, index, TAS_UUID);
  413. },
  414. });
  415. }
  416. for (std::size_t index = 0; index < tas_stick_devices.size(); ++index) {
  417. if (!tas_stick_devices[index]) {
  418. continue;
  419. }
  420. tas_stick_devices[index]->SetCallback({
  421. .on_change =
  422. [this, index](const Common::Input::CallbackStatus& callback) {
  423. SetStick(callback, index, TAS_UUID);
  424. },
  425. });
  426. }
  427. // Register virtual devices. No need to force update
  428. for (std::size_t index = 0; index < virtual_button_devices.size(); ++index) {
  429. if (!virtual_button_devices[index]) {
  430. continue;
  431. }
  432. virtual_button_devices[index]->SetCallback({
  433. .on_change =
  434. [this, index](const Common::Input::CallbackStatus& callback) {
  435. SetButton(callback, index, VIRTUAL_UUID);
  436. },
  437. });
  438. }
  439. for (std::size_t index = 0; index < virtual_stick_devices.size(); ++index) {
  440. if (!virtual_stick_devices[index]) {
  441. continue;
  442. }
  443. virtual_stick_devices[index]->SetCallback({
  444. .on_change =
  445. [this, index](const Common::Input::CallbackStatus& callback) {
  446. SetStick(callback, index, VIRTUAL_UUID);
  447. },
  448. });
  449. }
  450. for (std::size_t index = 0; index < virtual_motion_devices.size(); ++index) {
  451. if (!virtual_motion_devices[index]) {
  452. continue;
  453. }
  454. virtual_motion_devices[index]->SetCallback({
  455. .on_change =
  456. [this, index](const Common::Input::CallbackStatus& callback) {
  457. SetMotion(callback, index);
  458. },
  459. });
  460. }
  461. turbo_button_state = 0;
  462. is_initialized = true;
  463. }
  464. void EmulatedController::UnloadInput() {
  465. is_initialized = false;
  466. for (auto& button : button_devices) {
  467. button.reset();
  468. }
  469. for (auto& stick : stick_devices) {
  470. stick.reset();
  471. }
  472. for (auto& motion : motion_devices) {
  473. motion.reset();
  474. }
  475. for (auto& trigger : trigger_devices) {
  476. trigger.reset();
  477. }
  478. for (auto& battery : battery_devices) {
  479. battery.reset();
  480. }
  481. for (auto& color : color_devices) {
  482. color.reset();
  483. }
  484. for (auto& output : output_devices) {
  485. output.reset();
  486. }
  487. for (auto& button : tas_button_devices) {
  488. button.reset();
  489. }
  490. for (auto& stick : tas_stick_devices) {
  491. stick.reset();
  492. }
  493. for (auto& button : virtual_button_devices) {
  494. button.reset();
  495. }
  496. for (auto& stick : virtual_stick_devices) {
  497. stick.reset();
  498. }
  499. for (auto& motion : virtual_motion_devices) {
  500. motion.reset();
  501. }
  502. for (auto& camera : camera_devices) {
  503. camera.reset();
  504. }
  505. for (auto& ring : ring_analog_devices) {
  506. ring.reset();
  507. }
  508. for (auto& nfc : nfc_devices) {
  509. nfc.reset();
  510. }
  511. }
  512. void EmulatedController::EnableConfiguration() {
  513. std::scoped_lock lock{connect_mutex, npad_mutex};
  514. is_configuring = true;
  515. tmp_is_connected = is_connected;
  516. tmp_npad_type = npad_type;
  517. }
  518. void EmulatedController::DisableConfiguration() {
  519. is_configuring = false;
  520. // Get Joycon colors before turning on the controller
  521. for (const auto& color_device : color_devices) {
  522. color_device->ForceUpdate();
  523. }
  524. // Apply temporary npad type to the real controller
  525. if (tmp_npad_type != npad_type) {
  526. if (is_connected) {
  527. Disconnect();
  528. }
  529. SetNpadStyleIndex(tmp_npad_type);
  530. original_npad_type = tmp_npad_type;
  531. }
  532. // Apply temporary connected status to the real controller
  533. if (tmp_is_connected != is_connected) {
  534. if (tmp_is_connected) {
  535. Connect();
  536. return;
  537. }
  538. Disconnect();
  539. }
  540. }
  541. void EmulatedController::EnableSystemButtons() {
  542. std::scoped_lock lock{mutex};
  543. system_buttons_enabled = true;
  544. }
  545. void EmulatedController::DisableSystemButtons() {
  546. std::scoped_lock lock{mutex};
  547. system_buttons_enabled = false;
  548. controller.home_button_state.raw = 0;
  549. controller.capture_button_state.raw = 0;
  550. }
  551. void EmulatedController::ResetSystemButtons() {
  552. std::scoped_lock lock{mutex};
  553. controller.home_button_state.home.Assign(false);
  554. controller.capture_button_state.capture.Assign(false);
  555. }
  556. bool EmulatedController::IsConfiguring() const {
  557. return is_configuring;
  558. }
  559. void EmulatedController::SaveCurrentConfig() {
  560. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  561. auto& player = Settings::values.players.GetValue()[player_index];
  562. player.connected = is_connected;
  563. player.controller_type = MapNPadToSettingsType(npad_type);
  564. for (std::size_t index = 0; index < player.buttons.size(); ++index) {
  565. player.buttons[index] = button_params[index].Serialize();
  566. }
  567. for (std::size_t index = 0; index < player.analogs.size(); ++index) {
  568. player.analogs[index] = stick_params[index].Serialize();
  569. }
  570. for (std::size_t index = 0; index < player.motions.size(); ++index) {
  571. player.motions[index] = motion_params[index].Serialize();
  572. }
  573. if (npad_id_type == NpadIdType::Player1) {
  574. Settings::values.ringcon_analogs = ring_params[0].Serialize();
  575. }
  576. }
  577. void EmulatedController::RestoreConfig() {
  578. if (!is_configuring) {
  579. return;
  580. }
  581. ReloadFromSettings();
  582. }
  583. std::vector<Common::ParamPackage> EmulatedController::GetMappedDevices() const {
  584. std::vector<Common::ParamPackage> devices;
  585. for (const auto& param : button_params) {
  586. if (!param.Has("engine")) {
  587. continue;
  588. }
  589. const auto devices_it = std::find_if(
  590. devices.begin(), devices.end(), [&param](const Common::ParamPackage& param_) {
  591. return param.Get("engine", "") == param_.Get("engine", "") &&
  592. param.Get("guid", "") == param_.Get("guid", "") &&
  593. param.Get("port", 0) == param_.Get("port", 0) &&
  594. param.Get("pad", 0) == param_.Get("pad", 0);
  595. });
  596. if (devices_it != devices.end()) {
  597. continue;
  598. }
  599. auto& device = devices.emplace_back();
  600. device.Set("engine", param.Get("engine", ""));
  601. device.Set("guid", param.Get("guid", ""));
  602. device.Set("port", param.Get("port", 0));
  603. device.Set("pad", param.Get("pad", 0));
  604. }
  605. for (const auto& param : stick_params) {
  606. if (!param.Has("engine")) {
  607. continue;
  608. }
  609. if (param.Get("engine", "") == "analog_from_button") {
  610. continue;
  611. }
  612. const auto devices_it = std::find_if(
  613. devices.begin(), devices.end(), [&param](const Common::ParamPackage& param_) {
  614. return param.Get("engine", "") == param_.Get("engine", "") &&
  615. param.Get("guid", "") == param_.Get("guid", "") &&
  616. param.Get("port", 0) == param_.Get("port", 0) &&
  617. param.Get("pad", 0) == param_.Get("pad", 0);
  618. });
  619. if (devices_it != devices.end()) {
  620. continue;
  621. }
  622. auto& device = devices.emplace_back();
  623. device.Set("engine", param.Get("engine", ""));
  624. device.Set("guid", param.Get("guid", ""));
  625. device.Set("port", param.Get("port", 0));
  626. device.Set("pad", param.Get("pad", 0));
  627. }
  628. return devices;
  629. }
  630. Common::ParamPackage EmulatedController::GetButtonParam(std::size_t index) const {
  631. if (index >= button_params.size()) {
  632. return {};
  633. }
  634. return button_params[index];
  635. }
  636. Common::ParamPackage EmulatedController::GetStickParam(std::size_t index) const {
  637. if (index >= stick_params.size()) {
  638. return {};
  639. }
  640. return stick_params[index];
  641. }
  642. Common::ParamPackage EmulatedController::GetMotionParam(std::size_t index) const {
  643. if (index >= motion_params.size()) {
  644. return {};
  645. }
  646. return motion_params[index];
  647. }
  648. void EmulatedController::SetButtonParam(std::size_t index, Common::ParamPackage param) {
  649. if (index >= button_params.size()) {
  650. return;
  651. }
  652. button_params[index] = std::move(param);
  653. ReloadInput();
  654. }
  655. void EmulatedController::SetStickParam(std::size_t index, Common::ParamPackage param) {
  656. if (index >= stick_params.size()) {
  657. return;
  658. }
  659. stick_params[index] = std::move(param);
  660. ReloadInput();
  661. }
  662. void EmulatedController::SetMotionParam(std::size_t index, Common::ParamPackage param) {
  663. if (index >= motion_params.size()) {
  664. return;
  665. }
  666. motion_params[index] = std::move(param);
  667. ReloadInput();
  668. }
  669. void EmulatedController::StartMotionCalibration() {
  670. for (ControllerMotionInfo& motion : controller.motion_values) {
  671. motion.emulated.Calibrate();
  672. }
  673. }
  674. void EmulatedController::SetButton(const Common::Input::CallbackStatus& callback, std::size_t index,
  675. Common::UUID uuid) {
  676. if (index >= controller.button_values.size()) {
  677. return;
  678. }
  679. std::unique_lock lock{mutex};
  680. bool value_changed = false;
  681. const auto new_status = TransformToButton(callback);
  682. auto& current_status = controller.button_values[index];
  683. // Only read button values that have the same uuid or are pressed once
  684. if (current_status.uuid != uuid) {
  685. if (!new_status.value) {
  686. return;
  687. }
  688. }
  689. current_status.toggle = new_status.toggle;
  690. current_status.turbo = new_status.turbo;
  691. current_status.uuid = uuid;
  692. // Update button status with current
  693. if (!current_status.toggle) {
  694. current_status.locked = false;
  695. if (current_status.value != new_status.value) {
  696. current_status.value = new_status.value;
  697. value_changed = true;
  698. }
  699. } else {
  700. // Toggle button and lock status
  701. if (new_status.value && !current_status.locked) {
  702. current_status.locked = true;
  703. current_status.value = !current_status.value;
  704. value_changed = true;
  705. }
  706. // Unlock button ready for next press
  707. if (!new_status.value && current_status.locked) {
  708. current_status.locked = false;
  709. }
  710. }
  711. if (!value_changed) {
  712. return;
  713. }
  714. if (is_configuring) {
  715. controller.npad_button_state.raw = NpadButton::None;
  716. controller.debug_pad_button_state.raw = 0;
  717. controller.home_button_state.raw = 0;
  718. controller.capture_button_state.raw = 0;
  719. lock.unlock();
  720. TriggerOnChange(ControllerTriggerType::Button, false);
  721. return;
  722. }
  723. // GC controllers have triggers not buttons
  724. if (npad_type == NpadStyleIndex::GameCube) {
  725. if (index == Settings::NativeButton::ZR) {
  726. return;
  727. }
  728. if (index == Settings::NativeButton::ZL) {
  729. return;
  730. }
  731. }
  732. switch (index) {
  733. case Settings::NativeButton::A:
  734. controller.npad_button_state.a.Assign(current_status.value);
  735. controller.debug_pad_button_state.a.Assign(current_status.value);
  736. break;
  737. case Settings::NativeButton::B:
  738. controller.npad_button_state.b.Assign(current_status.value);
  739. controller.debug_pad_button_state.b.Assign(current_status.value);
  740. break;
  741. case Settings::NativeButton::X:
  742. controller.npad_button_state.x.Assign(current_status.value);
  743. controller.debug_pad_button_state.x.Assign(current_status.value);
  744. break;
  745. case Settings::NativeButton::Y:
  746. controller.npad_button_state.y.Assign(current_status.value);
  747. controller.debug_pad_button_state.y.Assign(current_status.value);
  748. break;
  749. case Settings::NativeButton::LStick:
  750. controller.npad_button_state.stick_l.Assign(current_status.value);
  751. break;
  752. case Settings::NativeButton::RStick:
  753. controller.npad_button_state.stick_r.Assign(current_status.value);
  754. break;
  755. case Settings::NativeButton::L:
  756. controller.npad_button_state.l.Assign(current_status.value);
  757. controller.debug_pad_button_state.l.Assign(current_status.value);
  758. break;
  759. case Settings::NativeButton::R:
  760. controller.npad_button_state.r.Assign(current_status.value);
  761. controller.debug_pad_button_state.r.Assign(current_status.value);
  762. break;
  763. case Settings::NativeButton::ZL:
  764. controller.npad_button_state.zl.Assign(current_status.value);
  765. controller.debug_pad_button_state.zl.Assign(current_status.value);
  766. break;
  767. case Settings::NativeButton::ZR:
  768. controller.npad_button_state.zr.Assign(current_status.value);
  769. controller.debug_pad_button_state.zr.Assign(current_status.value);
  770. break;
  771. case Settings::NativeButton::Plus:
  772. controller.npad_button_state.plus.Assign(current_status.value);
  773. controller.debug_pad_button_state.plus.Assign(current_status.value);
  774. break;
  775. case Settings::NativeButton::Minus:
  776. controller.npad_button_state.minus.Assign(current_status.value);
  777. controller.debug_pad_button_state.minus.Assign(current_status.value);
  778. break;
  779. case Settings::NativeButton::DLeft:
  780. controller.npad_button_state.left.Assign(current_status.value);
  781. controller.debug_pad_button_state.d_left.Assign(current_status.value);
  782. break;
  783. case Settings::NativeButton::DUp:
  784. controller.npad_button_state.up.Assign(current_status.value);
  785. controller.debug_pad_button_state.d_up.Assign(current_status.value);
  786. break;
  787. case Settings::NativeButton::DRight:
  788. controller.npad_button_state.right.Assign(current_status.value);
  789. controller.debug_pad_button_state.d_right.Assign(current_status.value);
  790. break;
  791. case Settings::NativeButton::DDown:
  792. controller.npad_button_state.down.Assign(current_status.value);
  793. controller.debug_pad_button_state.d_down.Assign(current_status.value);
  794. break;
  795. case Settings::NativeButton::SLLeft:
  796. controller.npad_button_state.left_sl.Assign(current_status.value);
  797. break;
  798. case Settings::NativeButton::SLRight:
  799. controller.npad_button_state.right_sl.Assign(current_status.value);
  800. break;
  801. case Settings::NativeButton::SRLeft:
  802. controller.npad_button_state.left_sr.Assign(current_status.value);
  803. break;
  804. case Settings::NativeButton::SRRight:
  805. controller.npad_button_state.right_sr.Assign(current_status.value);
  806. break;
  807. case Settings::NativeButton::Home:
  808. if (!system_buttons_enabled) {
  809. break;
  810. }
  811. controller.home_button_state.home.Assign(current_status.value);
  812. break;
  813. case Settings::NativeButton::Screenshot:
  814. if (!system_buttons_enabled) {
  815. break;
  816. }
  817. controller.capture_button_state.capture.Assign(current_status.value);
  818. break;
  819. }
  820. lock.unlock();
  821. if (!is_connected) {
  822. if (npad_id_type == NpadIdType::Player1 && npad_type != NpadStyleIndex::Handheld) {
  823. Connect();
  824. }
  825. if (npad_id_type == NpadIdType::Handheld && npad_type == NpadStyleIndex::Handheld) {
  826. Connect();
  827. }
  828. }
  829. TriggerOnChange(ControllerTriggerType::Button, true);
  830. }
  831. void EmulatedController::SetStick(const Common::Input::CallbackStatus& callback, std::size_t index,
  832. Common::UUID uuid) {
  833. if (index >= controller.stick_values.size()) {
  834. return;
  835. }
  836. auto trigger_guard =
  837. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Stick, !is_configuring); });
  838. std::scoped_lock lock{mutex};
  839. const auto stick_value = TransformToStick(callback);
  840. // Only read stick values that have the same uuid or are over the threshold to avoid flapping
  841. if (controller.stick_values[index].uuid != uuid) {
  842. const bool is_tas = uuid == TAS_UUID;
  843. if (is_tas && stick_value.x.value == 0 && stick_value.y.value == 0) {
  844. trigger_guard.Cancel();
  845. return;
  846. }
  847. if (!is_tas && !stick_value.down && !stick_value.up && !stick_value.left &&
  848. !stick_value.right) {
  849. trigger_guard.Cancel();
  850. return;
  851. }
  852. }
  853. controller.stick_values[index] = stick_value;
  854. controller.stick_values[index].uuid = uuid;
  855. if (is_configuring) {
  856. controller.analog_stick_state.left = {};
  857. controller.analog_stick_state.right = {};
  858. return;
  859. }
  860. const AnalogStickState stick{
  861. .x = static_cast<s32>(controller.stick_values[index].x.value * HID_JOYSTICK_MAX),
  862. .y = static_cast<s32>(controller.stick_values[index].y.value * HID_JOYSTICK_MAX),
  863. };
  864. switch (index) {
  865. case Settings::NativeAnalog::LStick:
  866. controller.analog_stick_state.left = stick;
  867. controller.npad_button_state.stick_l_left.Assign(controller.stick_values[index].left);
  868. controller.npad_button_state.stick_l_up.Assign(controller.stick_values[index].up);
  869. controller.npad_button_state.stick_l_right.Assign(controller.stick_values[index].right);
  870. controller.npad_button_state.stick_l_down.Assign(controller.stick_values[index].down);
  871. break;
  872. case Settings::NativeAnalog::RStick:
  873. controller.analog_stick_state.right = stick;
  874. controller.npad_button_state.stick_r_left.Assign(controller.stick_values[index].left);
  875. controller.npad_button_state.stick_r_up.Assign(controller.stick_values[index].up);
  876. controller.npad_button_state.stick_r_right.Assign(controller.stick_values[index].right);
  877. controller.npad_button_state.stick_r_down.Assign(controller.stick_values[index].down);
  878. break;
  879. }
  880. }
  881. void EmulatedController::SetTrigger(const Common::Input::CallbackStatus& callback,
  882. std::size_t index, Common::UUID uuid) {
  883. if (index >= controller.trigger_values.size()) {
  884. return;
  885. }
  886. auto trigger_guard =
  887. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Trigger, !is_configuring); });
  888. std::scoped_lock lock{mutex};
  889. const auto trigger_value = TransformToTrigger(callback);
  890. // Only read trigger values that have the same uuid or are pressed once
  891. if (controller.trigger_values[index].uuid != uuid) {
  892. if (!trigger_value.pressed.value) {
  893. return;
  894. }
  895. }
  896. controller.trigger_values[index] = trigger_value;
  897. controller.trigger_values[index].uuid = uuid;
  898. if (is_configuring) {
  899. controller.gc_trigger_state.left = 0;
  900. controller.gc_trigger_state.right = 0;
  901. return;
  902. }
  903. // Only GC controllers have analog triggers
  904. if (npad_type != NpadStyleIndex::GameCube) {
  905. trigger_guard.Cancel();
  906. return;
  907. }
  908. const auto& trigger = controller.trigger_values[index];
  909. switch (index) {
  910. case Settings::NativeTrigger::LTrigger:
  911. controller.gc_trigger_state.left = static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
  912. controller.npad_button_state.zl.Assign(trigger.pressed.value);
  913. break;
  914. case Settings::NativeTrigger::RTrigger:
  915. controller.gc_trigger_state.right =
  916. static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
  917. controller.npad_button_state.zr.Assign(trigger.pressed.value);
  918. break;
  919. }
  920. }
  921. void EmulatedController::SetMotion(const Common::Input::CallbackStatus& callback,
  922. std::size_t index) {
  923. if (index >= controller.motion_values.size()) {
  924. return;
  925. }
  926. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::Motion, !is_configuring); });
  927. std::scoped_lock lock{mutex};
  928. auto& raw_status = controller.motion_values[index].raw_status;
  929. auto& emulated = controller.motion_values[index].emulated;
  930. raw_status = TransformToMotion(callback);
  931. emulated.SetAcceleration(Common::Vec3f{
  932. raw_status.accel.x.value,
  933. raw_status.accel.y.value,
  934. raw_status.accel.z.value,
  935. });
  936. emulated.SetGyroscope(Common::Vec3f{
  937. raw_status.gyro.x.value,
  938. raw_status.gyro.y.value,
  939. raw_status.gyro.z.value,
  940. });
  941. emulated.SetUserGyroThreshold(raw_status.gyro.x.properties.threshold);
  942. emulated.UpdateRotation(raw_status.delta_timestamp);
  943. emulated.UpdateOrientation(raw_status.delta_timestamp);
  944. auto& motion = controller.motion_state[index];
  945. motion.accel = emulated.GetAcceleration();
  946. motion.gyro = emulated.GetGyroscope();
  947. motion.rotation = emulated.GetRotations();
  948. motion.euler = emulated.GetEulerAngles();
  949. motion.orientation = emulated.GetOrientation();
  950. motion.is_at_rest = !emulated.IsMoving(motion_sensitivity);
  951. }
  952. void EmulatedController::SetColors(const Common::Input::CallbackStatus& callback,
  953. std::size_t index) {
  954. if (index >= controller.color_values.size()) {
  955. return;
  956. }
  957. auto trigger_guard =
  958. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Color, !is_configuring); });
  959. std::scoped_lock lock{mutex};
  960. controller.color_values[index] = TransformToColor(callback);
  961. if (is_configuring) {
  962. return;
  963. }
  964. if (controller.color_values[index].body == 0) {
  965. trigger_guard.Cancel();
  966. return;
  967. }
  968. controller.colors_state.fullkey = {
  969. .body = GetNpadColor(controller.color_values[index].body),
  970. .button = GetNpadColor(controller.color_values[index].buttons),
  971. };
  972. if (npad_type == NpadStyleIndex::Fullkey) {
  973. controller.colors_state.left = {
  974. .body = GetNpadColor(controller.color_values[index].left_grip),
  975. .button = GetNpadColor(controller.color_values[index].buttons),
  976. };
  977. controller.colors_state.right = {
  978. .body = GetNpadColor(controller.color_values[index].right_grip),
  979. .button = GetNpadColor(controller.color_values[index].buttons),
  980. };
  981. } else {
  982. switch (index) {
  983. case LeftIndex:
  984. controller.colors_state.left = {
  985. .body = GetNpadColor(controller.color_values[index].body),
  986. .button = GetNpadColor(controller.color_values[index].buttons),
  987. };
  988. break;
  989. case RightIndex:
  990. controller.colors_state.right = {
  991. .body = GetNpadColor(controller.color_values[index].body),
  992. .button = GetNpadColor(controller.color_values[index].buttons),
  993. };
  994. break;
  995. }
  996. }
  997. }
  998. void EmulatedController::SetBattery(const Common::Input::CallbackStatus& callback,
  999. std::size_t index) {
  1000. if (index >= controller.battery_values.size()) {
  1001. return;
  1002. }
  1003. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::Battery, !is_configuring); });
  1004. std::scoped_lock lock{mutex};
  1005. controller.battery_values[index] = TransformToBattery(callback);
  1006. if (is_configuring) {
  1007. return;
  1008. }
  1009. bool is_charging = false;
  1010. bool is_powered = false;
  1011. NpadBatteryLevel battery_level = NpadBatteryLevel::Empty;
  1012. switch (controller.battery_values[index]) {
  1013. case Common::Input::BatteryLevel::Charging:
  1014. is_charging = true;
  1015. is_powered = true;
  1016. battery_level = NpadBatteryLevel::Full;
  1017. break;
  1018. case Common::Input::BatteryLevel::Medium:
  1019. battery_level = NpadBatteryLevel::High;
  1020. break;
  1021. case Common::Input::BatteryLevel::Low:
  1022. battery_level = NpadBatteryLevel::Low;
  1023. break;
  1024. case Common::Input::BatteryLevel::Critical:
  1025. battery_level = NpadBatteryLevel::Critical;
  1026. break;
  1027. case Common::Input::BatteryLevel::Empty:
  1028. battery_level = NpadBatteryLevel::Empty;
  1029. break;
  1030. case Common::Input::BatteryLevel::None:
  1031. case Common::Input::BatteryLevel::Full:
  1032. default:
  1033. is_powered = true;
  1034. battery_level = NpadBatteryLevel::Full;
  1035. break;
  1036. }
  1037. switch (index) {
  1038. case LeftIndex:
  1039. controller.battery_state.left = {
  1040. .is_powered = is_powered,
  1041. .is_charging = is_charging,
  1042. .battery_level = battery_level,
  1043. };
  1044. break;
  1045. case RightIndex:
  1046. controller.battery_state.right = {
  1047. .is_powered = is_powered,
  1048. .is_charging = is_charging,
  1049. .battery_level = battery_level,
  1050. };
  1051. break;
  1052. case DualIndex:
  1053. controller.battery_state.dual = {
  1054. .is_powered = is_powered,
  1055. .is_charging = is_charging,
  1056. .battery_level = battery_level,
  1057. };
  1058. break;
  1059. }
  1060. }
  1061. void EmulatedController::SetCamera(const Common::Input::CallbackStatus& callback) {
  1062. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::IrSensor, !is_configuring); });
  1063. std::scoped_lock lock{mutex};
  1064. controller.camera_values = TransformToCamera(callback);
  1065. if (is_configuring) {
  1066. return;
  1067. }
  1068. controller.camera_state.sample++;
  1069. controller.camera_state.format =
  1070. static_cast<Core::IrSensor::ImageTransferProcessorFormat>(controller.camera_values.format);
  1071. controller.camera_state.data = controller.camera_values.data;
  1072. }
  1073. void EmulatedController::SetRingAnalog(const Common::Input::CallbackStatus& callback) {
  1074. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::RingController, !is_configuring); });
  1075. std::scoped_lock lock{mutex};
  1076. const auto force_value = TransformToStick(callback);
  1077. controller.ring_analog_value = force_value.x;
  1078. if (is_configuring) {
  1079. return;
  1080. }
  1081. controller.ring_analog_state.force = force_value.x.value;
  1082. }
  1083. void EmulatedController::SetNfc(const Common::Input::CallbackStatus& callback) {
  1084. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::Nfc, !is_configuring); });
  1085. std::scoped_lock lock{mutex};
  1086. controller.nfc_values = TransformToNfc(callback);
  1087. if (is_configuring) {
  1088. return;
  1089. }
  1090. controller.nfc_state = controller.nfc_values;
  1091. }
  1092. bool EmulatedController::SetVibration(bool should_vibrate) {
  1093. VibrationValue vibration_value = DEFAULT_VIBRATION_VALUE;
  1094. if (should_vibrate) {
  1095. vibration_value.high_amplitude = 1.0f;
  1096. vibration_value.low_amplitude = 1.0f;
  1097. }
  1098. return SetVibration(DeviceIndex::Left, vibration_value);
  1099. }
  1100. bool EmulatedController::SetVibration(u32 slot, Core::HID::VibrationGcErmCommand erm_command) {
  1101. VibrationValue vibration_value = DEFAULT_VIBRATION_VALUE;
  1102. if (erm_command == Core::HID::VibrationGcErmCommand::Start) {
  1103. vibration_value.high_amplitude = 1.0f;
  1104. vibration_value.low_amplitude = 1.0f;
  1105. }
  1106. return SetVibration(DeviceIndex::Left, vibration_value);
  1107. }
  1108. bool EmulatedController::SetVibration(DeviceIndex device_index, const VibrationValue& vibration) {
  1109. if (!is_initialized) {
  1110. return false;
  1111. }
  1112. if (device_index >= DeviceIndex::MaxDeviceIndex) {
  1113. return false;
  1114. }
  1115. const std::size_t index = static_cast<std::size_t>(device_index);
  1116. if (!output_devices[index]) {
  1117. return false;
  1118. }
  1119. last_vibration_value = vibration;
  1120. if (!Settings::values.vibration_enabled) {
  1121. return false;
  1122. }
  1123. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  1124. const auto& player = Settings::values.players.GetValue()[player_index];
  1125. const f32 strength = static_cast<f32>(player.vibration_strength) / 100.0f;
  1126. if (!player.vibration_enabled) {
  1127. return false;
  1128. }
  1129. // Exponential amplification is too strong at low amplitudes. Switch to a linear
  1130. // amplification if strength is set below 0.7f
  1131. const Common::Input::VibrationAmplificationType type =
  1132. strength > 0.7f ? Common::Input::VibrationAmplificationType::Exponential
  1133. : Common::Input::VibrationAmplificationType::Linear;
  1134. const Common::Input::VibrationStatus status = {
  1135. .low_amplitude = std::min(vibration.low_amplitude * strength, 1.0f),
  1136. .low_frequency = vibration.low_frequency,
  1137. .high_amplitude = std::min(vibration.high_amplitude * strength, 1.0f),
  1138. .high_frequency = vibration.high_frequency,
  1139. .type = type,
  1140. };
  1141. return output_devices[index]->SetVibration(status) == Common::Input::DriverResult::Success;
  1142. }
  1143. VibrationValue EmulatedController::GetActualVibrationValue(DeviceIndex device_index) const {
  1144. return last_vibration_value;
  1145. }
  1146. bool EmulatedController::IsVibrationEnabled(std::size_t device_index) {
  1147. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  1148. const auto& player = Settings::values.players.GetValue()[player_index];
  1149. if (!is_initialized) {
  1150. return false;
  1151. }
  1152. if (!player.vibration_enabled) {
  1153. return false;
  1154. }
  1155. if (device_index >= output_devices.size()) {
  1156. return false;
  1157. }
  1158. if (!output_devices[device_index]) {
  1159. return false;
  1160. }
  1161. return output_devices[device_index]->IsVibrationEnabled();
  1162. }
  1163. Common::Input::DriverResult EmulatedController::SetPollingMode(
  1164. EmulatedDeviceIndex device_index, Common::Input::PollingMode polling_mode) {
  1165. LOG_INFO(Service_HID, "Set polling mode {}, device_index={}", polling_mode, device_index);
  1166. if (!is_initialized) {
  1167. return Common::Input::DriverResult::InvalidHandle;
  1168. }
  1169. auto& left_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Left)];
  1170. auto& right_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1171. auto& nfc_output_device = output_devices[3];
  1172. if (device_index == EmulatedDeviceIndex::LeftIndex) {
  1173. controller.left_polling_mode = polling_mode;
  1174. return left_output_device->SetPollingMode(polling_mode);
  1175. }
  1176. if (device_index == EmulatedDeviceIndex::RightIndex) {
  1177. controller.right_polling_mode = polling_mode;
  1178. const auto virtual_nfc_result = nfc_output_device->SetPollingMode(polling_mode);
  1179. const auto mapped_nfc_result = right_output_device->SetPollingMode(polling_mode);
  1180. // Restore previous state
  1181. if (mapped_nfc_result != Common::Input::DriverResult::Success) {
  1182. right_output_device->SetPollingMode(Common::Input::PollingMode::Active);
  1183. }
  1184. if (virtual_nfc_result == Common::Input::DriverResult::Success) {
  1185. return virtual_nfc_result;
  1186. }
  1187. return mapped_nfc_result;
  1188. }
  1189. controller.left_polling_mode = polling_mode;
  1190. controller.right_polling_mode = polling_mode;
  1191. left_output_device->SetPollingMode(polling_mode);
  1192. right_output_device->SetPollingMode(polling_mode);
  1193. nfc_output_device->SetPollingMode(polling_mode);
  1194. return Common::Input::DriverResult::Success;
  1195. }
  1196. Common::Input::PollingMode EmulatedController::GetPollingMode(
  1197. EmulatedDeviceIndex device_index) const {
  1198. if (device_index == EmulatedDeviceIndex::LeftIndex) {
  1199. return controller.left_polling_mode;
  1200. }
  1201. return controller.right_polling_mode;
  1202. }
  1203. bool EmulatedController::SetCameraFormat(
  1204. Core::IrSensor::ImageTransferProcessorFormat camera_format) {
  1205. LOG_INFO(Service_HID, "Set camera format {}", camera_format);
  1206. if (!is_initialized) {
  1207. return false;
  1208. }
  1209. auto& right_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1210. auto& camera_output_device = output_devices[2];
  1211. if (right_output_device->SetCameraFormat(static_cast<Common::Input::CameraFormat>(
  1212. camera_format)) == Common::Input::DriverResult::Success) {
  1213. return true;
  1214. }
  1215. // Fallback to Qt camera if native device doesn't have support
  1216. return camera_output_device->SetCameraFormat(static_cast<Common::Input::CameraFormat>(
  1217. camera_format)) == Common::Input::DriverResult::Success;
  1218. }
  1219. Common::ParamPackage EmulatedController::GetRingParam() const {
  1220. return ring_params[0];
  1221. }
  1222. void EmulatedController::SetRingParam(Common::ParamPackage param) {
  1223. ring_params[0] = std::move(param);
  1224. ReloadInput();
  1225. }
  1226. bool EmulatedController::HasNfc() const {
  1227. if (!is_initialized) {
  1228. return false;
  1229. }
  1230. const auto& nfc_output_device = output_devices[3];
  1231. switch (npad_type) {
  1232. case NpadStyleIndex::JoyconRight:
  1233. case NpadStyleIndex::JoyconDual:
  1234. case NpadStyleIndex::Fullkey:
  1235. case NpadStyleIndex::Handheld:
  1236. break;
  1237. default:
  1238. return false;
  1239. }
  1240. const bool has_virtual_nfc =
  1241. npad_id_type == NpadIdType::Player1 || npad_id_type == NpadIdType::Handheld;
  1242. const bool is_virtual_nfc_supported =
  1243. nfc_output_device->SupportsNfc() != Common::Input::NfcState::NotSupported;
  1244. return is_connected && (has_virtual_nfc && is_virtual_nfc_supported);
  1245. }
  1246. bool EmulatedController::AddNfcHandle() {
  1247. nfc_handles++;
  1248. return SetPollingMode(EmulatedDeviceIndex::RightIndex, Common::Input::PollingMode::NFC) ==
  1249. Common::Input::DriverResult::Success;
  1250. }
  1251. bool EmulatedController::RemoveNfcHandle() {
  1252. nfc_handles--;
  1253. if (nfc_handles <= 0) {
  1254. return SetPollingMode(EmulatedDeviceIndex::RightIndex,
  1255. Common::Input::PollingMode::Active) ==
  1256. Common::Input::DriverResult::Success;
  1257. }
  1258. return true;
  1259. }
  1260. bool EmulatedController::StartNfcPolling() {
  1261. if (!is_initialized) {
  1262. return false;
  1263. }
  1264. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1265. auto& nfc_virtual_output_device = output_devices[3];
  1266. const auto device_result = nfc_output_device->StartNfcPolling();
  1267. const auto virtual_device_result = nfc_virtual_output_device->StartNfcPolling();
  1268. return device_result == Common::Input::NfcState::Success ||
  1269. virtual_device_result == Common::Input::NfcState::Success;
  1270. }
  1271. bool EmulatedController::StopNfcPolling() {
  1272. if (!is_initialized) {
  1273. return false;
  1274. }
  1275. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1276. auto& nfc_virtual_output_device = output_devices[3];
  1277. const auto device_result = nfc_output_device->StopNfcPolling();
  1278. const auto virtual_device_result = nfc_virtual_output_device->StopNfcPolling();
  1279. return device_result == Common::Input::NfcState::Success ||
  1280. virtual_device_result == Common::Input::NfcState::Success;
  1281. }
  1282. bool EmulatedController::ReadAmiiboData(std::vector<u8>& data) {
  1283. if (!is_initialized) {
  1284. return false;
  1285. }
  1286. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1287. auto& nfc_virtual_output_device = output_devices[3];
  1288. if (nfc_output_device->ReadAmiiboData(data) == Common::Input::NfcState::Success) {
  1289. return true;
  1290. }
  1291. return nfc_virtual_output_device->ReadAmiiboData(data) == Common::Input::NfcState::Success;
  1292. }
  1293. bool EmulatedController::ReadMifareData(const Common::Input::MifareRequest& request,
  1294. Common::Input::MifareRequest& out_data) {
  1295. if (!is_initialized) {
  1296. return false;
  1297. }
  1298. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1299. auto& nfc_virtual_output_device = output_devices[3];
  1300. if (nfc_output_device->ReadMifareData(request, out_data) == Common::Input::NfcState::Success) {
  1301. return true;
  1302. }
  1303. return nfc_virtual_output_device->ReadMifareData(request, out_data) ==
  1304. Common::Input::NfcState::Success;
  1305. }
  1306. bool EmulatedController::WriteMifareData(const Common::Input::MifareRequest& request) {
  1307. if (!is_initialized) {
  1308. return false;
  1309. }
  1310. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1311. auto& nfc_virtual_output_device = output_devices[3];
  1312. if (nfc_output_device->WriteMifareData(request) == Common::Input::NfcState::Success) {
  1313. return true;
  1314. }
  1315. return nfc_virtual_output_device->WriteMifareData(request) == Common::Input::NfcState::Success;
  1316. }
  1317. bool EmulatedController::WriteNfc(const std::vector<u8>& data) {
  1318. if (!is_initialized) {
  1319. return false;
  1320. }
  1321. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1322. auto& nfc_virtual_output_device = output_devices[3];
  1323. if (nfc_output_device->SupportsNfc() != Common::Input::NfcState::NotSupported) {
  1324. return nfc_output_device->WriteNfcData(data) == Common::Input::NfcState::Success;
  1325. }
  1326. return nfc_virtual_output_device->WriteNfcData(data) == Common::Input::NfcState::Success;
  1327. }
  1328. void EmulatedController::SetLedPattern() {
  1329. if (!is_initialized) {
  1330. return;
  1331. }
  1332. for (auto& device : output_devices) {
  1333. if (!device) {
  1334. continue;
  1335. }
  1336. const LedPattern pattern = GetLedPattern();
  1337. const Common::Input::LedStatus status = {
  1338. .led_1 = pattern.position1 != 0,
  1339. .led_2 = pattern.position2 != 0,
  1340. .led_3 = pattern.position3 != 0,
  1341. .led_4 = pattern.position4 != 0,
  1342. };
  1343. device->SetLED(status);
  1344. }
  1345. }
  1346. void EmulatedController::SetGyroscopeZeroDriftMode(GyroscopeZeroDriftMode mode) {
  1347. for (auto& motion : controller.motion_values) {
  1348. switch (mode) {
  1349. case GyroscopeZeroDriftMode::Loose:
  1350. motion_sensitivity = motion.emulated.IsAtRestLoose;
  1351. motion.emulated.SetGyroThreshold(motion.emulated.ThresholdLoose);
  1352. break;
  1353. case GyroscopeZeroDriftMode::Tight:
  1354. motion_sensitivity = motion.emulated.IsAtRestTight;
  1355. motion.emulated.SetGyroThreshold(motion.emulated.ThresholdTight);
  1356. break;
  1357. case GyroscopeZeroDriftMode::Standard:
  1358. default:
  1359. motion_sensitivity = motion.emulated.IsAtRestStandard;
  1360. motion.emulated.SetGyroThreshold(motion.emulated.ThresholdStandard);
  1361. break;
  1362. }
  1363. }
  1364. }
  1365. void EmulatedController::SetSupportedNpadStyleTag(NpadStyleTag supported_styles) {
  1366. supported_style_tag = supported_styles;
  1367. if (!is_connected) {
  1368. return;
  1369. }
  1370. // Attempt to reconnect with the original type
  1371. if (npad_type != original_npad_type) {
  1372. Disconnect();
  1373. const auto current_npad_type = npad_type;
  1374. SetNpadStyleIndex(original_npad_type);
  1375. if (IsControllerSupported()) {
  1376. Connect();
  1377. return;
  1378. }
  1379. SetNpadStyleIndex(current_npad_type);
  1380. Connect();
  1381. }
  1382. if (IsControllerSupported()) {
  1383. return;
  1384. }
  1385. Disconnect();
  1386. // Fallback Fullkey controllers to Pro controllers
  1387. if (IsControllerFullkey() && supported_style_tag.fullkey) {
  1388. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
  1389. SetNpadStyleIndex(NpadStyleIndex::Fullkey);
  1390. Connect();
  1391. return;
  1392. }
  1393. // Fallback Dual joycon controllers to Pro controllers
  1394. if (npad_type == NpadStyleIndex::JoyconDual && supported_style_tag.fullkey) {
  1395. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
  1396. SetNpadStyleIndex(NpadStyleIndex::Fullkey);
  1397. Connect();
  1398. return;
  1399. }
  1400. // Fallback Pro controllers to Dual joycon
  1401. if (npad_type == NpadStyleIndex::Fullkey && supported_style_tag.joycon_dual) {
  1402. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Dual Joycons", npad_type);
  1403. SetNpadStyleIndex(NpadStyleIndex::JoyconDual);
  1404. Connect();
  1405. return;
  1406. }
  1407. LOG_ERROR(Service_HID, "Controller type {} is not supported. Disconnecting controller",
  1408. npad_type);
  1409. }
  1410. bool EmulatedController::IsControllerFullkey(bool use_temporary_value) const {
  1411. std::scoped_lock lock{mutex};
  1412. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1413. switch (type) {
  1414. case NpadStyleIndex::Fullkey:
  1415. case NpadStyleIndex::GameCube:
  1416. case NpadStyleIndex::NES:
  1417. case NpadStyleIndex::SNES:
  1418. case NpadStyleIndex::N64:
  1419. case NpadStyleIndex::SegaGenesis:
  1420. return true;
  1421. default:
  1422. return false;
  1423. }
  1424. }
  1425. bool EmulatedController::IsControllerSupported(bool use_temporary_value) const {
  1426. std::scoped_lock lock{mutex};
  1427. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1428. switch (type) {
  1429. case NpadStyleIndex::Fullkey:
  1430. return supported_style_tag.fullkey.As<bool>();
  1431. case NpadStyleIndex::Handheld:
  1432. return supported_style_tag.handheld.As<bool>();
  1433. case NpadStyleIndex::JoyconDual:
  1434. return supported_style_tag.joycon_dual.As<bool>();
  1435. case NpadStyleIndex::JoyconLeft:
  1436. return supported_style_tag.joycon_left.As<bool>();
  1437. case NpadStyleIndex::JoyconRight:
  1438. return supported_style_tag.joycon_right.As<bool>();
  1439. case NpadStyleIndex::GameCube:
  1440. return supported_style_tag.gamecube.As<bool>();
  1441. case NpadStyleIndex::Pokeball:
  1442. return supported_style_tag.palma.As<bool>();
  1443. case NpadStyleIndex::NES:
  1444. return supported_style_tag.lark.As<bool>();
  1445. case NpadStyleIndex::SNES:
  1446. return supported_style_tag.lucia.As<bool>();
  1447. case NpadStyleIndex::N64:
  1448. return supported_style_tag.lagoon.As<bool>();
  1449. case NpadStyleIndex::SegaGenesis:
  1450. return supported_style_tag.lager.As<bool>();
  1451. default:
  1452. return false;
  1453. }
  1454. }
  1455. void EmulatedController::Connect(bool use_temporary_value) {
  1456. if (!IsControllerSupported(use_temporary_value)) {
  1457. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1458. LOG_ERROR(Service_HID, "Controller type {} is not supported", type);
  1459. return;
  1460. }
  1461. auto trigger_guard =
  1462. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Connected, !is_configuring); });
  1463. std::scoped_lock lock{connect_mutex, mutex};
  1464. if (is_configuring) {
  1465. tmp_is_connected = true;
  1466. return;
  1467. }
  1468. if (is_connected) {
  1469. trigger_guard.Cancel();
  1470. return;
  1471. }
  1472. is_connected = true;
  1473. }
  1474. void EmulatedController::Disconnect() {
  1475. auto trigger_guard =
  1476. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Disconnected, !is_configuring); });
  1477. std::scoped_lock lock{connect_mutex, mutex};
  1478. if (is_configuring) {
  1479. tmp_is_connected = false;
  1480. return;
  1481. }
  1482. if (!is_connected) {
  1483. trigger_guard.Cancel();
  1484. return;
  1485. }
  1486. is_connected = false;
  1487. }
  1488. bool EmulatedController::IsConnected(bool get_temporary_value) const {
  1489. std::scoped_lock lock{connect_mutex};
  1490. if (get_temporary_value && is_configuring) {
  1491. return tmp_is_connected;
  1492. }
  1493. return is_connected;
  1494. }
  1495. NpadIdType EmulatedController::GetNpadIdType() const {
  1496. std::scoped_lock lock{mutex};
  1497. return npad_id_type;
  1498. }
  1499. NpadStyleIndex EmulatedController::GetNpadStyleIndex(bool get_temporary_value) const {
  1500. std::scoped_lock lock{npad_mutex};
  1501. if (get_temporary_value && is_configuring) {
  1502. return tmp_npad_type;
  1503. }
  1504. return npad_type;
  1505. }
  1506. void EmulatedController::SetNpadStyleIndex(NpadStyleIndex npad_type_) {
  1507. auto trigger_guard =
  1508. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Type, !is_configuring); });
  1509. std::scoped_lock lock{mutex, npad_mutex};
  1510. if (is_configuring) {
  1511. if (tmp_npad_type == npad_type_) {
  1512. trigger_guard.Cancel();
  1513. return;
  1514. }
  1515. tmp_npad_type = npad_type_;
  1516. return;
  1517. }
  1518. if (npad_type == npad_type_) {
  1519. trigger_guard.Cancel();
  1520. return;
  1521. }
  1522. if (is_connected) {
  1523. LOG_WARNING(Service_HID, "Controller {} type changed while it's connected",
  1524. Service::HID::NpadIdTypeToIndex(npad_id_type));
  1525. }
  1526. npad_type = npad_type_;
  1527. }
  1528. LedPattern EmulatedController::GetLedPattern() const {
  1529. switch (npad_id_type) {
  1530. case NpadIdType::Player1:
  1531. return LedPattern{1, 0, 0, 0};
  1532. case NpadIdType::Player2:
  1533. return LedPattern{1, 1, 0, 0};
  1534. case NpadIdType::Player3:
  1535. return LedPattern{1, 1, 1, 0};
  1536. case NpadIdType::Player4:
  1537. return LedPattern{1, 1, 1, 1};
  1538. case NpadIdType::Player5:
  1539. return LedPattern{1, 0, 0, 1};
  1540. case NpadIdType::Player6:
  1541. return LedPattern{1, 0, 1, 0};
  1542. case NpadIdType::Player7:
  1543. return LedPattern{1, 0, 1, 1};
  1544. case NpadIdType::Player8:
  1545. return LedPattern{0, 1, 1, 0};
  1546. default:
  1547. return LedPattern{0, 0, 0, 0};
  1548. }
  1549. }
  1550. ButtonValues EmulatedController::GetButtonsValues() const {
  1551. std::scoped_lock lock{mutex};
  1552. return controller.button_values;
  1553. }
  1554. SticksValues EmulatedController::GetSticksValues() const {
  1555. std::scoped_lock lock{mutex};
  1556. return controller.stick_values;
  1557. }
  1558. TriggerValues EmulatedController::GetTriggersValues() const {
  1559. std::scoped_lock lock{mutex};
  1560. return controller.trigger_values;
  1561. }
  1562. ControllerMotionValues EmulatedController::GetMotionValues() const {
  1563. std::scoped_lock lock{mutex};
  1564. return controller.motion_values;
  1565. }
  1566. ColorValues EmulatedController::GetColorsValues() const {
  1567. std::scoped_lock lock{mutex};
  1568. return controller.color_values;
  1569. }
  1570. BatteryValues EmulatedController::GetBatteryValues() const {
  1571. std::scoped_lock lock{mutex};
  1572. return controller.battery_values;
  1573. }
  1574. CameraValues EmulatedController::GetCameraValues() const {
  1575. std::scoped_lock lock{mutex};
  1576. return controller.camera_values;
  1577. }
  1578. RingAnalogValue EmulatedController::GetRingSensorValues() const {
  1579. return controller.ring_analog_value;
  1580. }
  1581. HomeButtonState EmulatedController::GetHomeButtons() const {
  1582. std::scoped_lock lock{mutex};
  1583. if (is_configuring) {
  1584. return {};
  1585. }
  1586. return controller.home_button_state;
  1587. }
  1588. CaptureButtonState EmulatedController::GetCaptureButtons() const {
  1589. std::scoped_lock lock{mutex};
  1590. if (is_configuring) {
  1591. return {};
  1592. }
  1593. return controller.capture_button_state;
  1594. }
  1595. NpadButtonState EmulatedController::GetNpadButtons() const {
  1596. std::scoped_lock lock{mutex};
  1597. if (is_configuring) {
  1598. return {};
  1599. }
  1600. return {controller.npad_button_state.raw & GetTurboButtonMask()};
  1601. }
  1602. DebugPadButton EmulatedController::GetDebugPadButtons() const {
  1603. std::scoped_lock lock{mutex};
  1604. if (is_configuring) {
  1605. return {};
  1606. }
  1607. return controller.debug_pad_button_state;
  1608. }
  1609. AnalogSticks EmulatedController::GetSticks() const {
  1610. std::scoped_lock lock{mutex};
  1611. if (is_configuring) {
  1612. return {};
  1613. }
  1614. return controller.analog_stick_state;
  1615. }
  1616. NpadGcTriggerState EmulatedController::GetTriggers() const {
  1617. std::scoped_lock lock{mutex};
  1618. if (is_configuring) {
  1619. return {};
  1620. }
  1621. return controller.gc_trigger_state;
  1622. }
  1623. MotionState EmulatedController::GetMotions() const {
  1624. std::unique_lock lock{mutex};
  1625. return controller.motion_state;
  1626. }
  1627. ControllerColors EmulatedController::GetColors() const {
  1628. std::scoped_lock lock{mutex};
  1629. return controller.colors_state;
  1630. }
  1631. BatteryLevelState EmulatedController::GetBattery() const {
  1632. std::scoped_lock lock{mutex};
  1633. return controller.battery_state;
  1634. }
  1635. const CameraState& EmulatedController::GetCamera() const {
  1636. std::scoped_lock lock{mutex};
  1637. return controller.camera_state;
  1638. }
  1639. RingSensorForce EmulatedController::GetRingSensorForce() const {
  1640. return controller.ring_analog_state;
  1641. }
  1642. const NfcState& EmulatedController::GetNfc() const {
  1643. std::scoped_lock lock{mutex};
  1644. return controller.nfc_state;
  1645. }
  1646. NpadColor EmulatedController::GetNpadColor(u32 color) {
  1647. return {
  1648. .r = static_cast<u8>((color >> 16) & 0xFF),
  1649. .g = static_cast<u8>((color >> 8) & 0xFF),
  1650. .b = static_cast<u8>(color & 0xFF),
  1651. .a = 0xff,
  1652. };
  1653. }
  1654. void EmulatedController::TriggerOnChange(ControllerTriggerType type, bool is_npad_service_update) {
  1655. std::scoped_lock lock{callback_mutex};
  1656. for (const auto& poller_pair : callback_list) {
  1657. const ControllerUpdateCallback& poller = poller_pair.second;
  1658. if (!is_npad_service_update && poller.is_npad_service) {
  1659. continue;
  1660. }
  1661. if (poller.on_change) {
  1662. poller.on_change(type);
  1663. }
  1664. }
  1665. }
  1666. int EmulatedController::SetCallback(ControllerUpdateCallback update_callback) {
  1667. std::scoped_lock lock{callback_mutex};
  1668. callback_list.insert_or_assign(last_callback_key, std::move(update_callback));
  1669. return last_callback_key++;
  1670. }
  1671. void EmulatedController::DeleteCallback(int key) {
  1672. std::scoped_lock lock{callback_mutex};
  1673. const auto& iterator = callback_list.find(key);
  1674. if (iterator == callback_list.end()) {
  1675. LOG_ERROR(Input, "Tried to delete non-existent callback {}", key);
  1676. return;
  1677. }
  1678. callback_list.erase(iterator);
  1679. }
  1680. void EmulatedController::StatusUpdate() {
  1681. turbo_button_state = (turbo_button_state + 1) % (TURBO_BUTTON_DELAY * 2);
  1682. // Some drivers like key motion need constant refreshing
  1683. for (std::size_t index = 0; index < motion_devices.size(); ++index) {
  1684. const auto& raw_status = controller.motion_values[index].raw_status;
  1685. auto& device = motion_devices[index];
  1686. if (!raw_status.force_update) {
  1687. continue;
  1688. }
  1689. if (!device) {
  1690. continue;
  1691. }
  1692. device->ForceUpdate();
  1693. }
  1694. }
  1695. NpadButton EmulatedController::GetTurboButtonMask() const {
  1696. // Apply no mask when disabled
  1697. if (turbo_button_state < TURBO_BUTTON_DELAY) {
  1698. return {NpadButton::All};
  1699. }
  1700. NpadButtonState button_mask{};
  1701. for (std::size_t index = 0; index < controller.button_values.size(); ++index) {
  1702. if (!controller.button_values[index].turbo) {
  1703. continue;
  1704. }
  1705. switch (index) {
  1706. case Settings::NativeButton::A:
  1707. button_mask.a.Assign(1);
  1708. break;
  1709. case Settings::NativeButton::B:
  1710. button_mask.b.Assign(1);
  1711. break;
  1712. case Settings::NativeButton::X:
  1713. button_mask.x.Assign(1);
  1714. break;
  1715. case Settings::NativeButton::Y:
  1716. button_mask.y.Assign(1);
  1717. break;
  1718. case Settings::NativeButton::L:
  1719. button_mask.l.Assign(1);
  1720. break;
  1721. case Settings::NativeButton::R:
  1722. button_mask.r.Assign(1);
  1723. break;
  1724. case Settings::NativeButton::ZL:
  1725. button_mask.zl.Assign(1);
  1726. break;
  1727. case Settings::NativeButton::ZR:
  1728. button_mask.zr.Assign(1);
  1729. break;
  1730. case Settings::NativeButton::DLeft:
  1731. button_mask.left.Assign(1);
  1732. break;
  1733. case Settings::NativeButton::DUp:
  1734. button_mask.up.Assign(1);
  1735. break;
  1736. case Settings::NativeButton::DRight:
  1737. button_mask.right.Assign(1);
  1738. break;
  1739. case Settings::NativeButton::DDown:
  1740. button_mask.down.Assign(1);
  1741. break;
  1742. case Settings::NativeButton::SLLeft:
  1743. button_mask.left_sl.Assign(1);
  1744. break;
  1745. case Settings::NativeButton::SLRight:
  1746. button_mask.right_sl.Assign(1);
  1747. break;
  1748. case Settings::NativeButton::SRLeft:
  1749. button_mask.left_sr.Assign(1);
  1750. break;
  1751. case Settings::NativeButton::SRRight:
  1752. button_mask.right_sr.Assign(1);
  1753. break;
  1754. default:
  1755. break;
  1756. }
  1757. }
  1758. return static_cast<NpadButton>(~button_mask.raw);
  1759. }
  1760. } // namespace Core::HID