QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
JoystickSDL.cc
Go to the documentation of this file.
1#include "JoystickSDL.h"
2
3#include <array>
4
5#include <QtCore/QMetaObject>
6#include <QtCore/QMutex>
7#include <QtCore/QThread>
8
9#include "JoystickManager.h"
10#include "QGCLoggingCategory.h"
11#include "SDLJoystick.h"
12#include <SDL3/SDL.h>
13
14// This is used for testing manual control extensions which require additional axes but all you have is a gamepad/joystick with limited axes.
15// Only available on debug builds.
16#ifdef QT_DEBUG
17//#define TEST_WITH_VIRTUAL_AXES
18#endif
19
20QGC_LOGGING_CATEGORY(JoystickSDLLog, "Joystick.JoystickSDL")
21
22
26static QMap<QString, Joystick*> s_discoveryCache;
28
30static bool sdlEventWatcher(void *userdata, SDL_Event *event)
31{
32 Q_UNUSED(userdata);
33
35 if (!manager) {
36 return true;
37 }
38
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);
43 break;
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);
47 break;
48 // Gamepad events ignored - SDL fires both joystick and gamepad events for gamepads
49 case SDL_EVENT_GAMEPAD_ADDED:
50 qCDebug(JoystickSDLLog) << "SDL event: Gamepad added (ignored, handled via joystick event), instance ID:" << event->gdevice.which;
51 break;
52 case SDL_EVENT_GAMEPAD_REMOVED:
53 qCDebug(JoystickSDLLog) << "SDL event: Gamepad removed (ignored, handled via joystick event), instance ID:" << event->gdevice.which;
54 break;
55
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",
61 Qt::QueuedConnection,
62 Q_ARG(int, static_cast<int>(event->jbattery.which)));
63 break;
64
65 case SDL_EVENT_GAMEPAD_REMAPPED:
66 qCDebug(JoystickSDLLog) << "Gamepad remapped:" << event->gdevice.which;
67 QMetaObject::invokeMethod(manager, "_handleGamepadRemapped",
68 Qt::QueuedConnection,
69 Q_ARG(int, static_cast<int>(event->gdevice.which)));
70 break;
71
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",
76 Qt::QueuedConnection,
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));
84 break;
85
86 case SDL_EVENT_GAMEPAD_SENSOR_UPDATE:
87 QMetaObject::invokeMethod(manager, "_handleSensorUpdate",
88 Qt::QueuedConnection,
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]));
94 break;
95
96 case SDL_EVENT_JOYSTICK_UPDATE_COMPLETE:
97 case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE:
98 QMetaObject::invokeMethod(manager, "_handleUpdateComplete",
99 Qt::QueuedConnection,
100 Q_ARG(int, static_cast<int>(event->common.type == SDL_EVENT_GAMEPAD_UPDATE_COMPLETE
101 ? event->gdevice.which : event->jdevice.which)));
102 break;
103
104 default:
105 break;
106 }
107
108 return true;
109}
110
111JoystickSDL::JoystickSDL(const QString &name, const QList<int> &gamepadAxes, const QList<int> &nonGamepadAxes, int buttonCount, int hatCount, int instanceId, QObject *parent)
112 : Joystick(name, gamepadAxes.length() + nonGamepadAxes.length()
113#ifdef TEST_WITH_VIRTUAL_AXES
114 + 2 // Add 2 virtual axes for testing
115#endif
116 , buttonCount, hatCount, parent)
117 , _gamepadAxes(gamepadAxes)
118 , _nonGamepadAxes(nonGamepadAxes)
119 , _instanceId(instanceId)
120{
121 qCDebug(JoystickSDLLog) << this;
122}
123
125{
126 qCDebug(JoystickSDLLog) << this;
127}
128
129quint64 JoystickSDL::_getProperties() const
130{
131 if (_sdlGamepad) {
132 return SDL_GetGamepadProperties(_sdlGamepad);
133 }
134 if (_sdlJoystick) {
135 return SDL_GetJoystickProperties(_sdlJoystick);
136 }
137 return 0;
138}
139
140bool JoystickSDL::_checkVirtualJoystick(const char *methodName) const
141{
142 if (!_sdlJoystick) {
143 qCWarning(JoystickSDLLog) << methodName << "called with null joystick";
144 return false;
145 }
146 if (!isVirtual()) {
147 qCWarning(JoystickSDLLog) << methodName << "called on non-virtual joystick:" << _name;
148 return false;
149 }
150 return true;
151}
152
153bool JoystickSDL::_hasGamepadCapability(const char *propertyName) const
154{
155 if (_sdlGamepad) {
156 SDL_PropertiesID props = SDL_GetGamepadProperties(_sdlGamepad);
157 return SDL_GetBooleanProperty(props, propertyName, false);
158 }
159 return false;
160}
161
163{
164 if (!SDLJoystick::init()) {
165 return false;
166 }
167
168 SDL_AddEventWatch(sdlEventWatcher, nullptr);
169 return true;
170}
171
172void JoystickSDL::shutdown(bool deleteDiscoveryCache)
173{
174 SDL_RemoveEventWatch(sdlEventWatcher, nullptr);
176
177 QMap<QString, Joystick*> cache;
178 {
179 const QMutexLocker cacheLocker(&s_discoveryCacheMutex);
180 cache.swap(s_discoveryCache);
181 }
182 if (deleteDiscoveryCache) {
183 qDeleteAll(cache);
184 }
185}
186
187QMap<QString, Joystick*> JoystickSDL::discover()
188{
189 if (!QThread::isMainThread()) {
190 // An empty map would make the caller delete joysticks that the cache still points to
191 qCCritical(JoystickSDLLog) << "Internal Error: called off the main thread, returning the previous discovery";
192 const QMutexLocker cacheLocker(&s_discoveryCacheMutex);
193 return s_discoveryCache;
194 }
195
196 QMap<QString, Joystick*> current;
197 // Working copy of the cache: joysticks found again move to current, the rest are deleted at the end
198 QMap<QString, Joystick*> previous;
199 {
200 const QMutexLocker cacheLocker(&s_discoveryCacheMutex);
201 previous = s_discoveryCache;
202 }
203
204 qCDebug(JoystickSDLLog) << "Discovering joysticks";
205
206 // Required on Android before SDL_GetJoysticks() returns devices
208
210
211 int count = 0;
212 SDL_JoystickID *ids = SDL_GetJoysticks(&count);
213 if (!ids) {
214 qCWarning(JoystickSDLLog) << "SDL_GetJoysticks failed:" << SDL_GetError();
215 return current;
216 }
217
218 qCDebug(JoystickSDLLog) << "SDL_GetJoysticks returned" << count << "joysticks";
219 for (int n = 0; n < count; ++n) {
220 const QString joystickName = SDLJoystick::getNameForInstanceId(ids[n]);
221 qCDebug(JoystickSDLLog) << " [" << n << "] ID:" << ids[n]
222 << "Name:" << joystickName
223 << "IsGamepad:" << SDL_IsGamepad(ids[n]);
224 }
225
226 for (int n = 0; n < count; ++n) {
227 const SDL_JoystickID jid = ids[n];
228 QString baseName = SDLJoystick::getNameForInstanceId(jid);
229 if (baseName.isEmpty()) {
230 baseName = QStringLiteral("Joystick %1").arg(jid);
231 }
232 QString name = baseName;
233
234 // Check cache by instance ID (reconnection of same device)
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) {
240 name = it.key();
241 current[name] = cachedJs;
242 previous.erase(it);
243 foundInCache = true;
244 } else {
245 // SDL instance ids can be recycled. If the id matches but the reported
246 // name changed, treat it as a new device and drop the stale cached object.
247 cachedJs->deleteLater();
248 previous.erase(it);
249 }
250 break;
251 }
252 }
253 if (foundInCache) {
254 continue;
255 }
256
257 // Check cache by name (for joysticks that were disconnected and reconnected)
258 if (previous.contains(name) && !current.contains(name)) {
259 current[name] = previous[name];
260 auto *js = static_cast<JoystickSDL*>(current[name]);
261 js->setInstanceId(jid);
262 (void) previous.remove(name);
263 continue;
264 }
265
266 // Handle duplicate names by appending a number
267 int duplicateIndex = 2;
268 while (current.contains(name) || previous.contains(name)) {
269 name = QStringLiteral("%1 #%2").arg(baseName).arg(duplicateIndex++);
270 }
271
272 QList<int> gamepadAxes;
273 QSet<int> joyAxesMappedToGamepad;
274
275 if (SDL_IsGamepad(jid)) {
276 auto tmpGamepad = SDL_OpenGamepad(jid);
277 if (!tmpGamepad) {
278 qCWarning(JoystickSDLLog) << "Failed to open gamepad" << jid << SDL_GetError();
279 continue;
280 }
281
282 // Determine if this gamepad axis is one we should show to the user
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);
286 }
287 }
288
289 // If a sdlJoystick axis is mapped to a sdlGamepad axis, then the axis is represented
290 // by both the sdlJoystick interface and the sdlGamepad interface. If this is the case,
291 // We'll only show the sdlGamepad interface version of the axis to the user.
292 int bindingCount = 0;
293 SDL_GamepadBinding **bindings = SDL_GetGamepadBindings(tmpGamepad, &bindingCount);
294 if (bindings) {
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);
299 }
300 }
301 SDL_free(bindings);
302 } else {
303 qCWarning(JoystickSDLLog) << "Failed to get bindings for" << name << "error:" << SDL_GetError();
304 }
305
306 SDL_CloseGamepad(tmpGamepad);
307 }
308
309 SDL_Joystick *tmpJoy = SDL_OpenJoystick(jid);
310 if (!tmpJoy) {
311 qCWarning(JoystickSDLLog) << "Failed to open joystick" << jid << SDL_GetError();
312 continue;
313 }
314
315 QList<int> nonGamepadAxes;
316 const int axisCount = SDL_GetNumJoystickAxes(tmpJoy);
317 for (int i = 0; i < axisCount; i++) {
318 if (!joyAxesMappedToGamepad.contains(i)) {
319 nonGamepadAxes.append(i);
320 }
321 }
322
323 const int buttonCount = SDL_GetNumJoystickButtons(tmpJoy);
324 const int hatCount = SDL_GetNumJoystickHats(tmpJoy);
325 SDL_CloseJoystick(tmpJoy);
326
327 qCDebug(JoystickSDLLog) << "Creating JoystickSDL for" << name << "jid:" << jid;
328
329 current[name] = new JoystickSDL(name,
330 gamepadAxes,
331 nonGamepadAxes,
332 qMax(0, buttonCount),
333 qMax(0, hatCount),
334 jid);
335 }
336
337 SDL_free(ids);
338
339 qCDebug(JoystickSDLLog) << "Discovered" << current.size() << "joysticks:";
340 for (auto it = current.begin(); it != current.end(); ++it) {
341 auto *js = static_cast<JoystickSDL*>(it.value());
342 qCDebug(JoystickSDLLog) << " " << it.key() << "instanceId:" << js->instanceId();
343 }
344
345 for (auto* joystick : std::as_const(previous)) {
346 joystick->deleteLater();
347 }
348
349 const QMutexLocker cacheLocker(&s_discoveryCacheMutex);
350 s_discoveryCache = current;
351 return current;
352}
353
354//-----------------------------------------------------------------------------
355// Joystick Interface Overrides
356//-----------------------------------------------------------------------------
357
358bool JoystickSDL::_open()
359{
360 if (isGamepad()) {
361 _sdlGamepad = SDL_OpenGamepad(_instanceId);
362 if (!_sdlGamepad) {
363 qCWarning(JoystickSDLLog) << "SDL_OpenGamepad failed:" << SDL_GetError();
364 return false;
365 }
366 _sdlJoystick = SDL_GetGamepadJoystick(_sdlGamepad);
367 } else {
368 _sdlJoystick = SDL_OpenJoystick(_instanceId);
369 }
370
371 if (!_sdlJoystick) {
372 qCWarning(JoystickSDLLog) << "SDL_JoystickOpen failed:" << SDL_GetError();
373 return false;
374 }
375
376 qCDebug(JoystickSDLLog) << "Opened" << SDL_GetJoystickName(_sdlJoystick) << "joystick at" << _sdlJoystick;
377
378 return true;
379}
380
381void JoystickSDL::_close()
382{
383 if (!_sdlJoystick) {
384 qCWarning(JoystickSDLLog) << "Attempt to close null joystick!";
385 return;
386 }
387
388 qCDebug(JoystickSDLLog) << "Closing joystick" << _name << "at" << _sdlJoystick;
389
390 if (_sdlHaptic) {
391 SDL_CloseHaptic(_sdlHaptic);
392 _sdlHaptic = nullptr;
393 }
394
395 if (_sdlGamepad) {
396 SDL_CloseGamepad(_sdlGamepad);
397 } else {
398 SDL_CloseJoystick(_sdlJoystick);
399 }
400
401 _sdlJoystick = nullptr;
402 _sdlGamepad = nullptr;
403}
404
405bool JoystickSDL::_update()
406{
407 if (!_sdlJoystick || !SDL_JoystickConnected(_sdlJoystick)) {
408 qCWarning(JoystickSDLLog) << "Joystick disconnected during update:" << _name;
409 return false;
410 }
411
412 if (_sdlGamepad) {
413 SDL_UpdateGamepads();
414 } else {
415 SDL_UpdateJoysticks();
416 }
417
418 return true;
419}
420
421//-----------------------------------------------------------------------------
422// Input State Accessors
423//-----------------------------------------------------------------------------
424
425bool JoystickSDL::_getButton(int idx) const
426{
427 // First try the standardized gamepad set if idx is inside that set
428 if (_sdlGamepad && (idx >= 0) && (idx < SDL_GAMEPAD_BUTTON_COUNT)) {
429 return SDL_GetGamepadButton(_sdlGamepad, static_cast<SDL_GamepadButton>(idx));
430 }
431
432 // Fall back to raw joystick buttons (covers unmapped/extras)
433 if (_sdlJoystick && (idx >= 0) && (idx < SDL_GetNumJoystickButtons(_sdlJoystick))) {
434 return SDL_GetJoystickButton(_sdlJoystick, idx);
435 }
436
437 return false;
438}
439
440int JoystickSDL::_getAxisValue(int idx) const
441{
442 if (idx < 0) {
443 return 0;
444 }
445
446#ifdef TEST_WITH_VIRTUAL_AXES
447 // Handle virtual axes (last 2 axes)
448 const int totalPhysicalAxes = _gamepadAxes.length() + _nonGamepadAxes.length();
449 if (idx >= totalPhysicalAxes && idx < totalPhysicalAxes + 2) {
450 // Check if button 0 is pressed
451 bool button0Down = false;
452 if (_sdlGamepad) {
453 button0Down = SDL_GetGamepadButton(_sdlGamepad, static_cast<SDL_GamepadButton>(0));
454 } else if (_sdlJoystick) {
455 button0Down = SDL_GetJoystickButton(_sdlJoystick, 0);
456 }
457
458 if (button0Down) {
459 // When button 0 is down, return values from axis 0 and 1
460 const int virtualAxisIdx = idx - totalPhysicalAxes;
461 if (virtualAxisIdx == 0) {
462 // First virtual axis maps to axis 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);
467 }
468 } else {
469 // Second virtual axis maps to axis 1
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);
474 }
475 }
476 } else {
477 // When button 0 is up, return centered values
478 return 0;
479 }
480 }
481#endif
482
483 if (_sdlGamepad) {
484 if (idx < _gamepadAxes.length()) {
485 return SDL_GetGamepadAxis(_sdlGamepad, static_cast<SDL_GamepadAxis>(_gamepadAxes[idx]));
486 }
487 const int nonGamepadIdx = idx - static_cast<int>(_gamepadAxes.length());
488 if (nonGamepadIdx < _nonGamepadAxes.length()) {
489 return SDL_GetJoystickAxis(_sdlJoystick, _nonGamepadAxes[nonGamepadIdx]);
490 }
491 return 0;
492 }
493
494 return SDL_GetJoystickAxis(_sdlJoystick, idx);
495}
496
497bool JoystickSDL::_getHat(int hat, int idx) const
498{
499 static constexpr std::array<uint8_t, 4> hatButtons = {SDL_HAT_UP, SDL_HAT_DOWN, SDL_HAT_LEFT, SDL_HAT_RIGHT};
500
501 if (idx < 0 || static_cast<size_t>(idx) >= hatButtons.size()) {
502 return false;
503 }
504
505 return ((SDL_GetJoystickHat(_sdlJoystick, hat) & hatButtons[idx]) != 0);
506}
507
508//-----------------------------------------------------------------------------
509// Haptic and LED
510//-----------------------------------------------------------------------------
511
513{
514 const quint64 props = _getProperties();
515 return props != 0 && SDL_GetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, false);
516}
517
519{
520 const quint64 props = _getProperties();
521 return props != 0 && SDL_GetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, false);
522}
523
525{
526 const quint64 props = _getProperties();
527 if (props == 0) {
528 return false;
529 }
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);
532}
533
534void JoystickSDL::rumble(quint16 lowFreq, quint16 highFreq, quint32 durationMs)
535{
536 if (_sdlGamepad) {
537 if (!SDL_RumbleGamepad(_sdlGamepad, lowFreq, highFreq, durationMs)) {
538 qCDebug(JoystickSDLLog) << "Rumble failed:" << SDL_GetError();
539 }
540 } else if (_sdlJoystick) {
541 if (!SDL_RumbleJoystick(_sdlJoystick, lowFreq, highFreq, durationMs)) {
542 qCDebug(JoystickSDLLog) << "Rumble failed:" << SDL_GetError();
543 }
544 }
545}
546
547void JoystickSDL::rumbleTriggers(quint16 left, quint16 right, quint32 durationMs)
548{
549 if (_sdlGamepad) {
550 if (!SDL_RumbleGamepadTriggers(_sdlGamepad, left, right, durationMs)) {
551 qCDebug(JoystickSDLLog) << "Trigger rumble failed:" << SDL_GetError();
552 }
553 }
554}
555
556void JoystickSDL::setLED(quint8 red, quint8 green, quint8 blue)
557{
558 if (_sdlGamepad) {
559 if (!SDL_SetGamepadLED(_sdlGamepad, red, green, blue)) {
560 qCDebug(JoystickSDLLog) << "Set LED failed:" << SDL_GetError();
561 }
562 } else if (_sdlJoystick) {
563 if (!SDL_SetJoystickLED(_sdlJoystick, red, green, blue)) {
564 qCDebug(JoystickSDLLog) << "Set LED failed:" << SDL_GetError();
565 }
566 }
567}
568
569bool JoystickSDL::sendEffect(const QByteArray &data)
570{
571 if (_sdlGamepad && !data.isEmpty()) {
572 if (!SDL_SendGamepadEffect(_sdlGamepad, data.constData(), static_cast<int>(data.size()))) {
573 qCDebug(JoystickSDLLog) << "sendEffect failed:" << SDL_GetError();
574 return false;
575 }
576 return true;
577 }
578 return false;
579}
580
581//-----------------------------------------------------------------------------
582// Device Identity
583//-----------------------------------------------------------------------------
584
585QString JoystickSDL::guid() const
586{
587 if (_sdlJoystick) {
588 SDL_GUID sdlGuid = SDL_GetJoystickGUID(_sdlJoystick);
589 char guidStr[33];
590 SDL_GUIDToString(sdlGuid, guidStr, sizeof(guidStr));
591 return QString::fromLatin1(guidStr);
592 }
593 return QString();
594}
595
597{
598 if (_sdlJoystick) {
599 return SDL_GetJoystickVendor(_sdlJoystick);
600 }
601 return 0;
602}
603
605{
606 if (_sdlJoystick) {
607 return SDL_GetJoystickProduct(_sdlJoystick);
608 }
609 return 0;
610}
611
612QString JoystickSDL::serial() const
613{
614 if (_sdlJoystick) {
615 const char *serialStr = SDL_GetJoystickSerial(_sdlJoystick);
616 if (serialStr) {
617 return QString::fromUtf8(serialStr);
618 }
619 }
620 return QString();
621}
622
624{
625 if (_sdlJoystick) {
626 SDL_JoystickType type = SDL_GetJoystickType(_sdlJoystick);
627 switch (type) {
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");
646 default:
647 return QStringLiteral("Unknown");
648 }
649 }
650 return QString();
651}
652
653QString JoystickSDL::path() const
654{
655 if (_sdlJoystick) {
656 const char *devicePath = SDL_GetJoystickPath(_sdlJoystick);
657 if (devicePath) {
658 return QString::fromUtf8(devicePath);
659 }
660 }
661 return QString();
662}
663
665{
666 return SDL_IsJoystickVirtual(_instanceId);
667}
668
670{
671 if (_sdlJoystick) {
672 return SDL_GetJoystickFirmwareVersion(_sdlJoystick);
673 }
674 return 0;
675}
676
678{
679 if (_sdlGamepad) {
680 return SDLJoystick::connectionStateToString(SDL_GetGamepadConnectionState(_sdlGamepad));
681 }
682 if (_sdlJoystick) {
683 return SDLJoystick::connectionStateToString(SDL_GetJoystickConnectionState(_sdlJoystick));
684 }
685 return QString();
686}
687
688//-----------------------------------------------------------------------------
689// Player Info
690//-----------------------------------------------------------------------------
691
693{
694 if (_sdlGamepad) {
695 return SDL_GetGamepadPlayerIndex(_sdlGamepad);
696 }
697 if (_sdlJoystick) {
698 return SDL_GetJoystickPlayerIndex(_sdlJoystick);
699 }
700 return -1;
701}
702
704{
705 bool success = false;
706 if (_sdlGamepad) {
707 success = SDL_SetGamepadPlayerIndex(_sdlGamepad, index);
708 } else if (_sdlJoystick) {
709 success = SDL_SetJoystickPlayerIndex(_sdlJoystick, index);
710 }
711
712 if (success) {
713 emit playerIndexChanged();
714 } else {
715 qCDebug(JoystickSDLLog) << "Failed to set player index:" << SDL_GetError();
716 }
717}
718
719//-----------------------------------------------------------------------------
720// Power & Battery Status
721//-----------------------------------------------------------------------------
722
724{
725 if (_sdlJoystick) {
726 int percent = -1;
727 SDL_GetJoystickPowerInfo(_sdlJoystick, &percent);
728 return percent;
729 }
730 return -1;
731}
732
734{
735 if (!_sdlJoystick) {
736 return QString();
737 }
738
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");
752 default:
753 return QString();
754 }
755}
756
757//-----------------------------------------------------------------------------
758// Gamepad Type Detection
759//-----------------------------------------------------------------------------
760
762{
763 return SDL_IsGamepad(_instanceId);
764}
765
767{
768 if (_sdlGamepad) {
769 return SDLJoystick::gamepadTypeDisplayName(SDL_GetGamepadType(_sdlGamepad));
770 }
771 return QString();
772}
773
774//-----------------------------------------------------------------------------
775// Control Labels
776//-----------------------------------------------------------------------------
777
778QString JoystickSDL::axisLabel(int axis) const
779{
780 if (axis < 0) {
781 return tr("Axis %1").arg(axis);
782 }
783
784 // Check gamepad axes first
785 if (_sdlGamepad && axis < _gamepadAxes.length()) {
786 const char *label = SDL_GetGamepadStringForAxis(static_cast<SDL_GamepadAxis>(_gamepadAxes[axis]));
787 if (label) {
788 return QString::fromUtf8(label);
789 }
790 }
791
792 // Check non-gamepad axes
793 const int nonGamepadIdx = axis - _gamepadAxes.length();
794 if (nonGamepadIdx >= 0 && nonGamepadIdx < _nonGamepadAxes.length()) {
795 // Non-gamepad axes don't have standard labels, use raw joystick axis number
796 return tr("Axis %1").arg(_nonGamepadAxes[nonGamepadIdx]);
797 }
798
799 return tr("Axis %1").arg(axis);
800}
801
802QString JoystickSDL::buttonLabel(int button) const
803{
804 if (_sdlGamepad && button >= 0 && button < SDL_GAMEPAD_BUTTON_COUNT) {
805 const char *label = SDL_GetGamepadStringForButton(static_cast<SDL_GamepadButton>(button));
806 if (label) {
807 return QString::fromUtf8(label);
808 }
809 }
810 return tr("Button %1").arg(button);
811}
812
813//-----------------------------------------------------------------------------
814// Mapping Management
815//-----------------------------------------------------------------------------
816
818{
819 if (_sdlGamepad) {
820 char *mapping = SDL_GetGamepadMapping(_sdlGamepad);
821 if (mapping) {
822 QString result = QString::fromUtf8(mapping);
823 SDL_free(mapping);
824 return result;
825 }
826 }
827 return QString();
828}
829
830bool JoystickSDL::addMapping(const QString &mapping)
831{
832 if (mapping.isEmpty()) {
833 return false;
834 }
835
836 int result = SDL_AddGamepadMapping(qPrintable(mapping));
837 if (result == -1) {
838 qCWarning(JoystickSDLLog) << "Failed to add gamepad mapping:" << SDL_GetError();
839 return false;
840 }
841
842 qCDebug(JoystickSDLLog) << "Added gamepad mapping, result:" << result;
843 return true;
844}
845
846QVariantMap JoystickSDL::getAxisBinding(int axis) const
847{
848 QVariantMap result;
849 result[QStringLiteral("valid")] = false;
850
851 if (axis < 0) {
852 return result;
853 }
854
855 // Gamepad axes have bindings
856 if (_sdlGamepad && axis < _gamepadAxes.length()) {
857 const SDL_GamepadAxis gamepadAxis = static_cast<SDL_GamepadAxis>(_gamepadAxes[axis]);
858 return SDLJoystick::findBinding(_sdlGamepad, [gamepadAxis](const SDL_GamepadBinding *binding) {
859 return binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS &&
860 binding->output.axis.axis == gamepadAxis;
861 });
862 }
863
864 // Non-gamepad axes map directly to joystick axes (no binding indirection)
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; // Indicates no gamepad mapping, direct joystick access
873 return result;
874 }
875
876 return result;
877}
878
879QVariantMap JoystickSDL::getButtonBinding(int button) const
880{
881 if (!_sdlGamepad || button < 0 || button >= SDL_GAMEPAD_BUTTON_COUNT) {
882 QVariantMap result;
883 result[QStringLiteral("valid")] = false;
884 return result;
885 }
886
887 const SDL_GamepadButton gamepadButton = static_cast<SDL_GamepadButton>(button);
888 return SDLJoystick::findBinding(_sdlGamepad, [gamepadButton](const SDL_GamepadBinding *binding) {
889 return binding->output_type == SDL_GAMEPAD_BINDTYPE_BUTTON &&
890 binding->output.button == gamepadButton;
891 });
892}
893
894//-----------------------------------------------------------------------------
895// Sensor Support
896//-----------------------------------------------------------------------------
897
899{
900 if (_sdlGamepad) {
901 return SDL_GamepadHasSensor(_sdlGamepad, SDL_SENSOR_GYRO);
902 }
903 return false;
904}
905
907{
908 if (_sdlGamepad) {
909 return SDL_GamepadHasSensor(_sdlGamepad, SDL_SENSOR_ACCEL);
910 }
911 return false;
912}
913
915{
916 if (_sdlGamepad && hasGyroscope()) {
917 if (!SDL_SetGamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_GYRO, enabled)) {
918 qCWarning(JoystickSDLLog) << "Failed to" << (enabled ? "enable" : "disable") << "gyroscope:" << SDL_GetError();
919 return false;
920 }
921 return true;
922 }
923 return false;
924}
925
927{
928 if (_sdlGamepad && hasAccelerometer()) {
929 if (!SDL_SetGamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_ACCEL, enabled)) {
930 qCWarning(JoystickSDLLog) << "Failed to" << (enabled ? "enable" : "disable") << "accelerometer:" << SDL_GetError();
931 return false;
932 }
933 return true;
934 }
935 return false;
936}
937
939{
940 // Use cached data from events if available (more efficient than polling)
941 if (_gyroDataCached) {
942 return _cachedGyroData;
943 }
944
945 if (!_sdlGamepad) {
946 return QVector3D();
947 }
948 std::array<float, 3> data = {0.0f, 0.0f, 0.0f};
949 if (!SDL_GetGamepadSensorData(_sdlGamepad, SDL_SENSOR_GYRO, data.data(), 3)) {
950 // Only log if sensor is supposed to be enabled - otherwise this is expected
951 if (SDL_GamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_GYRO)) {
952 qCDebug(JoystickSDLLog) << "Failed to get gyroscope data:" << SDL_GetError();
953 }
954 return QVector3D();
955 }
956 return QVector3D(data[0], data[1], data[2]);
957}
958
960{
961 // Use cached data from events if available (more efficient than polling)
962 if (_accelDataCached) {
963 return _cachedAccelData;
964 }
965
966 if (!_sdlGamepad) {
967 return QVector3D();
968 }
969 std::array<float, 3> data = {0.0f, 0.0f, 0.0f};
970 if (!SDL_GetGamepadSensorData(_sdlGamepad, SDL_SENSOR_ACCEL, data.data(), 3)) {
971 // Only log if sensor is supposed to be enabled - otherwise this is expected
972 if (SDL_GamepadSensorEnabled(_sdlGamepad, SDL_SENSOR_ACCEL)) {
973 qCDebug(JoystickSDLLog) << "Failed to get accelerometer data:" << SDL_GetError();
974 }
975 return QVector3D();
976 }
977 return QVector3D(data[0], data[1], data[2]);
978}
979
981{
982 if (_sdlGamepad) {
983 return SDL_GetGamepadSensorDataRate(_sdlGamepad, SDL_SENSOR_GYRO);
984 }
985 return 0.0f;
986}
987
989{
990 if (_sdlGamepad) {
991 return SDL_GetGamepadSensorDataRate(_sdlGamepad, SDL_SENSOR_ACCEL);
992 }
993 return 0.0f;
994}
995
996//-----------------------------------------------------------------------------
997// Touchpad Support
998//-----------------------------------------------------------------------------
999
1001{
1002 if (_sdlGamepad) {
1003 return SDL_GetNumGamepadTouchpads(_sdlGamepad);
1004 }
1005 return 0;
1006}
1007
1009{
1010 if (_sdlGamepad) {
1011 return SDL_GetNumGamepadTouchpadFingers(_sdlGamepad, touchpad);
1012 }
1013 return 0;
1014}
1015
1016QVariantMap JoystickSDL::getTouchpadFinger(int touchpad, int finger) const
1017{
1018 QVariantMap result;
1019 if (_sdlGamepad) {
1020 bool down = false;
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;
1028 return result;
1029 }
1030 }
1031 result[QStringLiteral("valid")] = false;
1032 return result;
1033}
1034
1035//-----------------------------------------------------------------------------
1036// Trackball Support
1037//-----------------------------------------------------------------------------
1038
1040{
1041 if (_sdlJoystick) {
1042 return SDL_GetNumJoystickBalls(_sdlJoystick);
1043 }
1044 return 0;
1045}
1046
1047QVariantMap JoystickSDL::getBall(int ball) const
1048{
1049 QVariantMap result;
1050 if (_sdlJoystick) {
1051 int dx = 0, dy = 0;
1052 if (SDL_GetJoystickBall(_sdlJoystick, ball, &dx, &dy)) {
1053 result[QStringLiteral("valid")] = true;
1054 result[QStringLiteral("dx")] = dx;
1055 result[QStringLiteral("dy")] = dy;
1056 return result;
1057 }
1058 }
1059 result[QStringLiteral("valid")] = false;
1060 return result;
1061}
1062
1063//-----------------------------------------------------------------------------
1064// Capability Queries
1065//-----------------------------------------------------------------------------
1066
1067bool JoystickSDL::hasButton(int button) const
1068{
1069 if (_sdlGamepad && button >= 0 && button < SDL_GAMEPAD_BUTTON_COUNT) {
1070 return SDL_GamepadHasButton(_sdlGamepad, static_cast<SDL_GamepadButton>(button));
1071 }
1072 if (_sdlJoystick && button >= 0 && button < SDL_GetNumJoystickButtons(_sdlJoystick)) {
1073 return true;
1074 }
1075 return false;
1076}
1077
1078bool JoystickSDL::hasAxis(int axis) const
1079{
1080 if (_sdlGamepad && axis >= 0 && axis < _gamepadAxes.length()) {
1081 return SDL_GamepadHasAxis(_sdlGamepad, static_cast<SDL_GamepadAxis>(_gamepadAxes[axis]));
1082 }
1083 if (_sdlJoystick) {
1084 const int totalAxes = _gamepadAxes.length() + _nonGamepadAxes.length()
1085#ifdef TEST_WITH_VIRTUAL_AXES
1086 + 2 // Add 2 virtual axes for testing
1087#endif
1088 ;
1089 return axis >= 0 && axis < totalAxes;
1090 }
1091 return false;
1092}
1093
1095{
1096 if (_sdlGamepad) {
1097 return SDLJoystick::gamepadTypeDisplayName(SDL_GetRealGamepadType(_sdlGamepad));
1098 }
1099 return QString();
1100}
1101
1102//-----------------------------------------------------------------------------
1103// Type-Specific Labels
1104//-----------------------------------------------------------------------------
1105
1106QString JoystickSDL::buttonLabelForType(int button) const
1107{
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));
1111 switch (label) {
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");
1128 default:
1129 break;
1130 }
1131 }
1132 return buttonLabel(button);
1133}
1134
1135//-----------------------------------------------------------------------------
1136// Haptic/Force Feedback Support
1137//-----------------------------------------------------------------------------
1138
1140{
1141 if (_sdlJoystick) {
1142 return SDL_IsJoystickHaptic(_sdlJoystick);
1143 }
1144 return false;
1145}
1146
1148{
1149 if (_sdlHaptic) {
1150 return SDL_GetMaxHapticEffects(_sdlHaptic);
1151 }
1152 return 0;
1153}
1154
1156{
1157 if (_sdlHaptic) {
1158 const Uint32 features = SDL_GetHapticFeatures(_sdlHaptic);
1159 return (features & SDL_HAPTIC_LEFTRIGHT) || (features & SDL_HAPTIC_SINE);
1160 }
1161 return false;
1162}
1163
1165{
1166 if (_sdlHaptic) {
1167 return true;
1168 }
1169
1170 if (!_sdlJoystick || !SDL_IsJoystickHaptic(_sdlJoystick)) {
1171 return false;
1172 }
1173
1174 _sdlHaptic = SDL_OpenHapticFromJoystick(_sdlJoystick);
1175 if (!_sdlHaptic) {
1176 qCWarning(JoystickSDLLog) << "Failed to open haptic device:" << SDL_GetError();
1177 return false;
1178 }
1179
1180 if (!SDL_InitHapticRumble(_sdlHaptic)) {
1181 qCWarning(JoystickSDLLog) << "Failed to init haptic rumble:" << SDL_GetError();
1182 SDL_CloseHaptic(_sdlHaptic);
1183 _sdlHaptic = nullptr;
1184 return false;
1185 }
1186
1187 qCDebug(JoystickSDLLog) << "Haptic rumble initialized";
1188 return true;
1189}
1190
1191bool JoystickSDL::hapticRumblePlay(float strength, quint32 durationMs)
1192{
1193 if (!_sdlHaptic) {
1194 if (!hapticRumbleInit()) {
1195 return false;
1196 }
1197 }
1198
1199 if (!SDL_PlayHapticRumble(_sdlHaptic, strength, durationMs)) {
1200 qCWarning(JoystickSDLLog) << "Failed to play haptic rumble:" << SDL_GetError();
1201 return false;
1202 }
1203 return true;
1204}
1205
1207{
1208 if (_sdlHaptic) {
1209 SDL_StopHapticRumble(_sdlHaptic);
1210 }
1211}
1212
1213//-----------------------------------------------------------------------------
1214// Mapping Utilities
1215//-----------------------------------------------------------------------------
1216
1217QString JoystickSDL::getMappingForGUID(const QString &guid) const
1218{
1219 if (guid.isEmpty()) {
1220 return QString();
1221 }
1222
1223 SDL_GUID sdlGuid = SDL_StringToGUID(qPrintable(guid));
1224 char *mapping = SDL_GetGamepadMappingForGUID(sdlGuid);
1225 if (mapping) {
1226 QString result = QString::fromUtf8(mapping);
1227 SDL_free(mapping);
1228 return result;
1229 }
1230 return QString();
1231}
1232
1233//-----------------------------------------------------------------------------
1234// Virtual Joystick Support
1235//-----------------------------------------------------------------------------
1236
1237bool JoystickSDL::setVirtualAxis(int axis, int value)
1238{
1239 if (!_checkVirtualJoystick("setVirtualAxis")) {
1240 return false;
1241 }
1242
1243 if (!SDL_SetJoystickVirtualAxis(_sdlJoystick, axis, static_cast<Sint16>(value))) {
1244 qCDebug(JoystickSDLLog) << "Failed to set virtual axis" << axis << ":" << SDL_GetError();
1245 return false;
1246 }
1247 return true;
1248}
1249
1250bool JoystickSDL::setVirtualButton(int button, bool down)
1251{
1252 if (!_checkVirtualJoystick("setVirtualButton")) {
1253 return false;
1254 }
1255
1256 if (!SDL_SetJoystickVirtualButton(_sdlJoystick, button, down)) {
1257 qCDebug(JoystickSDLLog) << "Failed to set virtual button" << button << ":" << SDL_GetError();
1258 return false;
1259 }
1260 return true;
1261}
1262
1263bool JoystickSDL::setVirtualHat(int hat, quint8 value)
1264{
1265 if (!_checkVirtualJoystick("setVirtualHat")) {
1266 return false;
1267 }
1268
1269 if (!SDL_SetJoystickVirtualHat(_sdlJoystick, hat, value)) {
1270 qCDebug(JoystickSDLLog) << "Failed to set virtual hat" << hat << ":" << SDL_GetError();
1271 return false;
1272 }
1273 return true;
1274}
1275
1276//-----------------------------------------------------------------------------
1277// Properties/Capability Detection
1278//-----------------------------------------------------------------------------
1279
1281{
1282 return _hasGamepadCapability(SDL_PROP_GAMEPAD_CAP_MONO_LED_BOOLEAN);
1283}
1284
1286{
1287 return _hasGamepadCapability(SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN);
1288}
1289
1291{
1292 return _hasGamepadCapability(SDL_PROP_GAMEPAD_CAP_PLAYER_LED_BOOLEAN);
1293}
1294
1295//-----------------------------------------------------------------------------
1296// Connection State
1297//-----------------------------------------------------------------------------
1298
1300{
1301 return connectionType();
1302}
1303
1304//-----------------------------------------------------------------------------
1305// Initial Axis State (for drift detection)
1306//-----------------------------------------------------------------------------
1307
1308QVariantMap JoystickSDL::getAxisInitialState(int axis) const
1309{
1310 QVariantMap result;
1311 result[QStringLiteral("valid")] = false;
1312 result[QStringLiteral("value")] = 0;
1313
1314 if (!_sdlJoystick || axis < 0) {
1315 return result;
1316 }
1317
1318 Sint16 initialValue = 0;
1319 if (SDL_GetJoystickAxisInitialState(_sdlJoystick, axis, &initialValue)) {
1320 result[QStringLiteral("valid")] = true;
1321 result[QStringLiteral("value")] = static_cast<int>(initialValue);
1322 }
1323 return result;
1324}
1325
1326//-----------------------------------------------------------------------------
1327// Per-Device Custom Mapping
1328//-----------------------------------------------------------------------------
1329
1330bool JoystickSDL::setMapping(const QString &mapping)
1331{
1332 if (!_sdlGamepad || mapping.isEmpty()) {
1333 return false;
1334 }
1335
1336 if (!SDL_SetGamepadMapping(SDL_GetJoystickID(_sdlJoystick), qPrintable(mapping))) {
1337 qCDebug(JoystickSDLLog) << "Failed to set gamepad mapping:" << SDL_GetError();
1338 return false;
1339 }
1340 return true;
1341}
1342
1343//-----------------------------------------------------------------------------
1344// Virtual Joystick Enhancements
1345//-----------------------------------------------------------------------------
1346
1347bool JoystickSDL::setVirtualBall(int ball, int dx, int dy)
1348{
1349 if (!_checkVirtualJoystick("setVirtualBall")) {
1350 return false;
1351 }
1352
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();
1355 return false;
1356 }
1357 return true;
1358}
1359
1360bool JoystickSDL::setVirtualTouchpad(int touchpad, int finger, bool down, float x, float y, float pressure)
1361{
1362 if (!_checkVirtualJoystick("setVirtualTouchpad")) {
1363 return false;
1364 }
1365
1366 // Validate and clamp touchpad coordinates to valid range [0.0, 1.0]
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);
1370
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;
1375 }
1376
1377 if (!SDL_SetJoystickVirtualTouchpad(_sdlJoystick, touchpad, finger, down, clampedX, clampedY, clampedPressure)) {
1378 qCDebug(JoystickSDLLog) << "Failed to set virtual touchpad" << touchpad << "finger" << finger << ":" << SDL_GetError();
1379 return false;
1380 }
1381 return true;
1382}
1383
1384bool JoystickSDL::sendVirtualSensorData(int sensorType, float x, float y, float z)
1385{
1386 if (!_checkVirtualJoystick("sendVirtualSensorData")) {
1387 return false;
1388 }
1389
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();
1393 return false;
1394 }
1395 return true;
1396}
1397
1398//-----------------------------------------------------------------------------
1399// Cached Sensor Data (Event-Driven Updates)
1400//-----------------------------------------------------------------------------
1401
1402void JoystickSDL::updateCachedGyroData(const QVector3D &data)
1403{
1404 _cachedGyroData = data;
1405 _gyroDataCached = true;
1406 emit gyroscopeDataUpdated(data);
1407}
1408
1409void JoystickSDL::updateCachedAccelData(const QVector3D &data)
1410{
1411 _cachedAccelData = data;
1412 _accelDataCached = true;
1413 emit accelerometerDataUpdated(data);
1414}
1415
1417{
1418 const QString currentState = connectionState();
1419 if (currentState != _lastConnectionState && !currentState.isEmpty()) {
1420 qCDebug(JoystickSDLLog) << "Connection state changed:" << _lastConnectionState << "->" << currentState;
1421 _lastConnectionState = currentState;
1422 emit connectionStateChanged(currentState);
1423 }
1424}
1425
1426QVariantList JoystickSDL::detectAxisDrift(int threshold) const
1427{
1428 QVariantList driftingAxes;
1429
1430 const int totalAxes = _gamepadAxes.length() + _nonGamepadAxes.length();
1431 for (int i = 0; i < totalAxes; ++i) {
1432 const int currentValue = _getAxisValue(i);
1433
1434 // Check if axis is significantly off-center (not near 0)
1435 // Threshold default of 8000 is ~25% of full range
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);
1443 }
1444 }
1445
1446 return driftingAxes;
1447}
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
Definition JoystickSDL.h:10
#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
~JoystickSDL() 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 bool init()
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
int instanceId() const
Definition JoystickSDL.h:32
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
QString name() const
Definition Joystick.h:206
Joystick(const QString &name, int axisCount, int buttonCount, int hatCount, QObject *parent=nullptr)
Definition Joystick.cc:77
QString _name
Definition Joystick.h:387
int axisCount() const
Definition Joystick.h:208
void playerIndexChanged()
void connectionStateChanged(const QString &newState)
int buttonCount() const
Definition Joystick.h:207
void accelerometerDataUpdated(const QVector3D &data)
void gyroscopeDataUpdated(const QVector3D &data)
RAII lock guard for joysticks.
Definition SDLJoystick.h:61
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).