SDL2Gamepad.cs 16 KB

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