SDL2Gamepad.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. using Ryujinx.Common.Configuration.Hid;
  2. using Ryujinx.Common.Configuration.Hid.Controller;
  3. using Ryujinx.Common.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Numerics;
  7. using static SDL2.SDL;
  8. namespace Ryujinx.Input.SDL2
  9. {
  10. class SDL2Gamepad : IGamepad
  11. {
  12. private bool HasConfiguration => _configuration != null;
  13. private record struct ButtonMappingEntry(GamepadButtonInputId To, GamepadButtonInputId From);
  14. private StandardControllerInputConfig _configuration;
  15. private static readonly SDL_GameControllerButton[] _buttonsDriverMapping = new SDL_GameControllerButton[(int)GamepadButtonInputId.Count]
  16. {
  17. // Unbound, ignored.
  18. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  19. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_A,
  20. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_B,
  21. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_X,
  22. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_Y,
  23. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSTICK,
  24. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSTICK,
  25. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
  26. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
  27. // NOTE: The left and right trigger are axis, we handle those differently
  28. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  29. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  30. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_UP,
  31. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_DOWN,
  32. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_LEFT,
  33. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
  34. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_BACK,
  35. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_START,
  36. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_GUIDE,
  37. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_MISC1,
  38. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE1,
  39. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE2,
  40. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE3,
  41. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE4,
  42. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_TOUCHPAD,
  43. // Virtual buttons are invalid, ignored.
  44. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  45. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  46. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  47. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  48. };
  49. private readonly object _userMappingLock = new();
  50. private readonly List<ButtonMappingEntry> _buttonsUserMapping;
  51. private readonly StickInputId[] _stickUserMapping = new StickInputId[(int)StickInputId.Count]
  52. {
  53. StickInputId.Unbound,
  54. StickInputId.Left,
  55. StickInputId.Right,
  56. };
  57. public GamepadFeaturesFlag Features { get; }
  58. private IntPtr _gamepadHandle;
  59. private float _triggerThreshold;
  60. public SDL2Gamepad(IntPtr gamepadHandle, string driverId)
  61. {
  62. _gamepadHandle = gamepadHandle;
  63. _buttonsUserMapping = new List<ButtonMappingEntry>(20);
  64. Name = SDL_GameControllerName(_gamepadHandle);
  65. Id = driverId;
  66. Features = GetFeaturesFlag();
  67. _triggerThreshold = 0.0f;
  68. // Enable motion tracking
  69. if (Features.HasFlag(GamepadFeaturesFlag.Motion))
  70. {
  71. if (SDL_GameControllerSetSensorEnabled(_gamepadHandle, SDL_SensorType.SDL_SENSOR_ACCEL, SDL_bool.SDL_TRUE) != 0)
  72. {
  73. Logger.Error?.Print(LogClass.Hid, $"Could not enable data reporting for SensorType {SDL_SensorType.SDL_SENSOR_ACCEL}.");
  74. }
  75. if (SDL_GameControllerSetSensorEnabled(_gamepadHandle, SDL_SensorType.SDL_SENSOR_GYRO, SDL_bool.SDL_TRUE) != 0)
  76. {
  77. Logger.Error?.Print(LogClass.Hid, $"Could not enable data reporting for SensorType {SDL_SensorType.SDL_SENSOR_GYRO}.");
  78. }
  79. }
  80. }
  81. private GamepadFeaturesFlag GetFeaturesFlag()
  82. {
  83. GamepadFeaturesFlag result = GamepadFeaturesFlag.None;
  84. if (SDL_GameControllerHasSensor(_gamepadHandle, SDL_SensorType.SDL_SENSOR_ACCEL) == SDL_bool.SDL_TRUE &&
  85. SDL_GameControllerHasSensor(_gamepadHandle, SDL_SensorType.SDL_SENSOR_GYRO) == SDL_bool.SDL_TRUE)
  86. {
  87. result |= GamepadFeaturesFlag.Motion;
  88. }
  89. int error = SDL_GameControllerRumble(_gamepadHandle, 0, 0, 100);
  90. if (error == 0)
  91. {
  92. result |= GamepadFeaturesFlag.Rumble;
  93. }
  94. return result;
  95. }
  96. public string Id { get; }
  97. public string Name { get; }
  98. public bool IsConnected => SDL_GameControllerGetAttached(_gamepadHandle) == SDL_bool.SDL_TRUE;
  99. protected virtual void Dispose(bool disposing)
  100. {
  101. if (disposing && _gamepadHandle != IntPtr.Zero)
  102. {
  103. SDL_GameControllerClose(_gamepadHandle);
  104. _gamepadHandle = IntPtr.Zero;
  105. }
  106. }
  107. public void Dispose()
  108. {
  109. Dispose(true);
  110. }
  111. public void SetTriggerThreshold(float triggerThreshold)
  112. {
  113. _triggerThreshold = triggerThreshold;
  114. }
  115. public void Rumble(float lowFrequency, float highFrequency, uint durationMs)
  116. {
  117. if (Features.HasFlag(GamepadFeaturesFlag.Rumble))
  118. {
  119. ushort lowFrequencyRaw = (ushort)(lowFrequency * ushort.MaxValue);
  120. ushort highFrequencyRaw = (ushort)(highFrequency * ushort.MaxValue);
  121. if (durationMs == uint.MaxValue)
  122. {
  123. if (SDL_GameControllerRumble(_gamepadHandle, lowFrequencyRaw, highFrequencyRaw, SDL_HAPTIC_INFINITY) != 0)
  124. {
  125. Logger.Error?.Print(LogClass.Hid, "Rumble is not supported on this game controller.");
  126. }
  127. }
  128. else if (durationMs > SDL_HAPTIC_INFINITY)
  129. {
  130. Logger.Error?.Print(LogClass.Hid, $"Unsupported rumble duration {durationMs}");
  131. }
  132. else
  133. {
  134. if (SDL_GameControllerRumble(_gamepadHandle, lowFrequencyRaw, highFrequencyRaw, durationMs) != 0)
  135. {
  136. Logger.Error?.Print(LogClass.Hid, "Rumble is not supported on this game controller.");
  137. }
  138. }
  139. }
  140. }
  141. public Vector3 GetMotionData(MotionInputId inputId)
  142. {
  143. SDL_SensorType sensorType = SDL_SensorType.SDL_SENSOR_INVALID;
  144. if (inputId == MotionInputId.Accelerometer)
  145. {
  146. sensorType = SDL_SensorType.SDL_SENSOR_ACCEL;
  147. }
  148. else if (inputId == MotionInputId.Gyroscope)
  149. {
  150. sensorType = SDL_SensorType.SDL_SENSOR_GYRO;
  151. }
  152. if (Features.HasFlag(GamepadFeaturesFlag.Motion) && sensorType != SDL_SensorType.SDL_SENSOR_INVALID)
  153. {
  154. const int ElementCount = 3;
  155. unsafe
  156. {
  157. float* values = stackalloc float[ElementCount];
  158. int result = SDL_GameControllerGetSensorData(_gamepadHandle, sensorType, (IntPtr)values, ElementCount);
  159. if (result == 0)
  160. {
  161. Vector3 value = new(values[0], values[1], values[2]);
  162. if (inputId == MotionInputId.Gyroscope)
  163. {
  164. return RadToDegree(value);
  165. }
  166. if (inputId == MotionInputId.Accelerometer)
  167. {
  168. return GsToMs2(value);
  169. }
  170. return value;
  171. }
  172. }
  173. }
  174. return Vector3.Zero;
  175. }
  176. private static Vector3 RadToDegree(Vector3 rad)
  177. {
  178. return rad * (180 / MathF.PI);
  179. }
  180. private static Vector3 GsToMs2(Vector3 gs)
  181. {
  182. return gs / SDL_STANDARD_GRAVITY;
  183. }
  184. public void SetConfiguration(InputConfig configuration)
  185. {
  186. lock (_userMappingLock)
  187. {
  188. _configuration = (StandardControllerInputConfig)configuration;
  189. _buttonsUserMapping.Clear();
  190. // First update sticks
  191. _stickUserMapping[(int)StickInputId.Left] = (StickInputId)_configuration.LeftJoyconStick.Joystick;
  192. _stickUserMapping[(int)StickInputId.Right] = (StickInputId)_configuration.RightJoyconStick.Joystick;
  193. // Then left joycon
  194. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftStick, (GamepadButtonInputId)_configuration.LeftJoyconStick.StickButton));
  195. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadUp, (GamepadButtonInputId)_configuration.LeftJoycon.DpadUp));
  196. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadDown, (GamepadButtonInputId)_configuration.LeftJoycon.DpadDown));
  197. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadLeft, (GamepadButtonInputId)_configuration.LeftJoycon.DpadLeft));
  198. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadRight, (GamepadButtonInputId)_configuration.LeftJoycon.DpadRight));
  199. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.Minus, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonMinus));
  200. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftShoulder, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonL));
  201. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftTrigger, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonZl));
  202. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleRightTrigger0, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonSr));
  203. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleLeftTrigger0, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonSl));
  204. // Finally right joycon
  205. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightStick, (GamepadButtonInputId)_configuration.RightJoyconStick.StickButton));
  206. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.A, (GamepadButtonInputId)_configuration.RightJoycon.ButtonA));
  207. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.B, (GamepadButtonInputId)_configuration.RightJoycon.ButtonB));
  208. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.X, (GamepadButtonInputId)_configuration.RightJoycon.ButtonX));
  209. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.Y, (GamepadButtonInputId)_configuration.RightJoycon.ButtonY));
  210. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.Plus, (GamepadButtonInputId)_configuration.RightJoycon.ButtonPlus));
  211. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightShoulder, (GamepadButtonInputId)_configuration.RightJoycon.ButtonR));
  212. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightTrigger, (GamepadButtonInputId)_configuration.RightJoycon.ButtonZr));
  213. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleRightTrigger1, (GamepadButtonInputId)_configuration.RightJoycon.ButtonSr));
  214. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleLeftTrigger1, (GamepadButtonInputId)_configuration.RightJoycon.ButtonSl));
  215. SetTriggerThreshold(_configuration.TriggerThreshold);
  216. }
  217. }
  218. public GamepadStateSnapshot GetStateSnapshot()
  219. {
  220. return IGamepad.GetStateSnapshot(this);
  221. }
  222. public GamepadStateSnapshot GetMappedStateSnapshot()
  223. {
  224. GamepadStateSnapshot rawState = GetStateSnapshot();
  225. GamepadStateSnapshot result = default;
  226. lock (_userMappingLock)
  227. {
  228. if (_buttonsUserMapping.Count == 0)
  229. {
  230. return rawState;
  231. }
  232. foreach (ButtonMappingEntry entry in _buttonsUserMapping)
  233. {
  234. if (entry.From == GamepadButtonInputId.Unbound || entry.To == GamepadButtonInputId.Unbound)
  235. {
  236. continue;
  237. }
  238. // Do not touch state of button already pressed
  239. if (!result.IsPressed(entry.To))
  240. {
  241. result.SetPressed(entry.To, rawState.IsPressed(entry.From));
  242. }
  243. }
  244. (float leftStickX, float leftStickY) = rawState.GetStick(_stickUserMapping[(int)StickInputId.Left]);
  245. (float rightStickX, float rightStickY) = rawState.GetStick(_stickUserMapping[(int)StickInputId.Right]);
  246. result.SetStick(StickInputId.Left, leftStickX, leftStickY);
  247. result.SetStick(StickInputId.Right, rightStickX, rightStickY);
  248. }
  249. return result;
  250. }
  251. private static float ConvertRawStickValue(short value)
  252. {
  253. const float ConvertRate = 1.0f / (short.MaxValue + 0.5f);
  254. return value * ConvertRate;
  255. }
  256. public (float, float) GetStick(StickInputId inputId)
  257. {
  258. if (inputId == StickInputId.Unbound)
  259. {
  260. return (0.0f, 0.0f);
  261. }
  262. short stickX;
  263. short stickY;
  264. if (inputId == StickInputId.Left)
  265. {
  266. stickX = SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTX);
  267. stickY = SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTY);
  268. }
  269. else if (inputId == StickInputId.Right)
  270. {
  271. stickX = SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTX);
  272. stickY = SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTY);
  273. }
  274. else
  275. {
  276. throw new NotSupportedException($"Unsupported stick {inputId}");
  277. }
  278. float resultX = ConvertRawStickValue(stickX);
  279. float resultY = -ConvertRawStickValue(stickY);
  280. if (HasConfiguration)
  281. {
  282. if ((inputId == StickInputId.Left && _configuration.LeftJoyconStick.InvertStickX) ||
  283. (inputId == StickInputId.Right && _configuration.RightJoyconStick.InvertStickX))
  284. {
  285. resultX = -resultX;
  286. }
  287. if ((inputId == StickInputId.Left && _configuration.LeftJoyconStick.InvertStickY) ||
  288. (inputId == StickInputId.Right && _configuration.RightJoyconStick.InvertStickY))
  289. {
  290. resultY = -resultY;
  291. }
  292. if ((inputId == StickInputId.Left && _configuration.LeftJoyconStick.Rotate90CW) ||
  293. (inputId == StickInputId.Right && _configuration.RightJoyconStick.Rotate90CW))
  294. {
  295. float temp = resultX;
  296. resultX = resultY;
  297. resultY = -temp;
  298. }
  299. }
  300. return (resultX, resultY);
  301. }
  302. public bool IsPressed(GamepadButtonInputId inputId)
  303. {
  304. if (inputId == GamepadButtonInputId.LeftTrigger)
  305. {
  306. return ConvertRawStickValue(SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERLEFT)) > _triggerThreshold;
  307. }
  308. if (inputId == GamepadButtonInputId.RightTrigger)
  309. {
  310. return ConvertRawStickValue(SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) > _triggerThreshold;
  311. }
  312. if (_buttonsDriverMapping[(int)inputId] == SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID)
  313. {
  314. return false;
  315. }
  316. return SDL_GameControllerGetButton(_gamepadHandle, _buttonsDriverMapping[(int)inputId]) == 1;
  317. }
  318. }
  319. }