5#include <QtCore/QMetaObject>
6#include <QtCore/QMutex>
7#include <QtCore/QThread>
39 switch (event->type) {
40 case SDL_EVENT_JOYSTICK_ADDED:
41 qCInfo(JoystickSDLLog) <<
"SDL event: Joystick added, instance ID:" <<
event->jdevice.which;
42 QMetaObject::invokeMethod(manager,
"_checkForAddedOrRemovedJoysticks", Qt::QueuedConnection);
44 case SDL_EVENT_JOYSTICK_REMOVED:
45 qCInfo(JoystickSDLLog) <<
"SDL event: Joystick removed, instance ID:" <<
event->jdevice.which;
46 QMetaObject::invokeMethod(manager,
"_checkForAddedOrRemovedJoysticks", Qt::QueuedConnection);
49 case SDL_EVENT_GAMEPAD_ADDED:
50 qCDebug(JoystickSDLLog) <<
"SDL event: Gamepad added (ignored, handled via joystick event), instance ID:" <<
event->gdevice.which;
52 case SDL_EVENT_GAMEPAD_REMOVED:
53 qCDebug(JoystickSDLLog) <<
"SDL event: Gamepad removed (ignored, handled via joystick event), instance ID:" <<
event->gdevice.which;
56 case SDL_EVENT_JOYSTICK_BATTERY_UPDATED:
57 qCDebug(JoystickSDLLog) <<
"Battery updated for joystick" <<
event->jbattery.which
58 <<
"state:" <<
event->jbattery.state
59 <<
"percent:" <<
event->jbattery.percent;
60 QMetaObject::invokeMethod(manager,
"_handleBatteryUpdated",
62 Q_ARG(
int,
static_cast<int>(event->jbattery.which)));
65 case SDL_EVENT_GAMEPAD_REMAPPED:
66 qCDebug(JoystickSDLLog) <<
"Gamepad remapped:" <<
event->gdevice.which;
67 QMetaObject::invokeMethod(manager,
"_handleGamepadRemapped",
69 Q_ARG(
int,
static_cast<int>(event->gdevice.which)));
72 case SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN:
73 case SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION:
74 case SDL_EVENT_GAMEPAD_TOUCHPAD_UP:
75 QMetaObject::invokeMethod(manager,
"_handleTouchpadEvent",
77 Q_ARG(
int,
static_cast<int>(event->gtouchpad.which)),
78 Q_ARG(
int, event->gtouchpad.touchpad),
79 Q_ARG(
int, event->gtouchpad.finger),
80 Q_ARG(
bool, event->type != SDL_EVENT_GAMEPAD_TOUCHPAD_UP),
81 Q_ARG(
float, event->gtouchpad.x),
82 Q_ARG(
float, event->gtouchpad.y),
83 Q_ARG(
float, event->gtouchpad.pressure));
86 case SDL_EVENT_GAMEPAD_SENSOR_UPDATE:
87 QMetaObject::invokeMethod(manager,
"_handleSensorUpdate",
89 Q_ARG(
int,
static_cast<int>(event->gsensor.which)),
90 Q_ARG(
int, event->gsensor.sensor),
91 Q_ARG(
float, event->gsensor.data[0]),
92 Q_ARG(
float, event->gsensor.data[1]),
93 Q_ARG(
float, event->gsensor.data[2]));
96 case SDL_EVENT_JOYSTICK_UPDATE_COMPLETE:
97 case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE:
98 QMetaObject::invokeMethod(manager,
"_handleUpdateComplete",
100 Q_ARG(
int,
static_cast<int>(event->common.type == SDL_EVENT_GAMEPAD_UPDATE_COMPLETE
101 ? event->gdevice.which : event->jdevice.which)));
112 :
Joystick(
name, gamepadAxes.length() + nonGamepadAxes.length()
113#ifdef TEST_WITH_VIRTUAL_AXES
117 , _gamepadAxes(gamepadAxes)
118 , _nonGamepadAxes(nonGamepadAxes)
121 qCDebug(JoystickSDLLog) <<
this;
126 qCDebug(JoystickSDLLog) <<
this;
129quint64 JoystickSDL::_getProperties()
const
132 return SDL_GetGamepadProperties(_sdlGamepad);
135 return SDL_GetJoystickProperties(_sdlJoystick);
140bool JoystickSDL::_checkVirtualJoystick(
const char *methodName)
const
143 qCWarning(JoystickSDLLog) << methodName <<
"called with null joystick";
147 qCWarning(JoystickSDLLog) << methodName <<
"called on non-virtual joystick:" <<
_name;
153bool JoystickSDL::_hasGamepadCapability(
const char *propertyName)
const
156 SDL_PropertiesID props = SDL_GetGamepadProperties(_sdlGamepad);
157 return SDL_GetBooleanProperty(props, propertyName,
false);
177 QMap<QString, Joystick*> cache;
182 if (deleteDiscoveryCache) {
189 if (!QThread::isMainThread()) {
191 qCCritical(JoystickSDLLog) <<
"Internal Error: called off the main thread, returning the previous discovery";
196 QMap<QString, Joystick*> current;
198 QMap<QString, Joystick*> previous;
204 qCDebug(JoystickSDLLog) <<
"Discovering joysticks";
212 SDL_JoystickID *ids = SDL_GetJoysticks(&count);
214 qCWarning(JoystickSDLLog) <<
"SDL_GetJoysticks failed:" << SDL_GetError();
218 qCDebug(JoystickSDLLog) <<
"SDL_GetJoysticks returned" << count <<
"joysticks";
219 for (
int n = 0; n < count; ++n) {
221 qCDebug(JoystickSDLLog) <<
" [" << n <<
"] ID:" << ids[n]
222 <<
"Name:" << joystickName
223 <<
"IsGamepad:" << SDL_IsGamepad(ids[n]);
226 for (
int n = 0; n < count; ++n) {
227 const SDL_JoystickID jid = ids[n];
229 if (baseName.isEmpty()) {
230 baseName = QStringLiteral(
"Joystick %1").arg(jid);
232 QString
name = baseName;
235 bool foundInCache =
false;
236 for (
auto it = previous.begin(); it != previous.end(); ++it) {
237 auto *cachedJs =
static_cast<JoystickSDL*
>(it.value());
238 if (
static_cast<SDL_JoystickID
>(cachedJs->instanceId()) == jid) {
239 if (cachedJs->name() == baseName) {
241 current[
name] = cachedJs;
247 cachedJs->deleteLater();
258 if (previous.contains(
name) && !current.contains(
name)) {
261 js->setInstanceId(jid);
262 (void) previous.remove(
name);
267 int duplicateIndex = 2;
268 while (current.contains(
name) || previous.contains(
name)) {
269 name = QStringLiteral(
"%1 #%2").arg(baseName).arg(duplicateIndex++);
272 QList<int> gamepadAxes;
273 QSet<int> joyAxesMappedToGamepad;
275 if (SDL_IsGamepad(jid)) {
276 auto tmpGamepad = SDL_OpenGamepad(jid);
278 qCWarning(JoystickSDLLog) <<
"Failed to open gamepad" << jid << SDL_GetError();
283 for (
int i = 0; i < SDL_GAMEPAD_AXIS_COUNT; i++) {
284 if (SDL_GamepadHasAxis(tmpGamepad,
static_cast<SDL_GamepadAxis
>(i))) {
285 gamepadAxes.append(i);
292 int bindingCount = 0;
293 SDL_GamepadBinding **bindings = SDL_GetGamepadBindings(tmpGamepad, &bindingCount);
295 for (
int i = 0; i < bindingCount; ++i) {
296 SDL_GamepadBinding *binding = bindings[i];
297 if (binding && binding->input_type == SDL_GAMEPAD_BINDTYPE_AXIS && binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS) {
298 joyAxesMappedToGamepad.insert(binding->input.axis.axis);
303 qCWarning(JoystickSDLLog) <<
"Failed to get bindings for" <<
name <<
"error:" << SDL_GetError();
306 SDL_CloseGamepad(tmpGamepad);
311 qCWarning(JoystickSDLLog) <<
"Failed to open joystick" << jid << SDL_GetError();
315 QList<int> nonGamepadAxes;
316 const int axisCount = SDL_GetNumJoystickAxes(tmpJoy);
318 if (!joyAxesMappedToGamepad.contains(i)) {
319 nonGamepadAxes.append(i);
323 const int buttonCount = SDL_GetNumJoystickButtons(tmpJoy);
324 const int hatCount = SDL_GetNumJoystickHats(tmpJoy);
325 SDL_CloseJoystick(tmpJoy);
327 qCDebug(JoystickSDLLog) <<
"Creating JoystickSDL for" <<
name <<
"jid:" << jid;
339 qCDebug(JoystickSDLLog) <<
"Discovered" << current.size() <<
"joysticks:";
340 for (
auto it = current.begin(); it != current.end(); ++it) {
342 qCDebug(JoystickSDLLog) <<
" " << it.key() <<
"instanceId:" << js->instanceId();
345 for (
auto* joystick : std::as_const(previous)) {
346 joystick->deleteLater();
358bool JoystickSDL::_open()
361 _sdlGamepad = SDL_OpenGamepad(_instanceId);
363 qCWarning(JoystickSDLLog) <<
"SDL_OpenGamepad failed:" << SDL_GetError();
366 _sdlJoystick = SDL_GetGamepadJoystick(_sdlGamepad);
368 _sdlJoystick = SDL_OpenJoystick(_instanceId);
372 qCWarning(JoystickSDLLog) <<
"SDL_JoystickOpen failed:" << SDL_GetError();
376 qCDebug(JoystickSDLLog) <<
"Opened" << SDL_GetJoystickName(_sdlJoystick) <<
"joystick at" << _sdlJoystick;
381void JoystickSDL::_close()
384 qCWarning(JoystickSDLLog) <<
"Attempt to close null joystick!";
388 qCDebug(JoystickSDLLog) <<
"Closing joystick" <<
_name <<
"at" << _sdlJoystick;
391 SDL_CloseHaptic(_sdlHaptic);
392 _sdlHaptic =
nullptr;
396 SDL_CloseGamepad(_sdlGamepad);
398 SDL_CloseJoystick(_sdlJoystick);
401 _sdlJoystick =
nullptr;
402 _sdlGamepad =
nullptr;
405bool JoystickSDL::_update()
407 if (!_sdlJoystick || !SDL_JoystickConnected(_sdlJoystick)) {
408 qCWarning(JoystickSDLLog) <<
"Joystick disconnected during update:" <<
_name;
413 SDL_UpdateGamepads();
415 SDL_UpdateJoysticks();
425bool JoystickSDL::_getButton(
int idx)
const
428 if (_sdlGamepad && (idx >= 0) && (idx < SDL_GAMEPAD_BUTTON_COUNT)) {
429 return SDL_GetGamepadButton(_sdlGamepad,
static_cast<SDL_GamepadButton
>(idx));
433 if (_sdlJoystick && (idx >= 0) && (idx < SDL_GetNumJoystickButtons(_sdlJoystick))) {
434 return SDL_GetJoystickButton(_sdlJoystick, idx);
440int JoystickSDL::_getAxisValue(
int idx)
const
446#ifdef TEST_WITH_VIRTUAL_AXES
448 const int totalPhysicalAxes = _gamepadAxes.length() + _nonGamepadAxes.length();
449 if (idx >= totalPhysicalAxes && idx < totalPhysicalAxes + 2) {
451 bool button0Down =
false;
453 button0Down = SDL_GetGamepadButton(_sdlGamepad,
static_cast<SDL_GamepadButton
>(0));
454 }
else if (_sdlJoystick) {
455 button0Down = SDL_GetJoystickButton(_sdlJoystick, 0);
460 const int virtualAxisIdx = idx - totalPhysicalAxes;
461 if (virtualAxisIdx == 0) {
463 if (_sdlGamepad && _gamepadAxes.length() > 0) {
464 return SDL_GetGamepadAxis(_sdlGamepad,
static_cast<SDL_GamepadAxis
>(_gamepadAxes[0]));
465 }
else if (_sdlJoystick) {
466 return SDL_GetJoystickAxis(_sdlJoystick, 0);
470 if (_sdlGamepad && _gamepadAxes.length() > 1) {
471 return SDL_GetGamepadAxis(_sdlGamepad,
static_cast<SDL_GamepadAxis
>(_gamepadAxes[1]));
472 }
else if (_sdlJoystick) {
473 return SDL_GetJoystickAxis(_sdlJoystick, 1);
484 if (idx < _gamepadAxes.length()) {
485 return SDL_GetGamepadAxis(_sdlGamepad,
static_cast<SDL_GamepadAxis
>(_gamepadAxes[idx]));
487 const int nonGamepadIdx = idx -
static_cast<int>(_gamepadAxes.length());
488 if (nonGamepadIdx < _nonGamepadAxes.length()) {
489 return SDL_GetJoystickAxis(_sdlJoystick, _nonGamepadAxes[nonGamepadIdx]);
494 return SDL_GetJoystickAxis(_sdlJoystick, idx);
497bool JoystickSDL::_getHat(
int hat,
int idx)
const
499 static constexpr std::array<uint8_t, 4> hatButtons = {SDL_HAT_UP, SDL_HAT_DOWN, SDL_HAT_LEFT, SDL_HAT_RIGHT};
501 if (idx < 0 ||
static_cast<size_t>(idx) >= hatButtons.size()) {
505 return ((SDL_GetJoystickHat(_sdlJoystick, hat) & hatButtons[idx]) != 0);
514 const quint64 props = _getProperties();
515 return props != 0 && SDL_GetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN,
false);
520 const quint64 props = _getProperties();
521 return props != 0 && SDL_GetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN,
false);
526 const quint64 props = _getProperties();
530 return SDL_GetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN,
false) ||
531 SDL_GetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN,
false);
537 if (!SDL_RumbleGamepad(_sdlGamepad, lowFreq, highFreq, durationMs)) {
538 qCDebug(JoystickSDLLog) <<
"Rumble failed:" << SDL_GetError();
540 }
else if (_sdlJoystick) {
541 if (!SDL_RumbleJoystick(_sdlJoystick, lowFreq, highFreq, durationMs)) {
542 qCDebug(JoystickSDLLog) <<
"Rumble failed:" << SDL_GetError();
550 if (!SDL_RumbleGamepadTriggers(_sdlGamepad, left, right, durationMs)) {
551 qCDebug(JoystickSDLLog) <<
"Trigger rumble failed:" << SDL_GetError();
559 if (!SDL_SetGamepadLED(_sdlGamepad, red, green, blue)) {
560 qCDebug(JoystickSDLLog) <<
"Set LED failed:" << SDL_GetError();
562 }
else if (_sdlJoystick) {
563 if (!SDL_SetJoystickLED(_sdlJoystick, red, green, blue)) {
564 qCDebug(JoystickSDLLog) <<
"Set LED failed:" << SDL_GetError();
571 if (_sdlGamepad && !data.isEmpty()) {
572 if (!SDL_SendGamepadEffect(_sdlGamepad, data.constData(),
static_cast<int>(data.size()))) {
573 qCDebug(JoystickSDLLog) <<
"sendEffect failed:" << SDL_GetError();
588 SDL_GUID sdlGuid = SDL_GetJoystickGUID(_sdlJoystick);
590 SDL_GUIDToString(sdlGuid, guidStr,
sizeof(guidStr));
591 return QString::fromLatin1(guidStr);
599 return SDL_GetJoystickVendor(_sdlJoystick);
607 return SDL_GetJoystickProduct(_sdlJoystick);
615 const char *serialStr = SDL_GetJoystickSerial(_sdlJoystick);
617 return QString::fromUtf8(serialStr);
626 SDL_JoystickType type = SDL_GetJoystickType(_sdlJoystick);
628 case SDL_JOYSTICK_TYPE_GAMEPAD:
629 return QStringLiteral(
"Gamepad");
630 case SDL_JOYSTICK_TYPE_WHEEL:
631 return QStringLiteral(
"Wheel");
632 case SDL_JOYSTICK_TYPE_ARCADE_STICK:
633 return QStringLiteral(
"Arcade Stick");
634 case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
635 return QStringLiteral(
"Flight Stick");
636 case SDL_JOYSTICK_TYPE_DANCE_PAD:
637 return QStringLiteral(
"Dance Pad");
638 case SDL_JOYSTICK_TYPE_GUITAR:
639 return QStringLiteral(
"Guitar");
640 case SDL_JOYSTICK_TYPE_DRUM_KIT:
641 return QStringLiteral(
"Drum Kit");
642 case SDL_JOYSTICK_TYPE_ARCADE_PAD:
643 return QStringLiteral(
"Arcade Pad");
644 case SDL_JOYSTICK_TYPE_THROTTLE:
645 return QStringLiteral(
"Throttle");
647 return QStringLiteral(
"Unknown");
656 const char *devicePath = SDL_GetJoystickPath(_sdlJoystick);
658 return QString::fromUtf8(devicePath);
666 return SDL_IsJoystickVirtual(_instanceId);
672 return SDL_GetJoystickFirmwareVersion(_sdlJoystick);
695 return SDL_GetGamepadPlayerIndex(_sdlGamepad);
698 return SDL_GetJoystickPlayerIndex(_sdlJoystick);
705 bool success =
false;
707 success = SDL_SetGamepadPlayerIndex(_sdlGamepad, index);
708 }
else if (_sdlJoystick) {
709 success = SDL_SetJoystickPlayerIndex(_sdlJoystick, index);
715 qCDebug(JoystickSDLLog) <<
"Failed to set player index:" << SDL_GetError();
727 SDL_GetJoystickPowerInfo(_sdlJoystick, &percent);
739 switch (SDL_GetJoystickPowerInfo(_sdlJoystick,
nullptr)) {
740 case SDL_POWERSTATE_ERROR:
741 return QStringLiteral(
"Error");
742 case SDL_POWERSTATE_UNKNOWN:
743 return QStringLiteral(
"Unknown");
744 case SDL_POWERSTATE_ON_BATTERY:
745 return QStringLiteral(
"On Battery");
746 case SDL_POWERSTATE_NO_BATTERY:
747 return QStringLiteral(
"No Battery");
748 case SDL_POWERSTATE_CHARGING:
749 return QStringLiteral(
"Charging");
750 case SDL_POWERSTATE_CHARGED:
751 return QStringLiteral(
"Charged");
763 return SDL_IsGamepad(_instanceId);
781 return tr(
"Axis %1").arg(axis);
785 if (_sdlGamepad && axis < _gamepadAxes.length()) {
786 const char *label = SDL_GetGamepadStringForAxis(
static_cast<SDL_GamepadAxis
>(_gamepadAxes[axis]));
788 return QString::fromUtf8(label);
793 const int nonGamepadIdx = axis - _gamepadAxes.length();
794 if (nonGamepadIdx >= 0 && nonGamepadIdx < _nonGamepadAxes.length()) {
796 return tr(
"Axis %1").arg(_nonGamepadAxes[nonGamepadIdx]);
799 return tr(
"Axis %1").arg(axis);
804 if (_sdlGamepad && button >= 0 && button < SDL_GAMEPAD_BUTTON_COUNT) {
805 const char *label = SDL_GetGamepadStringForButton(
static_cast<SDL_GamepadButton
>(button));
807 return QString::fromUtf8(label);
810 return tr(
"Button %1").arg(button);
820 char *mapping = SDL_GetGamepadMapping(_sdlGamepad);
822 QString result = QString::fromUtf8(mapping);
832 if (mapping.isEmpty()) {
836 int result = SDL_AddGamepadMapping(qPrintable(mapping));
838 qCWarning(JoystickSDLLog) <<
"Failed to add gamepad mapping:" << SDL_GetError();
842 qCDebug(JoystickSDLLog) <<
"Added gamepad mapping, result:" << result;
849 result[QStringLiteral(
"valid")] =
false;
856 if (_sdlGamepad && axis < _gamepadAxes.length()) {
857 const SDL_GamepadAxis gamepadAxis =
static_cast<SDL_GamepadAxis
>(_gamepadAxes[axis]);
859 return binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS &&
860 binding->output.axis.axis == gamepadAxis;
865 const int nonGamepadIdx = axis - _gamepadAxes.length();
866 if (nonGamepadIdx >= 0 && nonGamepadIdx < _nonGamepadAxes.length()) {
867 result[QStringLiteral(
"valid")] =
true;
868 result[QStringLiteral(
"inputType")] =
static_cast<int>(SDL_GAMEPAD_BINDTYPE_AXIS);
869 result[QStringLiteral(
"inputAxis")] = _nonGamepadAxes[nonGamepadIdx];
870 result[QStringLiteral(
"inputAxisMin")] = -32768;
871 result[QStringLiteral(
"inputAxisMax")] = 32767;
872 result[QStringLiteral(
"direct")] =
true;
881 if (!_sdlGamepad || button < 0 || button >= SDL_GAMEPAD_BUTTON_COUNT) {
883 result[QStringLiteral(
"valid")] =
false;
887 const SDL_GamepadButton gamepadButton =
static_cast<SDL_GamepadButton
>(button);
889 return binding->output_type == SDL_GAMEPAD_BINDTYPE_BUTTON &&
890 binding->output.button == gamepadButton;
901 return SDL_GamepadHasSensor(_sdlGamepad, SDL_SENSOR_GYRO);
909 return SDL_GamepadHasSensor(_sdlGamepad, SDL_SENSOR_ACCEL);
917 if (!SDL_SetGamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_GYRO, enabled)) {
918 qCWarning(JoystickSDLLog) <<
"Failed to" << (enabled ?
"enable" :
"disable") <<
"gyroscope:" << SDL_GetError();
929 if (!SDL_SetGamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_ACCEL, enabled)) {
930 qCWarning(JoystickSDLLog) <<
"Failed to" << (enabled ?
"enable" :
"disable") <<
"accelerometer:" << SDL_GetError();
941 if (_gyroDataCached) {
942 return _cachedGyroData;
948 std::array<float, 3> data = {0.0f, 0.0f, 0.0f};
949 if (!SDL_GetGamepadSensorData(_sdlGamepad, SDL_SENSOR_GYRO, data.data(), 3)) {
951 if (SDL_GamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_GYRO)) {
952 qCDebug(JoystickSDLLog) <<
"Failed to get gyroscope data:" << SDL_GetError();
956 return QVector3D(data[0], data[1], data[2]);
962 if (_accelDataCached) {
963 return _cachedAccelData;
969 std::array<float, 3> data = {0.0f, 0.0f, 0.0f};
970 if (!SDL_GetGamepadSensorData(_sdlGamepad, SDL_SENSOR_ACCEL, data.data(), 3)) {
972 if (SDL_GamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_ACCEL)) {
973 qCDebug(JoystickSDLLog) <<
"Failed to get accelerometer data:" << SDL_GetError();
977 return QVector3D(data[0], data[1], data[2]);
983 return SDL_GetGamepadSensorDataRate(_sdlGamepad, SDL_SENSOR_GYRO);
991 return SDL_GetGamepadSensorDataRate(_sdlGamepad, SDL_SENSOR_ACCEL);
1003 return SDL_GetNumGamepadTouchpads(_sdlGamepad);
1011 return SDL_GetNumGamepadTouchpadFingers(_sdlGamepad, touchpad);
1021 float x = 0.0f, y = 0.0f, pressure = 0.0f;
1022 if (SDL_GetGamepadTouchpadFinger(_sdlGamepad, touchpad, finger, &down, &x, &y, &pressure)) {
1023 result[QStringLiteral(
"valid")] =
true;
1024 result[QStringLiteral(
"down")] = down;
1025 result[QStringLiteral(
"x")] = x;
1026 result[QStringLiteral(
"y")] = y;
1027 result[QStringLiteral(
"pressure")] = pressure;
1031 result[QStringLiteral(
"valid")] =
false;
1042 return SDL_GetNumJoystickBalls(_sdlJoystick);
1052 if (SDL_GetJoystickBall(_sdlJoystick, ball, &dx, &dy)) {
1053 result[QStringLiteral(
"valid")] =
true;
1054 result[QStringLiteral(
"dx")] = dx;
1055 result[QStringLiteral(
"dy")] = dy;
1059 result[QStringLiteral(
"valid")] =
false;
1069 if (_sdlGamepad && button >= 0 && button < SDL_GAMEPAD_BUTTON_COUNT) {
1070 return SDL_GamepadHasButton(_sdlGamepad,
static_cast<SDL_GamepadButton
>(button));
1072 if (_sdlJoystick && button >= 0 && button < SDL_GetNumJoystickButtons(_sdlJoystick)) {
1080 if (_sdlGamepad && axis >= 0 && axis < _gamepadAxes.length()) {
1081 return SDL_GamepadHasAxis(_sdlGamepad,
static_cast<SDL_GamepadAxis
>(_gamepadAxes[axis]));
1084 const int totalAxes = _gamepadAxes.length() + _nonGamepadAxes.length()
1085#ifdef TEST_WITH_VIRTUAL_AXES
1089 return axis >= 0 && axis < totalAxes;
1108 if (_sdlGamepad && button >= 0 && button < SDL_GAMEPAD_BUTTON_COUNT) {
1109 SDL_GamepadType type = SDL_GetGamepadType(_sdlGamepad);
1110 SDL_GamepadButtonLabel label = SDL_GetGamepadButtonLabelForType(type,
static_cast<SDL_GamepadButton
>(button));
1112 case SDL_GAMEPAD_BUTTON_LABEL_A:
1113 return QStringLiteral(
"A");
1114 case SDL_GAMEPAD_BUTTON_LABEL_B:
1115 return QStringLiteral(
"B");
1116 case SDL_GAMEPAD_BUTTON_LABEL_X:
1117 return QStringLiteral(
"X");
1118 case SDL_GAMEPAD_BUTTON_LABEL_Y:
1119 return QStringLiteral(
"Y");
1120 case SDL_GAMEPAD_BUTTON_LABEL_CROSS:
1121 return QStringLiteral(
"Cross");
1122 case SDL_GAMEPAD_BUTTON_LABEL_CIRCLE:
1123 return QStringLiteral(
"Circle");
1124 case SDL_GAMEPAD_BUTTON_LABEL_SQUARE:
1125 return QStringLiteral(
"Square");
1126 case SDL_GAMEPAD_BUTTON_LABEL_TRIANGLE:
1127 return QStringLiteral(
"Triangle");
1142 return SDL_IsJoystickHaptic(_sdlJoystick);
1150 return SDL_GetMaxHapticEffects(_sdlHaptic);
1158 const Uint32 features = SDL_GetHapticFeatures(_sdlHaptic);
1159 return (features & SDL_HAPTIC_LEFTRIGHT) || (features & SDL_HAPTIC_SINE);
1170 if (!_sdlJoystick || !SDL_IsJoystickHaptic(_sdlJoystick)) {
1174 _sdlHaptic = SDL_OpenHapticFromJoystick(_sdlJoystick);
1176 qCWarning(JoystickSDLLog) <<
"Failed to open haptic device:" << SDL_GetError();
1180 if (!SDL_InitHapticRumble(_sdlHaptic)) {
1181 qCWarning(JoystickSDLLog) <<
"Failed to init haptic rumble:" << SDL_GetError();
1182 SDL_CloseHaptic(_sdlHaptic);
1183 _sdlHaptic =
nullptr;
1187 qCDebug(JoystickSDLLog) <<
"Haptic rumble initialized";
1199 if (!SDL_PlayHapticRumble(_sdlHaptic, strength, durationMs)) {
1200 qCWarning(JoystickSDLLog) <<
"Failed to play haptic rumble:" << SDL_GetError();
1209 SDL_StopHapticRumble(_sdlHaptic);
1219 if (
guid.isEmpty()) {
1223 SDL_GUID sdlGuid = SDL_StringToGUID(qPrintable(
guid));
1224 char *mapping = SDL_GetGamepadMappingForGUID(sdlGuid);
1226 QString result = QString::fromUtf8(mapping);
1239 if (!_checkVirtualJoystick(
"setVirtualAxis")) {
1243 if (!SDL_SetJoystickVirtualAxis(_sdlJoystick, axis,
static_cast<Sint16
>(value))) {
1244 qCDebug(JoystickSDLLog) <<
"Failed to set virtual axis" << axis <<
":" << SDL_GetError();
1252 if (!_checkVirtualJoystick(
"setVirtualButton")) {
1256 if (!SDL_SetJoystickVirtualButton(_sdlJoystick, button, down)) {
1257 qCDebug(JoystickSDLLog) <<
"Failed to set virtual button" << button <<
":" << SDL_GetError();
1265 if (!_checkVirtualJoystick(
"setVirtualHat")) {
1269 if (!SDL_SetJoystickVirtualHat(_sdlJoystick, hat, value)) {
1270 qCDebug(JoystickSDLLog) <<
"Failed to set virtual hat" << hat <<
":" << SDL_GetError();
1282 return _hasGamepadCapability(SDL_PROP_GAMEPAD_CAP_MONO_LED_BOOLEAN);
1287 return _hasGamepadCapability(SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN);
1292 return _hasGamepadCapability(SDL_PROP_GAMEPAD_CAP_PLAYER_LED_BOOLEAN);
1311 result[QStringLiteral(
"valid")] =
false;
1312 result[QStringLiteral(
"value")] = 0;
1314 if (!_sdlJoystick || axis < 0) {
1318 Sint16 initialValue = 0;
1319 if (SDL_GetJoystickAxisInitialState(_sdlJoystick, axis, &initialValue)) {
1320 result[QStringLiteral(
"valid")] =
true;
1321 result[QStringLiteral(
"value")] =
static_cast<int>(initialValue);
1332 if (!_sdlGamepad || mapping.isEmpty()) {
1336 if (!SDL_SetGamepadMapping(SDL_GetJoystickID(_sdlJoystick), qPrintable(mapping))) {
1337 qCDebug(JoystickSDLLog) <<
"Failed to set gamepad mapping:" << SDL_GetError();
1349 if (!_checkVirtualJoystick(
"setVirtualBall")) {
1353 if (!SDL_SetJoystickVirtualBall(_sdlJoystick, ball,
static_cast<Sint16
>(dx),
static_cast<Sint16
>(dy))) {
1354 qCDebug(JoystickSDLLog) <<
"Failed to set virtual ball" << ball <<
":" << SDL_GetError();
1362 if (!_checkVirtualJoystick(
"setVirtualTouchpad")) {
1367 const float clampedX = qBound(0.0f, x, 1.0f);
1368 const float clampedY = qBound(0.0f, y, 1.0f);
1369 const float clampedPressure = qBound(0.0f, pressure, 1.0f);
1371 if (x != clampedX || y != clampedY || pressure != clampedPressure) {
1372 qCDebug(JoystickSDLLog) <<
"Virtual touchpad coordinates clamped: x" << x <<
"->" << clampedX
1373 <<
"y" << y <<
"->" << clampedY
1374 <<
"pressure" << pressure <<
"->" << clampedPressure;
1377 if (!SDL_SetJoystickVirtualTouchpad(_sdlJoystick, touchpad, finger, down, clampedX, clampedY, clampedPressure)) {
1378 qCDebug(JoystickSDLLog) <<
"Failed to set virtual touchpad" << touchpad <<
"finger" << finger <<
":" << SDL_GetError();
1386 if (!_checkVirtualJoystick(
"sendVirtualSensorData")) {
1390 const float data[3] = {x, y, z};
1391 if (!SDL_SendJoystickVirtualSensorData(_sdlJoystick,
static_cast<SDL_SensorType
>(sensorType), SDL_GetTicksNS(), data, 3)) {
1392 qCDebug(JoystickSDLLog) <<
"Failed to send virtual sensor data:" << SDL_GetError();
1404 _cachedGyroData = data;
1405 _gyroDataCached =
true;
1411 _cachedAccelData = data;
1412 _accelDataCached =
true;
1419 if (currentState != _lastConnectionState && !currentState.isEmpty()) {
1420 qCDebug(JoystickSDLLog) <<
"Connection state changed:" << _lastConnectionState <<
"->" << currentState;
1421 _lastConnectionState = currentState;
1428 QVariantList driftingAxes;
1430 const int totalAxes = _gamepadAxes.length() + _nonGamepadAxes.length();
1431 for (
int i = 0; i < totalAxes; ++i) {
1432 const int currentValue = _getAxisValue(i);
1436 if (qAbs(currentValue) > threshold) {
1437 QVariantMap axisInfo;
1438 axisInfo[QStringLiteral(
"axis")] = i;
1439 axisInfo[QStringLiteral(
"label")] =
axisLabel(i);
1440 axisInfo[QStringLiteral(
"value")] = currentValue;
1441 axisInfo[QStringLiteral(
"percentage")] = qRound(qAbs(currentValue) * 100.0 / 32767.0);
1442 driftingAxes.append(axisInfo);
1446 return driftingAxes;
static QMap< QString, Joystick * > s_discoveryCache
static QMutex s_discoveryCacheMutex
static bool sdlEventWatcher(void *userdata, SDL_Event *event)
SDL event watcher - uses Qt::QueuedConnection for thread safety.
struct SDL_Joystick SDL_Joystick
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static JoystickManager * instance()
QString getMapping() const override
QString powerState() const override
bool isVirtual() const override
int batteryPercent() const override
quint16 vendorId() const override
QVariantMap getTouchpadFinger(int touchpad, int finger) const override
bool addMapping(const QString &mapping) override
QVariantMap getButtonBinding(int button) const override
void rumbleTriggers(quint16 left, quint16 right, quint32 durationMs) override
bool setVirtualButton(int button, bool down) override
QString serial() const override
bool setMapping(const QString &mapping) override
void updateCachedGyroData(const QVector3D &data)
bool setVirtualTouchpad(int touchpad, int finger, bool down, float x, float y, float pressure) override
QVector3D gyroscopeData() const override
void checkConnectionStateChanged()
bool hasAxis(int axis) const override
bool hasPlayerLED() const override
JoystickSDL(const QString &name, const QList< int > &gamepadAxes, const QList< int > &nonGamepadAxes, int buttonCount, int hatCount, int instanceId, QObject *parent=nullptr)
int playerIndex() const override
bool setVirtualHat(int hat, quint8 value) override
static void shutdown(bool deleteDiscoveryCache=true)
QString deviceType() const override
QString realGamepadType() const override
QVariantMap getBall(int ball) const override
void setPlayerIndex(int index) override
QVariantMap getAxisInitialState(int axis) const override
bool hasGyroscope() const override
bool hasMonoLED() const override
quint16 productId() const override
bool setAccelerometerEnabled(bool enabled) override
QString gamepadType() const override
void rumble(quint16 lowFreq, quint16 highFreq, quint32 durationMs) override
bool setVirtualBall(int ball, int dx, int dy) override
QString axisLabel(int axis) const override
QString getMappingForGUID(const QString &guid) const override
bool setVirtualAxis(int axis, int value) override
static QMap< QString, Joystick * > discover()
int ballCount() const override
void hapticRumbleStop() override
Q_INVOKABLE QVariantList detectAxisDrift(int threshold=8000) const
bool hasAccelerometer() const override
bool hasRumble() const override
void updateCachedAccelData(const QVector3D &data)
bool hapticRumblePlay(float strength, quint32 durationMs) override
QString buttonLabel(int button) const override
QVector3D accelerometerData() const override
QString connectionState() const override
QString buttonLabelForType(int button) const override
QVariantMap getAxisBinding(int axis) const override
QString connectionType() const override
bool hasButton(int button) const override
QString path() const override
QString guid() const override
bool isGamepad() const override
bool hasRumbleTriggers() const override
bool sendVirtualSensorData(int sensorType, float x, float y, float z) override
void setLED(quint8 red, quint8 green, quint8 blue) override
float gyroscopeDataRate() const override
float accelerometerDataRate() const override
bool hasRGBLED() const override
bool hasLED() const override
bool hasHaptic() const override
bool hapticRumbleSupported() const override
bool sendEffect(const QByteArray &data) override
quint16 firmwareVersion() const override
int hapticEffectsCount() const override
int touchpadCount() const override
int touchpadFingerCount(int touchpad) const override
bool hapticRumbleInit() override
bool setGyroscopeEnabled(bool enabled) override
Joystick(const QString &name, int axisCount, int buttonCount, int hatCount, QObject *parent=nullptr)
void playerIndexChanged()
void connectionStateChanged(const QString &newState)
void accelerometerDataUpdated(const QVector3D &data)
void gyroscopeDataUpdated(const QVector3D &data)
RAII lock guard for joysticks.
QString connectionStateToString(int state)
Connection state to string.
void shutdown()
Shutdown SDL joystick/gamepad subsystems.
QString gamepadTypeDisplayName(int type)
bool init()
Initialize SDL joystick/gamepad subsystems with QGC-specific hints.
QString getNameForInstanceId(int instanceId)
Get device name for instance ID.
QVariantMap findBinding(SDL_Gamepad *gamepad, const std::function< bool(const SDL_GamepadBinding *)> &matchFunc)
void pumpEvents()
Pump SDL events (call periodically).