3 Joystick::Joystick(QObject
*parent
, int joystickEventTimeout
, bool doAutoRepeat
, int repeatDelay
)
6 if ( SDL_WasInit(SDL_INIT_JOYSTICK
) ) {
8 for (i
= 0; i
< SDL_NumJoysticks(); i
++)
9 joystickNames
.append(SDL_JoystickName(i
));
10 connect(&joystickTimer
, SIGNAL(timeout()), this, SLOT(processEvents()));
12 fprintf(stderr
, "ERROR: couldn't initialize SDL joystick support\n");
16 numAxes
= numButtons
= numHats
= numTrackballs
= 0;
17 autoRepeat
= doAutoRepeat
;
18 autoRepeatDelay
= repeatDelay
;
19 eventTimeout
= joystickEventTimeout
;
28 bool Joystick::open(int stick
)
33 joystick
= SDL_JoystickOpen(stick
);
35 numAxes
= SDL_JoystickNumAxes(joystick
);
36 numButtons
= SDL_JoystickNumButtons(joystick
);
37 numHats
= SDL_JoystickNumHats(joystick
);
38 numTrackballs
= SDL_JoystickNumBalls(joystick
);
39 joystickTimer
.start(eventTimeout
);
42 fprintf(stderr
, "ERROR: couldn't open SDL joystick #%d", stick
);
47 void Joystick::close()
51 SDL_JoystickClose(joystick
);
53 numAxes
= numButtons
= numHats
= numTrackballs
= 0;
56 void Joystick::processEvents()
64 for (i
= 0; i
< numAxes
; i
++) {
65 Sint16 moved
= SDL_JoystickGetAxis(joystick
, i
);
66 if ( abs(moved
) >= deadzones
[i
] ) {
67 if ( (moved
!= axes
[i
]) ) {
68 int deltaMoved
= abs(axes
[i
] - moved
);
69 if ( deltaMoved
>= sensitivities
[i
] )
70 emit
axisValueChanged(i
, moved
);
72 axisRepeatTimers
[i
].restart();
73 } else if (autoRepeat
&& moved
!= 0) {
74 if ( axisRepeatTimers
[i
].elapsed() >= autoRepeatDelay
) {
75 emit
axisValueChanged(i
, moved
);
79 axisRepeatTimers
[i
].restart();
81 emit
axisValueChanged(i
, 0);
83 for (i
= 0; i
< numButtons
; i
++) {
84 Uint8 changed
= SDL_JoystickGetButton(joystick
, i
);
85 if ( (changed
!= buttons
[i
]) ) {
86 emit
buttonValueChanged(i
, (bool) changed
);
88 buttonRepeatTimers
[i
].restart();
89 } else if (autoRepeat
&& changed
!= 0) {
90 if ( buttonRepeatTimers
[i
].elapsed() >= autoRepeatDelay
) {
91 emit
buttonValueChanged(i
, (bool) changed
);
95 buttonRepeatTimers
[i
].restart();
97 for (i
= 0; i
< numHats
; i
++) {
98 Uint8 changed
= SDL_JoystickGetHat(joystick
, i
);
99 if ( (changed
!= hats
[i
]) ) {
100 emit
hatValueChanged(i
, changed
);
102 hatRepeatTimers
[i
].restart();
103 } else if (autoRepeat
&& changed
!= 0) {
104 if ( hatRepeatTimers
[i
].elapsed() >= autoRepeatDelay
) {
105 emit
hatValueChanged(i
, changed
);
109 hatRepeatTimers
[i
].restart();
112 for (i
= 0; i
< numTrackballs
; i
++) {
114 SDL_JoystickGetBall(joystick
, i
, &dx
, &dy
);
115 if ( dx
!= 0 || dy
!= 0 )
116 emit
trackballValueChanged(i
, dx
, dy
);
120 int Joystick::getAxisValue(int axis
)
123 SDL_JoystickUpdate();
124 return SDL_JoystickGetAxis(joystick
, axis
);