Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/drivers/sdl/joypad_sdl.cpp
10277 views
1
/**************************************************************************/
2
/* joypad_sdl.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "joypad_sdl.h"
32
33
#ifdef SDL_ENABLED
34
35
#include "core/input/default_controller_mappings.h"
36
#include "core/os/time.h"
37
#include "core/variant/dictionary.h"
38
39
#include <iterator>
40
41
#include <SDL3/SDL.h>
42
#include <SDL3/SDL_error.h>
43
#include <SDL3/SDL_events.h>
44
#include <SDL3/SDL_gamepad.h>
45
#include <SDL3/SDL_iostream.h>
46
#include <SDL3/SDL_joystick.h>
47
48
JoypadSDL *JoypadSDL::singleton = nullptr;
49
50
// Macro to skip the SDL joystick event handling if the device is an SDL gamepad, because
51
// there are separate events for SDL gamepads
52
#define SKIP_EVENT_FOR_GAMEPAD \
53
if (SDL_IsGamepad(sdl_event.jdevice.which)) { \
54
continue; \
55
}
56
57
JoypadSDL::JoypadSDL() {
58
singleton = this;
59
}
60
61
#ifdef WINDOWS_ENABLED
62
extern "C" {
63
HWND SDL_HelperWindow;
64
}
65
66
// Required for DInput joypads to work
67
// TODO: remove this workaround when we update to newer version of SDL
68
JoypadSDL::JoypadSDL(HWND p_helper_window) :
69
JoypadSDL() {
70
SDL_HelperWindow = p_helper_window;
71
}
72
#endif
73
74
JoypadSDL::~JoypadSDL() {
75
// Process any remaining input events
76
process_events();
77
for (int i = 0; i < Input::JOYPADS_MAX; i++) {
78
if (joypads[i].attached) {
79
close_joypad(i);
80
}
81
}
82
SDL_Quit();
83
singleton = nullptr;
84
}
85
86
JoypadSDL *JoypadSDL::get_singleton() {
87
return singleton;
88
}
89
90
Error JoypadSDL::initialize() {
91
SDL_SetHint(SDL_HINT_JOYSTICK_THREAD, "1");
92
SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
93
ERR_FAIL_COND_V_MSG(!SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_GAMEPAD), FAILED, SDL_GetError());
94
95
// Add Godot's mapping database from memory
96
int i = 0;
97
while (DefaultControllerMappings::mappings[i]) {
98
String mapping_string = DefaultControllerMappings::mappings[i++];
99
CharString data = mapping_string.utf8();
100
SDL_IOStream *rw = SDL_IOFromMem((void *)data.ptr(), data.size());
101
SDL_AddGamepadMappingsFromIO(rw, 1);
102
}
103
104
// Make sure that we handle already connected joypads when the driver is initialized.
105
process_events();
106
107
print_verbose("SDL: Init OK!");
108
return OK;
109
}
110
111
void JoypadSDL::process_events() {
112
// Update rumble first for it to be applied when we handle SDL events
113
for (int i = 0; i < Input::JOYPADS_MAX; i++) {
114
Joypad &joy = joypads[i];
115
if (joy.attached && joy.supports_force_feedback) {
116
uint64_t timestamp = Input::get_singleton()->get_joy_vibration_timestamp(i);
117
118
// Update the joypad rumble only if there was a new vibration request
119
if (timestamp > joy.ff_effect_timestamp) {
120
joy.ff_effect_timestamp = timestamp;
121
122
SDL_Joystick *sdl_joy = SDL_GetJoystickFromID(joypads[i].sdl_instance_idx);
123
Vector2 strength = Input::get_singleton()->get_joy_vibration_strength(i);
124
125
// If the vibration was requested to start, SDL_RumbleJoystick will start it.
126
// If the vibration was requested to stop, strength and duration will be 0, so SDL will stop the rumble.
127
SDL_RumbleJoystick(
128
sdl_joy,
129
// Rumble strength goes from 0 to 0xFFFF
130
strength.x * UINT16_MAX,
131
strength.y * UINT16_MAX,
132
Input::get_singleton()->get_joy_vibration_duration(i) * 1000);
133
}
134
}
135
}
136
137
SDL_Event sdl_event;
138
while (SDL_PollEvent(&sdl_event)) {
139
// A new joypad was attached
140
if (sdl_event.type == SDL_EVENT_JOYSTICK_ADDED) {
141
int joy_id = Input::get_singleton()->get_unused_joy_id();
142
if (joy_id == -1) {
143
// There is no space for more joypads...
144
print_error("A new joypad was attached but couldn't allocate a new id for it because joypad limit was reached.");
145
} else {
146
SDL_Joystick *joy = nullptr;
147
SDL_Gamepad *gamepad = nullptr;
148
String device_name;
149
150
// Gamepads must be opened with SDL_OpenGamepad to get their special remapped events
151
if (SDL_IsGamepad(sdl_event.jdevice.which)) {
152
gamepad = SDL_OpenGamepad(sdl_event.jdevice.which);
153
154
ERR_CONTINUE_MSG(!gamepad,
155
vformat("Error opening gamepad at index %d: %s", sdl_event.jdevice.which, SDL_GetError()));
156
157
device_name = SDL_GetGamepadName(gamepad);
158
joy = SDL_GetGamepadJoystick(gamepad);
159
160
print_verbose(vformat("SDL: Gamepad %s connected", SDL_GetGamepadName(gamepad)));
161
} else {
162
joy = SDL_OpenJoystick(sdl_event.jdevice.which);
163
ERR_CONTINUE_MSG(!joy,
164
vformat("Error opening joystick at index %d: %s", sdl_event.jdevice.which, SDL_GetError()));
165
166
device_name = SDL_GetJoystickName(joy);
167
168
print_verbose(vformat("SDL: Joystick %s connected", SDL_GetJoystickName(joy)));
169
}
170
171
const int MAX_GUID_SIZE = 64;
172
char guid[MAX_GUID_SIZE] = {};
173
174
SDL_GUIDToString(SDL_GetJoystickGUID(joy), guid, MAX_GUID_SIZE);
175
SDL_PropertiesID propertiesID = SDL_GetJoystickProperties(joy);
176
177
joypads[joy_id].attached = true;
178
joypads[joy_id].sdl_instance_idx = sdl_event.jdevice.which;
179
joypads[joy_id].supports_force_feedback = SDL_GetBooleanProperty(propertiesID, SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, false);
180
joypads[joy_id].guid = StringName(String(guid));
181
182
sdl_instance_id_to_joypad_id.insert(sdl_event.jdevice.which, joy_id);
183
184
Dictionary joypad_info;
185
joypad_info["mapping_handled"] = true; // Skip Godot's mapping system because SDL already handles the joypad's mapping.
186
joypad_info["raw_name"] = String(SDL_GetJoystickName(joy));
187
joypad_info["vendor_id"] = itos(SDL_GetJoystickVendor(joy));
188
joypad_info["product_id"] = itos(SDL_GetJoystickProduct(joy));
189
190
const uint64_t steam_handle = SDL_GetGamepadSteamHandle(gamepad);
191
if (steam_handle != 0) {
192
joypad_info["steam_input_index"] = itos(steam_handle);
193
}
194
195
const int player_index = SDL_GetJoystickPlayerIndex(joy);
196
if (player_index >= 0) {
197
// For XInput controllers SDL_GetJoystickPlayerIndex returns the XInput user index.
198
joypad_info["xinput_index"] = itos(player_index);
199
}
200
201
Input::get_singleton()->joy_connection_changed(
202
joy_id,
203
true,
204
device_name,
205
joypads[joy_id].guid,
206
joypad_info);
207
}
208
// An event for an attached joypad
209
} else if (sdl_event.type >= SDL_EVENT_JOYSTICK_AXIS_MOTION && sdl_event.type < SDL_EVENT_FINGER_DOWN && sdl_instance_id_to_joypad_id.has(sdl_event.jdevice.which)) {
210
int joy_id = sdl_instance_id_to_joypad_id.get(sdl_event.jdevice.which);
211
212
switch (sdl_event.type) {
213
case SDL_EVENT_JOYSTICK_REMOVED:
214
Input::get_singleton()->joy_connection_changed(joy_id, false, "");
215
close_joypad(joy_id);
216
break;
217
218
case SDL_EVENT_JOYSTICK_AXIS_MOTION:
219
SKIP_EVENT_FOR_GAMEPAD;
220
221
Input::get_singleton()->joy_axis(
222
joy_id,
223
static_cast<JoyAxis>(sdl_event.jaxis.axis), // Godot joy axis constants are already intentionally the same as SDL's
224
((sdl_event.jaxis.value - SDL_JOYSTICK_AXIS_MIN) / (float)(SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN) - 0.5f) * 2.0f);
225
break;
226
227
case SDL_EVENT_JOYSTICK_BUTTON_UP:
228
case SDL_EVENT_JOYSTICK_BUTTON_DOWN:
229
SKIP_EVENT_FOR_GAMEPAD;
230
231
Input::get_singleton()->joy_button(
232
joy_id,
233
static_cast<JoyButton>(sdl_event.jbutton.button), // Godot button constants are intentionally the same as SDL's, so we can just straight up use them
234
sdl_event.jbutton.down);
235
break;
236
237
case SDL_EVENT_JOYSTICK_HAT_MOTION:
238
SKIP_EVENT_FOR_GAMEPAD;
239
240
Input::get_singleton()->joy_hat(
241
joy_id,
242
(HatMask)sdl_event.jhat.value // Godot hat masks are identical to SDL hat masks, so we can just use them as-is.
243
);
244
break;
245
246
case SDL_EVENT_GAMEPAD_AXIS_MOTION: {
247
float axis_value;
248
249
if (sdl_event.gaxis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER || sdl_event.gaxis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) {
250
// Gamepad triggers go from 0 to SDL_JOYSTICK_AXIS_MAX
251
axis_value = sdl_event.gaxis.value / (float)SDL_JOYSTICK_AXIS_MAX;
252
} else {
253
// Other axis go from SDL_JOYSTICK_AXIS_MIN to SDL_JOYSTICK_AXIS_MAX
254
axis_value =
255
((sdl_event.gaxis.value - SDL_JOYSTICK_AXIS_MIN) / (float)(SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN) - 0.5f) * 2.0f;
256
}
257
258
Input::get_singleton()->joy_axis(
259
joy_id,
260
static_cast<JoyAxis>(sdl_event.gaxis.axis), // Godot joy axis constants are already intentionally the same as SDL's
261
axis_value);
262
} break;
263
264
// Do note SDL gamepads do not have separate events for the dpad
265
case SDL_EVENT_GAMEPAD_BUTTON_UP:
266
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
267
Input::get_singleton()->joy_button(
268
joy_id,
269
static_cast<JoyButton>(sdl_event.gbutton.button), // Godot button constants are intentionally the same as SDL's, so we can just straight up use them
270
sdl_event.gbutton.down);
271
break;
272
}
273
}
274
}
275
}
276
277
void JoypadSDL::close_joypad(int p_pad_idx) {
278
int sdl_instance_idx = joypads[p_pad_idx].sdl_instance_idx;
279
280
joypads[p_pad_idx].attached = false;
281
sdl_instance_id_to_joypad_id.erase(sdl_instance_idx);
282
283
if (SDL_IsGamepad(sdl_instance_idx)) {
284
SDL_Gamepad *gamepad = SDL_GetGamepadFromID(sdl_instance_idx);
285
SDL_CloseGamepad(gamepad);
286
} else {
287
SDL_Joystick *joy = SDL_GetJoystickFromID(sdl_instance_idx);
288
SDL_CloseJoystick(joy);
289
}
290
}
291
292
#endif // SDL_ENABLED
293
294