Add workarounds for some SDL joystick index issues

This commit is contained in:
Cameron Gutman 2023-10-18 00:42:59 -05:00
parent cf615ea88d
commit 948b9c818a
2 changed files with 27 additions and 3 deletions

View file

@ -191,7 +191,17 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
case SDL_CONTROLLERDEVICEADDED:
SDL_GameController* gc = SDL_GameControllerOpen(event.cdevice.which);
if (gc != nullptr) {
m_Gamepads.append(gc);
// SDL_CONTROLLERDEVICEADDED can be reported multiple times for the same
// gamepad in rare cases, because SDL doesn't fixup the device index in
// the SDL_CONTROLLERDEVICEADDED event if an unopened gamepad disappears
// before we've processed the add event.
if (!m_Gamepads.contains(gc)) {
m_Gamepads.append(gc);
}
else {
// We already have this game controller open
SDL_GameControllerClose(gc);
}
}
break;
}

View file

@ -46,8 +46,8 @@ SdlInputHandler::findStateForGamepad(SDL_JoystickID id)
}
}
// This should only happen with too many gamepads
SDL_assert(SDL_NumJoysticks() > MAX_GAMEPADS);
// We can get a spurious removal event if the device is removed
// before or during SDL_GameControllerOpen(). This is fine to ignore.
return nullptr;
}
@ -466,6 +466,20 @@ void SdlInputHandler::handleControllerDeviceEvent(SDL_ControllerDeviceEvent* eve
return;
}
// SDL_CONTROLLERDEVICEADDED can be reported multiple times for the same
// gamepad in rare cases, because SDL doesn't fixup the device index in
// the SDL_CONTROLLERDEVICEADDED event if an unopened gamepad disappears
// before we've processed the add event.
for (int i = 0; i < MAX_GAMEPADS; i++) {
if (m_GamepadState[i].controller == controller) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Received duplicate add event for controller index: %d",
event->which);
SDL_GameControllerClose(controller);
return;
}
}
// We used to use SDL_GameControllerGetPlayerIndex() here but that
// can lead to strange issues due to bugs in Windows where an Xbox
// controller will join as player 2, even though no player 1 controller