input.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. // SPDX-FileCopyrightText: 2017 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <functional>
  5. #include <memory>
  6. #include <string>
  7. #include <unordered_map>
  8. #include <utility>
  9. #include <vector>
  10. #include "common/logging/log.h"
  11. #include "common/param_package.h"
  12. #include "common/uuid.h"
  13. namespace Common::Input {
  14. // Type of data that is expected to recieve or send
  15. enum class InputType {
  16. None,
  17. Battery,
  18. Button,
  19. Stick,
  20. Analog,
  21. Trigger,
  22. Motion,
  23. Touch,
  24. Color,
  25. Vibration,
  26. Nfc,
  27. IrSensor,
  28. };
  29. // Internal battery charge level
  30. enum class BatteryLevel : u32 {
  31. None,
  32. Empty,
  33. Critical,
  34. Low,
  35. Medium,
  36. Full,
  37. Charging,
  38. };
  39. enum class PollingMode {
  40. // Constant polling of buttons, analogs and motion data
  41. Active,
  42. // Only update on button change, digital analogs
  43. Pasive,
  44. // Enable near field communication polling
  45. NFC,
  46. // Enable infrared camera polling
  47. IR,
  48. // Enable ring controller polling
  49. Ring,
  50. };
  51. enum class CameraFormat {
  52. Size320x240,
  53. Size160x120,
  54. Size80x60,
  55. Size40x30,
  56. Size20x15,
  57. None,
  58. };
  59. // Different results that can happen from a device request
  60. enum class DriverResult {
  61. Success,
  62. WrongReply,
  63. Timeout,
  64. UnsupportedControllerType,
  65. HandleInUse,
  66. ErrorReadingData,
  67. ErrorWritingData,
  68. NoDeviceDetected,
  69. InvalidHandle,
  70. NotSupported,
  71. Disabled,
  72. Unknown,
  73. };
  74. // Nfc reply from the controller
  75. enum class NfcState {
  76. Success,
  77. NewAmiibo,
  78. WaitingForAmiibo,
  79. AmiiboRemoved,
  80. NotAnAmiibo,
  81. NotSupported,
  82. WrongDeviceState,
  83. WriteFailed,
  84. Unknown,
  85. };
  86. // Hint for amplification curve to be used
  87. enum class VibrationAmplificationType {
  88. Linear,
  89. Exponential,
  90. };
  91. // Analog properties for calibration
  92. struct AnalogProperties {
  93. // Anything below this value will be detected as zero
  94. float deadzone{};
  95. // Anyting above this values will be detected as one
  96. float range{1.0f};
  97. // Minimum value to be detected as active
  98. float threshold{0.5f};
  99. // Drift correction applied to the raw data
  100. float offset{};
  101. // Invert direction of the sensor data
  102. bool inverted{};
  103. // Press once to activate, press again to release
  104. bool toggle{};
  105. };
  106. // Single analog sensor data
  107. struct AnalogStatus {
  108. float value{};
  109. float raw_value{};
  110. AnalogProperties properties{};
  111. };
  112. // Button data
  113. struct ButtonStatus {
  114. Common::UUID uuid{};
  115. bool value{};
  116. // Invert value of the button
  117. bool inverted{};
  118. // Press once to activate, press again to release
  119. bool toggle{};
  120. // Spams the button when active
  121. bool turbo{};
  122. // Internal lock for the toggle status
  123. bool locked{};
  124. };
  125. // Internal battery data
  126. using BatteryStatus = BatteryLevel;
  127. // Analog and digital joystick data
  128. struct StickStatus {
  129. Common::UUID uuid{};
  130. AnalogStatus x{};
  131. AnalogStatus y{};
  132. bool left{};
  133. bool right{};
  134. bool up{};
  135. bool down{};
  136. };
  137. // Analog and digital trigger data
  138. struct TriggerStatus {
  139. Common::UUID uuid{};
  140. AnalogStatus analog{};
  141. ButtonStatus pressed{};
  142. };
  143. // 3D vector representing motion input
  144. struct MotionSensor {
  145. AnalogStatus x{};
  146. AnalogStatus y{};
  147. AnalogStatus z{};
  148. };
  149. // Motion data used to calculate controller orientation
  150. struct MotionStatus {
  151. // Gyroscope vector measurement in radians/s.
  152. MotionSensor gyro{};
  153. // Acceleration vector measurement in G force
  154. MotionSensor accel{};
  155. // Time since last measurement in microseconds
  156. u64 delta_timestamp{};
  157. // Request to update after reading the value
  158. bool force_update{};
  159. };
  160. // Data of a single point on a touch screen
  161. struct TouchStatus {
  162. ButtonStatus pressed{};
  163. AnalogStatus x{};
  164. AnalogStatus y{};
  165. int id{};
  166. };
  167. // Physical controller color in RGB format
  168. struct BodyColorStatus {
  169. u32 body{};
  170. u32 buttons{};
  171. u32 left_grip{};
  172. u32 right_grip{};
  173. };
  174. // HD rumble data
  175. struct VibrationStatus {
  176. f32 low_amplitude{};
  177. f32 low_frequency{};
  178. f32 high_amplitude{};
  179. f32 high_frequency{};
  180. VibrationAmplificationType type;
  181. };
  182. // Physical controller LED pattern
  183. struct LedStatus {
  184. bool led_1{};
  185. bool led_2{};
  186. bool led_3{};
  187. bool led_4{};
  188. };
  189. // Raw data fom camera
  190. struct CameraStatus {
  191. CameraFormat format{CameraFormat::None};
  192. std::vector<u8> data{};
  193. };
  194. struct NfcStatus {
  195. NfcState state{};
  196. std::vector<u8> data{};
  197. };
  198. // List of buttons to be passed to Qt that can be translated
  199. enum class ButtonNames {
  200. Undefined,
  201. Invalid,
  202. // This will display the engine name instead of the button name
  203. Engine,
  204. // This will display the button by value instead of the button name
  205. Value,
  206. // Joycon button names
  207. ButtonLeft,
  208. ButtonRight,
  209. ButtonDown,
  210. ButtonUp,
  211. ButtonA,
  212. ButtonB,
  213. ButtonX,
  214. ButtonY,
  215. ButtonPlus,
  216. ButtonMinus,
  217. ButtonHome,
  218. ButtonCapture,
  219. ButtonStickL,
  220. ButtonStickR,
  221. TriggerL,
  222. TriggerZL,
  223. TriggerSL,
  224. TriggerR,
  225. TriggerZR,
  226. TriggerSR,
  227. // GC button names
  228. TriggerZ,
  229. ButtonStart,
  230. // DS4 button names
  231. L1,
  232. L2,
  233. L3,
  234. R1,
  235. R2,
  236. R3,
  237. Circle,
  238. Cross,
  239. Square,
  240. Triangle,
  241. Share,
  242. Options,
  243. Home,
  244. Touch,
  245. // Mouse buttons
  246. ButtonMouseWheel,
  247. ButtonBackward,
  248. ButtonForward,
  249. ButtonTask,
  250. ButtonExtra,
  251. };
  252. // Callback data consisting of an input type and the equivalent data status
  253. struct CallbackStatus {
  254. InputType type{InputType::None};
  255. ButtonStatus button_status{};
  256. StickStatus stick_status{};
  257. AnalogStatus analog_status{};
  258. TriggerStatus trigger_status{};
  259. MotionStatus motion_status{};
  260. TouchStatus touch_status{};
  261. BodyColorStatus color_status{};
  262. BatteryStatus battery_status{};
  263. VibrationStatus vibration_status{};
  264. CameraFormat camera_status{CameraFormat::None};
  265. NfcState nfc_status{NfcState::Unknown};
  266. std::vector<u8> raw_data{};
  267. };
  268. // Triggered once every input change
  269. struct InputCallback {
  270. std::function<void(const CallbackStatus&)> on_change;
  271. };
  272. /// An abstract class template for an input device (a button, an analog input, etc.).
  273. class InputDevice {
  274. public:
  275. virtual ~InputDevice() = default;
  276. // Force input device to update data regardless of the current state
  277. virtual void ForceUpdate() {}
  278. // Sets the function to be triggered when input changes
  279. void SetCallback(InputCallback callback_) {
  280. callback = std::move(callback_);
  281. }
  282. // Triggers the function set in the callback
  283. void TriggerOnChange(const CallbackStatus& status) {
  284. if (callback.on_change) {
  285. callback.on_change(status);
  286. }
  287. }
  288. private:
  289. InputCallback callback;
  290. };
  291. /// An abstract class template for an output device (rumble, LED pattern, polling mode).
  292. class OutputDevice {
  293. public:
  294. virtual ~OutputDevice() = default;
  295. virtual DriverResult SetLED([[maybe_unused]] const LedStatus& led_status) {
  296. return DriverResult::NotSupported;
  297. }
  298. virtual DriverResult SetVibration([[maybe_unused]] const VibrationStatus& vibration_status) {
  299. return DriverResult::NotSupported;
  300. }
  301. virtual bool IsVibrationEnabled() {
  302. return false;
  303. }
  304. virtual DriverResult SetPollingMode([[maybe_unused]] PollingMode polling_mode) {
  305. return DriverResult::NotSupported;
  306. }
  307. virtual DriverResult SetCameraFormat([[maybe_unused]] CameraFormat camera_format) {
  308. return DriverResult::NotSupported;
  309. }
  310. virtual NfcState SupportsNfc() const {
  311. return NfcState::NotSupported;
  312. }
  313. virtual NfcState WriteNfcData([[maybe_unused]] const std::vector<u8>& data) {
  314. return NfcState::NotSupported;
  315. }
  316. };
  317. /// An abstract class template for a factory that can create input devices.
  318. template <typename InputDeviceType>
  319. class Factory {
  320. public:
  321. virtual ~Factory() = default;
  322. virtual std::unique_ptr<InputDeviceType> Create(const Common::ParamPackage&) = 0;
  323. };
  324. namespace Impl {
  325. template <typename InputDeviceType>
  326. using FactoryListType = std::unordered_map<std::string, std::shared_ptr<Factory<InputDeviceType>>>;
  327. template <typename InputDeviceType>
  328. struct FactoryList {
  329. static FactoryListType<InputDeviceType> list;
  330. };
  331. template <typename InputDeviceType>
  332. FactoryListType<InputDeviceType> FactoryList<InputDeviceType>::list;
  333. } // namespace Impl
  334. /**
  335. * Registers an input device factory.
  336. * @tparam InputDeviceType the type of input devices the factory can create
  337. * @param name the name of the factory. Will be used to match the "engine" parameter when creating
  338. * a device
  339. * @param factory the factory object to register
  340. */
  341. template <typename InputDeviceType>
  342. void RegisterFactory(const std::string& name, std::shared_ptr<Factory<InputDeviceType>> factory) {
  343. auto pair = std::make_pair(name, std::move(factory));
  344. if (!Impl::FactoryList<InputDeviceType>::list.insert(std::move(pair)).second) {
  345. LOG_ERROR(Input, "Factory '{}' already registered", name);
  346. }
  347. }
  348. inline void RegisterInputFactory(const std::string& name,
  349. std::shared_ptr<Factory<InputDevice>> factory) {
  350. RegisterFactory<InputDevice>(name, std::move(factory));
  351. }
  352. inline void RegisterOutputFactory(const std::string& name,
  353. std::shared_ptr<Factory<OutputDevice>> factory) {
  354. RegisterFactory<OutputDevice>(name, std::move(factory));
  355. }
  356. /**
  357. * Unregisters an input device factory.
  358. * @tparam InputDeviceType the type of input devices the factory can create
  359. * @param name the name of the factory to unregister
  360. */
  361. template <typename InputDeviceType>
  362. void UnregisterFactory(const std::string& name) {
  363. if (Impl::FactoryList<InputDeviceType>::list.erase(name) == 0) {
  364. LOG_ERROR(Input, "Factory '{}' not registered", name);
  365. }
  366. }
  367. inline void UnregisterInputFactory(const std::string& name) {
  368. UnregisterFactory<InputDevice>(name);
  369. }
  370. inline void UnregisterOutputFactory(const std::string& name) {
  371. UnregisterFactory<OutputDevice>(name);
  372. }
  373. /**
  374. * Create an input device from given paramters.
  375. * @tparam InputDeviceType the type of input devices to create
  376. * @param params a serialized ParamPackage string that contains all parameters for creating the
  377. * device
  378. */
  379. template <typename InputDeviceType>
  380. std::unique_ptr<InputDeviceType> CreateDeviceFromString(const std::string& params) {
  381. const Common::ParamPackage package(params);
  382. const std::string engine = package.Get("engine", "null");
  383. const auto& factory_list = Impl::FactoryList<InputDeviceType>::list;
  384. const auto pair = factory_list.find(engine);
  385. if (pair == factory_list.end()) {
  386. if (engine != "null") {
  387. LOG_ERROR(Input, "Unknown engine name: {}", engine);
  388. }
  389. return std::make_unique<InputDeviceType>();
  390. }
  391. return pair->second->Create(package);
  392. }
  393. inline std::unique_ptr<InputDevice> CreateInputDeviceFromString(const std::string& params) {
  394. return CreateDeviceFromString<InputDevice>(params);
  395. }
  396. inline std::unique_ptr<OutputDevice> CreateOutputDeviceFromString(const std::string& params) {
  397. return CreateDeviceFromString<OutputDevice>(params);
  398. }
  399. /**
  400. * Create an input device from given parameters.
  401. * @tparam InputDeviceType the type of input devices to create
  402. * @param package A ParamPackage that contains all parameters for creating the device
  403. */
  404. template <typename InputDeviceType>
  405. std::unique_ptr<InputDeviceType> CreateDevice(const ParamPackage& package) {
  406. const std::string engine = package.Get("engine", "null");
  407. const auto& factory_list = Impl::FactoryList<InputDeviceType>::list;
  408. const auto pair = factory_list.find(engine);
  409. if (pair == factory_list.end()) {
  410. if (engine != "null") {
  411. LOG_ERROR(Input, "Unknown engine name: {}", engine);
  412. }
  413. return std::make_unique<InputDeviceType>();
  414. }
  415. return pair->second->Create(package);
  416. }
  417. inline std::unique_ptr<InputDevice> CreateInputDevice(const ParamPackage& package) {
  418. return CreateDevice<InputDevice>(package);
  419. }
  420. inline std::unique_ptr<OutputDevice> CreateOutputDevice(const ParamPackage& package) {
  421. return CreateDevice<OutputDevice>(package);
  422. }
  423. } // namespace Common::Input