2
\$\begingroup\$

Here's something that's been bugging me all day: Controller detection in SDL.

First thing is that it doesn't automatically detect when a controller is connected. Finding out when a controller is disconnected is no problem:

if(joystick.closed > 0) { SendEvent(E_CONTROLLER_DISCONNECTED); //cleanup }

I simply have a little loop to detect for new controllers:

SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
joysticks_.Clear();
joysticks_.Resize(SDL_NumJoysticks());

Which works but is very, very slow. Regardless if I have a controller plugged in or not, this step alone takes 10-20ms. Even spacing it apart every few seconds, there are obviously noticable lag spikes whenever I am doing the detection; even with another thread, the lag spikes are still there. However I have not found any better alternative.

This type of behavior is imperitive to proper operation. This is especially so since if a controller gets disconnected, it won't automatically re-open in SDL when I reconnected it. Is there any better way to do this?

Oh, and as another point to make, I don't want to use SDL Events. They do basically what I've listed above, but don't work well with my existing multithreaded approach.

\$\endgroup\$
3
  • \$\begingroup\$ Only allow controllers to be plugged in while in a menu? \$\endgroup\$ Commented Apr 14, 2014 at 8:29
  • \$\begingroup\$ Is upgrading to SDL 2.0 an option for you? The new version reportedly supports hot-plugging joysticks. \$\endgroup\$ Commented Apr 17, 2014 at 13:50
  • \$\begingroup\$ I'm running 2.0.1 atm. \$\endgroup\$
    – user39686
    Commented Apr 17, 2014 at 14:39

1 Answer 1

5
+100
\$\begingroup\$

There's only one clean way, and that's to use a SDL_Event regardless. I don't know how you are handling event so that it is inconvenient in your architecture, but have you considered Event Filters ?

Basically you register a callback that catches the events before they are pushed to the event queue. If the event is a SDL_JOYDEVICEADDED or SDL_JOYDEVICEREMOVED event, you can handle the joystick behavior there or warn some other thread and return 0 (do not push the event in the queue). Else you do nothing and return 1 (push the event in the queue). That way you can treat joystick event as soon as they are spawned, and you don't need to treat every event in the queue first.

For more specific answer, we need more specific details of your architecture.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I really just have to man it up and use events. I've been playing around with SDL2 all day, and I've come to realize that there's just no way around it. Thanks for the filter idea, though I ended up using something different. \$\endgroup\$
    – user39686
    Commented Apr 17, 2014 at 21:34

You must log in to answer this question.