Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/SDL/SDLGamepad.cpp

raw symbols SCIP
1 // Copyright 2025 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/SDL/SDLGamepad.h"
5
6 #include <array>
7 #include <span>
8 #include <unordered_set>
9
10 #include "Common/Logging/Log.h"
11 #include "Common/ScopeGuard.h"
12
13 namespace ciface::SDL
14 {
15
16 static bool IsTriggerAxis(int index)
17 {
18 // First 4 axes are for the analog sticks, the rest are for the triggers
19 return index >= 4;
20 }
21
22 Gamepad::Gamepad(SDL_Gamepad* const gamepad, SDL_Joystick* const joystick)
23 : m_gamepad(gamepad), m_joystick(joystick)
24 {
25 const char* const sdl_name =
26 (gamepad != nullptr) ? SDL_GetGamepadName(gamepad) : SDL_GetJoystickName(joystick);
27 m_name = (sdl_name != nullptr) ? sdl_name : "Unknown";
28
29 // If a Joystick input has a Gamepad equivalent button/hat we don't add it.
30 // "Equivalent" axes are still added as hidden/undetectable inputs to handle
31 // loading of existing configs which may use "full surface" inputs.
32 // Otherwise handling those would require dealing with gamepad specific quirks.
33 std::unordered_set<int> registered_buttons;
34 std::unordered_set<int> registered_hats;
35 std::unordered_set<int> registered_axes;
36 const auto register_mapping = [&](const SDL_GamepadBinding& bind) {
37 switch (bind.input_type)
38 {
39 case SDL_GAMEPAD_BINDTYPE_BUTTON:
40 registered_buttons.insert(bind.input.button);
41 break;
42 case SDL_GAMEPAD_BINDTYPE_HAT:
43 registered_hats.insert(bind.input.hat.hat);
44 break;
45 case SDL_GAMEPAD_BINDTYPE_AXIS:
46 registered_axes.insert(bind.input.axis.axis);
47 break;
48 default:
49 break;
50 }
51 };
52
53 if (gamepad != nullptr)
54 {
55 // Inputs
56 int binding_count = 0;
57 auto** bindings = SDL_GetGamepadBindings(gamepad, &binding_count);
58 Common::ScopeGuard free_bindings([&] { SDL_free(bindings); });
59
60 for (auto* const binding : std::span(bindings, binding_count))
61 {
62 register_mapping(*binding);
63
64 switch (binding->output_type)
65 {
66 case SDL_GAMEPAD_BINDTYPE_BUTTON:
67 AddInput(new Button(gamepad, *binding));
68 break;
69 case SDL_GAMEPAD_BINDTYPE_AXIS:
70 {
71 const auto axis = binding->output.axis.axis;
72 if (IsTriggerAxis(axis))
73 {
74 AddInput(new Axis(m_gamepad, 32767, axis));
75 }
76 else
77 {
78 // Each axis gets a negative and a positive input instance associated with it
79 AddInput(new Axis(m_gamepad, -32768, axis));
80 AddInput(new Axis(m_gamepad, 32767, axis));
81 }
82 break;
83 }
84 default:
85 break;
86 }
87 }
88
89 const auto properties = SDL_GetGamepadProperties(m_gamepad);
90
91 // Rumble
92 if (SDL_GetBooleanProperty(properties, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false))
93 {
94 AddOutput(new CombinedMotor(*this, &m_low_freq_rumble, &m_high_freq_rumble));
95 AddOutput(new Rumble("Motor L", *this, &m_low_freq_rumble, &Gamepad::UpdateRumble));
96 AddOutput(new Rumble("Motor R", *this, &m_high_freq_rumble, &Gamepad::UpdateRumble));
97 }
98 if (SDL_GetBooleanProperty(properties, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false))
99 {
100 AddOutput(
101 new Rumble("Trigger L", *this, &m_trigger_l_rumble, &Gamepad::UpdateRumbleTriggers));
102 AddOutput(
103 new Rumble("Trigger R", *this, &m_trigger_r_rumble, &Gamepad::UpdateRumbleTriggers));
104 }
105
106 // Touchpad
107 if (SDL_GetNumGamepadTouchpads(m_gamepad) > 0)
108 {
109 const char* const name_x = "Touchpad X";
110 AddInput(new NonDetectableDirectionalInput<-1>(name_x, &m_touchpad_x));
111 AddInput(new NonDetectableDirectionalInput<+1>(name_x, &m_touchpad_x));
112 const char* const name_y = "Touchpad Y";
113 AddInput(new NonDetectableDirectionalInput<-1>(name_y, &m_touchpad_y));
114 AddInput(new NonDetectableDirectionalInput<+1>(name_y, &m_touchpad_y));
115 AddInput(new NormalizedInput("Touchpad Pressure", &m_touchpad_pressure));
116 }
117
118 // Motion
119 const auto add_sensor = [this](SDL_SensorType type, std::string_view sensor_name,
120 const SDLMotionAxisList& axes) {
121 if (SDL_SetGamepadSensorEnabled(m_gamepad, type, true))
122 {
123 for (const SDLMotionAxis& axis : axes)
124 {
125 AddInput(new MotionInput(fmt::format("{} {}", sensor_name, axis.name), m_gamepad, type,
126 axis.index, axis.scale));
127 }
128 }
129 };
130
131 add_sensor(SDL_SENSOR_ACCEL, "Accel", SDL_AXES_ACCELEROMETER);
132 add_sensor(SDL_SENSOR_GYRO, "Gyro", SDL_AXES_GYRO);
133 add_sensor(SDL_SENSOR_ACCEL_L, "Accel L", SDL_AXES_ACCELEROMETER);
134 add_sensor(SDL_SENSOR_GYRO_L, "Gyro L", SDL_AXES_GYRO);
135 add_sensor(SDL_SENSOR_ACCEL_R, "Accel R", SDL_AXES_ACCELEROMETER);
136 add_sensor(SDL_SENSOR_GYRO_R, "Gyro R", SDL_AXES_GYRO);
137 }
138
139 // Legacy inputs
140
141 // Buttons
142 int n_legacy_buttons = SDL_GetNumJoystickButtons(joystick);
143 if (n_legacy_buttons < 0)
144 {
145 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Error in SDL_JoystickNumButtons(): {}", SDL_GetError());
146 n_legacy_buttons = 0;
147 }
148 for (int i = 0; i != n_legacy_buttons; ++i)
149 {
150 if (registered_buttons.contains(i))
151 continue;
152
153 AddInput(new LegacyButton(m_joystick, i));
154 }
155
156 // Axes
157 int n_legacy_axes = SDL_GetNumJoystickAxes(joystick);
158 if (n_legacy_axes < 0)
159 {
160 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Error in SDL_JoystickNumAxes(): {}", SDL_GetError());
161 n_legacy_axes = 0;
162 }
163 for (int i = 0; i != n_legacy_axes; ++i)
164 {
165 const bool is_registered = registered_axes.contains(i);
166
167 // each axis gets a negative and a positive input instance associated with it
168 AddFullAnalogSurfaceInputs(new LegacyAxis(m_joystick, i, -32768, is_registered),
169 new LegacyAxis(m_joystick, i, 32767, is_registered));
170 }
171
172 // Hats
173 int n_legacy_hats = SDL_GetNumJoystickHats(joystick);
174 if (n_legacy_hats < 0)
175 {
176 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Error in SDL_JoystickNumHats(): {}", SDL_GetError());
177 n_legacy_hats = 0;
178 }
179 for (int i = 0; i != n_legacy_hats; ++i)
180 {
181 if (registered_hats.contains(i))
182 continue;
183
184 // each hat gets 4 input instances associated with it, (up down left right)
185 for (u8 d = 0; d != 4; ++d)
186 AddInput(new LegacyHat(m_joystick, i, d));
187 }
188
189 // Haptics
190 if (SDL_IsJoystickHaptic(m_joystick))
191 {
192 m_haptic = SDL_OpenHapticFromJoystick(m_joystick);
193 if (m_haptic)
194 {
195 const unsigned int supported_effects = SDL_GetMaxHapticEffects(m_haptic);
196
197 // Disable autocenter:
198 if (supported_effects & SDL_HAPTIC_AUTOCENTER)
199 SDL_SetHapticAutocenter(m_haptic, 0);
200
201 // Constant
202 if (supported_effects & SDL_HAPTIC_CONSTANT)
203 AddOutput(new ConstantEffect(m_haptic));
204
205 // Ramp
206 if (supported_effects & SDL_HAPTIC_RAMP)
207 AddOutput(new RampEffect(m_haptic));
208
209 // Periodic
210 for (auto waveform :
211 {SDL_HAPTIC_SINE, SDL_HAPTIC_TRIANGLE, SDL_HAPTIC_SAWTOOTHUP, SDL_HAPTIC_SAWTOOTHDOWN})
212 {
213 if (supported_effects & waveform)
214 AddOutput(new PeriodicEffect(m_haptic, waveform));
215 }
216
217 // LeftRight
218 if (supported_effects & SDL_HAPTIC_LEFTRIGHT)
219 {
220 AddOutput(new LeftRightEffect(m_haptic, LeftRightEffect::Motor::Strong));
221 AddOutput(new LeftRightEffect(m_haptic, LeftRightEffect::Motor::Weak));
222 }
223 }
224 }
225
226 // Battery
227 if (UpdateBatteryLevel())
228 AddInput(new BatteryInput{&m_battery_value});
229 }
230
231 bool Gamepad::UpdateBatteryLevel()
232 {
233 int battery_percent = 0;
234 if (SDL_GetJoystickPowerInfo(m_joystick, &battery_percent) == SDL_POWERSTATE_ERROR)
235 return false;
236
237 m_battery_value = std::max(0, battery_percent);
238 return true;
239 }
240
241 Gamepad::~Gamepad()
242 {
243 if (m_haptic)
244 {
245 // stop/destroy all effects
246 SDL_StopHapticEffects(m_haptic);
247 // close haptic before joystick
248 SDL_CloseHaptic(m_haptic);
249 m_haptic = nullptr;
250 }
251 if (m_gamepad)
252 {
253 // stop all rumble
254 SDL_RumbleGamepad(m_gamepad, 0, 0, 0);
255 SDL_CloseGamepad(m_gamepad);
256 }
257 SDL_CloseJoystick(m_joystick);
258 }
259
260 std::string Gamepad::GetName() const
261 {
262 return m_name;
263 }
264
265 std::string Gamepad::GetSource() const
266 {
267 return "SDL";
268 }
269
270 SDL_JoystickID Gamepad::GetSDLInstanceID() const
271 {
272 return SDL_GetJoystickID(m_joystick);
273 }
274
275 std::string Gamepad::Button::GetName() const
276 {
277 const auto button = m_binding.output.button;
278
279 if (std::size_t(button) >= std::size(s_sdl_button_names))
280 return GetLegacyButtonName(button);
281
282 return s_sdl_button_names[button];
283 }
284
285 std::string Gamepad::Axis::GetName() const
286 {
287 if (std::size_t(m_axis) >= std::size(s_sdl_axis_names))
288 return GetLegacyAxisName(m_axis, m_range);
289
290 if (IsTriggerAxis(m_axis))
291 return s_sdl_axis_names[m_axis];
292
293 bool negative = m_range < 0;
294
295 // Respect XInput: the vertical axes are inverted on SDL
296 if (m_axis % 2 == 1)
297 negative = !negative;
298
299 return std::string(s_sdl_axis_names[m_axis]) + (negative ? '-' : '+');
300 }
301
302 ControlState Gamepad::Button::GetState() const
303 {
304 return SDL_GetGamepadButton(m_gc, m_binding.output.button);
305 }
306
307 ControlState Gamepad::Axis::GetState() const
308 {
309 return ControlState(SDL_GetGamepadAxis(m_gc, m_axis)) / m_range;
310 }
311
312 bool Gamepad::Button::IsMatchingName(std::string_view name) const
313 {
314 if (GetName() == name)
315 return true;
316
317 // Positionally match XInput button names.
318 // e.g. Switch Pro controller A-button matches "Button B".
319 // e.g. PlayStation controller Circle-button matches "Button B".
320 if (m_binding.output.button == SDL_GAMEPAD_BUTTON_SOUTH && name == "Button A")
321 return true;
322 if (m_binding.output.button == SDL_GAMEPAD_BUTTON_EAST && name == "Button B")
323 return true;
324 if (m_binding.output.button == SDL_GAMEPAD_BUTTON_WEST && name == "Button X")
325 return true;
326 if (m_binding.output.button == SDL_GAMEPAD_BUTTON_NORTH && name == "Button Y")
327 return true;
328
329 // Match the old "Button 0"-like names.
330 switch (m_binding.input_type)
331 {
332 case SDL_GAMEPAD_BINDTYPE_BUTTON:
333 return name == GetLegacyButtonName(m_binding.input.button);
334 case SDL_GAMEPAD_BINDTYPE_HAT:
335 return name == GetLegacyHatName(m_binding.input.hat.hat,
336 GetDirectionFromHatMask(m_binding.input.hat.hat_mask));
337 default:
338 return false;
339 }
340 }
341
342 ControlState Gamepad::MotionInput::GetState() const
343 {
344 std::array<float, 3> data{};
345 SDL_GetGamepadSensorData(m_gc, m_type, data.data(), (int)data.size());
346 return m_scale * data[m_index];
347 }
348
349 // Legacy input
350 ControlState Gamepad::LegacyButton::GetState() const
351 {
352 return SDL_GetJoystickButton(m_js, m_index);
353 }
354
355 ControlState Gamepad::LegacyAxis::GetState() const
356 {
357 return ControlState(SDL_GetJoystickAxis(m_js, m_index)) / m_range;
358 }
359
360 ControlState Gamepad::LegacyHat::GetState() const
361 {
362 return (SDL_GetJoystickHat(m_js, m_index) & (1 << m_direction)) > 0;
363 }
364
365 void Gamepad::HapticEffect::UpdateEffect()
366 {
367 if (m_effect.type != DISABLED_EFFECT_TYPE)
368 {
369 if (m_id < 0)
370 {
371 // Upload and try to play the effect.
372 m_id = SDL_CreateHapticEffect(m_haptic, &m_effect);
373
374 if (m_id >= 0)
375 SDL_RunHapticEffect(m_haptic, m_id, 1);
376 }
377 else
378 {
379 // Effect is already playing. Update parameters.
380 SDL_UpdateHapticEffect(m_haptic, m_id, &m_effect);
381 }
382 }
383 else if (m_id >= 0)
384 {
385 // Stop and remove the effect.
386 SDL_StopHapticEffect(m_haptic, m_id);
387 SDL_DestroyHapticEffect(m_haptic, m_id);
388 m_id = -1;
389 }
390 }
391
392 Gamepad::HapticEffect::HapticEffect(SDL_Haptic* haptic) : m_haptic(haptic)
393 {
394 // FYI: type is set within UpdateParameters.
395 m_effect.type = DISABLED_EFFECT_TYPE;
396 }
397
398 Gamepad::HapticEffect::~HapticEffect()
399 {
400 m_effect.type = DISABLED_EFFECT_TYPE;
401 UpdateEffect();
402 }
403
404 void Gamepad::HapticEffect::SetDirection(SDL_HapticDirection* dir)
405 {
406 // Left direction (for wheels)
407 dir->type = SDL_HAPTIC_CARTESIAN;
408 dir->dir[0] = -1;
409 }
410
411 Gamepad::ConstantEffect::ConstantEffect(SDL_Haptic* haptic) : HapticEffect(haptic)
412 {
413 m_effect.constant = {};
414 SetDirection(&m_effect.constant.direction);
415 m_effect.constant.length = RUMBLE_LENGTH_MS;
416 }
417
418 Gamepad::RampEffect::RampEffect(SDL_Haptic* haptic) : HapticEffect(haptic)
419 {
420 m_effect.ramp = {};
421 SetDirection(&m_effect.ramp.direction);
422 m_effect.ramp.length = RUMBLE_LENGTH_MS;
423 }
424
425 Gamepad::PeriodicEffect::PeriodicEffect(SDL_Haptic* haptic, u16 waveform)
426 : HapticEffect(haptic), m_waveform(waveform)
427 {
428 m_effect.periodic = {};
429 SetDirection(&m_effect.periodic.direction);
430 m_effect.periodic.length = RUMBLE_LENGTH_MS;
431 m_effect.periodic.period = RUMBLE_PERIOD_MS;
432 m_effect.periodic.offset = 0;
433 m_effect.periodic.phase = 0;
434 }
435
436 Gamepad::LeftRightEffect::LeftRightEffect(SDL_Haptic* haptic, Motor motor)
437 : HapticEffect(haptic), m_motor(motor)
438 {
439 m_effect.leftright = {};
440 m_effect.leftright.length = RUMBLE_LENGTH_MS;
441 }
442
443 std::string Gamepad::ConstantEffect::GetName() const
444 {
445 return "Constant";
446 }
447
448 std::string Gamepad::RampEffect::GetName() const
449 {
450 return "Ramp";
451 }
452
453 std::string Gamepad::PeriodicEffect::GetName() const
454 {
455 switch (m_waveform)
456 {
457 case SDL_HAPTIC_SINE:
458 return "Sine";
459 case SDL_HAPTIC_TRIANGLE:
460 return "Triangle";
461 case SDL_HAPTIC_SAWTOOTHUP:
462 return "Sawtooth Up";
463 case SDL_HAPTIC_SAWTOOTHDOWN:
464 return "Sawtooth Down";
465 default:
466 return "Unknown";
467 }
468 }
469
470 std::string Gamepad::LeftRightEffect::GetName() const
471 {
472 return (Motor::Strong == m_motor) ? "Strong" : "Weak";
473 }
474
475 void Gamepad::HapticEffect::SetState(ControlState state)
476 {
477 // Maximum force value for all SDL effects:
478 constexpr s16 MAX_FORCE_VALUE = 0x7fff;
479
480 if (UpdateParameters(s16(state * MAX_FORCE_VALUE)))
481 {
482 UpdateEffect();
483 }
484 }
485
486 bool Gamepad::ConstantEffect::UpdateParameters(s16 value)
487 {
488 s16& level = m_effect.constant.level;
489 const s16 old_level = level;
490
491 level = value;
492
493 m_effect.type = level ? SDL_HAPTIC_CONSTANT : DISABLED_EFFECT_TYPE;
494 return level != old_level;
495 }
496
497 bool Gamepad::RampEffect::UpdateParameters(s16 value)
498 {
499 s16& level = m_effect.ramp.start;
500 const s16 old_level = level;
501
502 level = value;
503 // FYI: Setting end to same as start is odd,
504 // but so is using Ramp effects for rumble simulation.
505 m_effect.ramp.end = level;
506
507 m_effect.type = level ? SDL_HAPTIC_RAMP : DISABLED_EFFECT_TYPE;
508 return level != old_level;
509 }
510
511 bool Gamepad::PeriodicEffect::UpdateParameters(s16 value)
512 {
513 s16& level = m_effect.periodic.magnitude;
514 const s16 old_level = level;
515
516 level = value;
517
518 m_effect.type = level ? m_waveform : DISABLED_EFFECT_TYPE;
519 return level != old_level;
520 }
521
522 bool Gamepad::LeftRightEffect::UpdateParameters(s16 value)
523 {
524 u16& level = (Motor::Strong == m_motor) ? m_effect.leftright.large_magnitude :
525 m_effect.leftright.small_magnitude;
526 const u16 old_level = level;
527
528 level = value;
529
530 m_effect.type = level ? SDL_HAPTIC_LEFTRIGHT : DISABLED_EFFECT_TYPE;
531 return level != old_level;
532 }
533 } // namespace ciface::SDL