all repos — mgba @ d2bf16b8723f69224cdeaa20699c61144df66a66

mGBA Game Boy Advance Emulator

src/platform/sdl/sdl-events.c (view raw)

  1/* Copyright (c) 2013-2014 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "sdl-events.h"
  7
  8#include <mgba/core/core.h>
  9#include <mgba/core/input.h>
 10#include <mgba/core/serialize.h>
 11#include <mgba/core/thread.h>
 12#include <mgba/internal/debugger/debugger.h>
 13#include <mgba/internal/gba/input.h>
 14#include <mgba-util/configuration.h>
 15#include <mgba-util/formatting.h>
 16#include <mgba-util/vfs.h>
 17
 18#if SDL_VERSION_ATLEAST(2, 0, 0) && defined(__APPLE__)
 19#define GUI_MOD KMOD_GUI
 20#else
 21#define GUI_MOD KMOD_CTRL
 22#endif
 23
 24#define GYRO_STEPS 100
 25#define RUMBLE_PWM 16
 26#define RUMBLE_STEPS 2
 27
 28mLOG_DEFINE_CATEGORY(SDL_EVENTS, "SDL Events");
 29
 30DEFINE_VECTOR(SDL_JoystickList, struct SDL_JoystickCombo);
 31
 32#if SDL_VERSION_ATLEAST(2, 0, 0)
 33static void _mSDLSetRumble(struct mRumble* rumble, int enable);
 34#endif
 35static int32_t _mSDLReadTiltX(struct mRotationSource* rumble);
 36static int32_t _mSDLReadTiltY(struct mRotationSource* rumble);
 37static int32_t _mSDLReadGyroZ(struct mRotationSource* rumble);
 38static void _mSDLRotationSample(struct mRotationSource* source);
 39
 40bool mSDLInitEvents(struct mSDLEvents* context) {
 41#if SDL_VERSION_ATLEAST(2, 0, 4)
 42	SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
 43#endif
 44	if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
 45		mLOG(SDL_EVENTS, ERROR, "SDL joystick initialization failed: %s", SDL_GetError());
 46	}
 47
 48#if SDL_VERSION_ATLEAST(2, 0, 0)
 49	SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
 50	if (SDL_InitSubSystem(SDL_INIT_HAPTIC) < 0) {
 51		mLOG(SDL_EVENTS, ERROR, "SDL haptic initialization failed: %s", SDL_GetError());
 52	}
 53	if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
 54		mLOG(SDL_EVENTS, ERROR, "SDL video initialization failed: %s", SDL_GetError());
 55	}
 56#endif
 57
 58	SDL_JoystickEventState(SDL_ENABLE);
 59	int nJoysticks = SDL_NumJoysticks();
 60	SDL_JoystickListInit(&context->joysticks, nJoysticks);
 61	if (nJoysticks > 0) {
 62		mSDLUpdateJoysticks(context, NULL);
 63		// Some OSes don't do hotplug detection
 64		if (!SDL_JoystickListSize(&context->joysticks)) {
 65			int i;
 66			for (i = 0; i < nJoysticks; ++i) {
 67				struct SDL_JoystickCombo* joystick = SDL_JoystickListAppend(&context->joysticks);
 68				joystick->joystick = SDL_JoystickOpen(i);
 69				joystick->index = SDL_JoystickListSize(&context->joysticks) - 1;
 70#if SDL_VERSION_ATLEAST(2, 0, 0)
 71				joystick->id = SDL_JoystickInstanceID(joystick->joystick);
 72				joystick->haptic = SDL_HapticOpenFromJoystick(joystick->joystick);
 73#else
 74				joystick->id = SDL_JoystickIndex(joystick->joystick);
 75#endif
 76			}
 77		}
 78	}
 79
 80	context->playersAttached = 0;
 81
 82	size_t i;
 83	for (i = 0; i < MAX_PLAYERS; ++i) {
 84		context->preferredJoysticks[i] = 0;
 85	}
 86
 87#if !SDL_VERSION_ATLEAST(2, 0, 0)
 88	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
 89#else
 90	context->screensaverSuspendDepth = 0;
 91#endif
 92	return true;
 93}
 94
 95void mSDLDeinitEvents(struct mSDLEvents* context) {
 96	size_t i;
 97	for (i = 0; i < SDL_JoystickListSize(&context->joysticks); ++i) {
 98		struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&context->joysticks, i);
 99#if SDL_VERSION_ATLEAST(2, 0, 0)
100		SDL_HapticClose(joystick->haptic);
101#endif
102		SDL_JoystickClose(joystick->joystick);
103	}
104	SDL_JoystickListDeinit(&context->joysticks);
105	SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
106}
107
108void mSDLEventsLoadConfig(struct mSDLEvents* context, const struct Configuration* config) {
109	context->preferredJoysticks[0] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 0);
110	context->preferredJoysticks[1] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 1);
111	context->preferredJoysticks[2] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 2);
112	context->preferredJoysticks[3] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 3);
113}
114
115void mSDLInitBindingsGBA(struct mInputMap* inputMap) {
116#ifdef BUILD_PANDORA
117	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_PAGEDOWN, GBA_KEY_A);
118	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_END, GBA_KEY_B);
119	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RSHIFT, GBA_KEY_L);
120	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RCTRL, GBA_KEY_R);
121	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LALT, GBA_KEY_START);
122	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LCTRL, GBA_KEY_SELECT);
123	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_UP, GBA_KEY_UP);
124	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_DOWN, GBA_KEY_DOWN);
125	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LEFT, GBA_KEY_LEFT);
126	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RIGHT, GBA_KEY_RIGHT);
127#else
128	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_x, GBA_KEY_A);
129	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_z, GBA_KEY_B);
130	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_a, GBA_KEY_L);
131	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_s, GBA_KEY_R);
132	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RETURN, GBA_KEY_START);
133	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_BACKSPACE, GBA_KEY_SELECT);
134	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_UP, GBA_KEY_UP);
135	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_DOWN, GBA_KEY_DOWN);
136	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LEFT, GBA_KEY_LEFT);
137	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RIGHT, GBA_KEY_RIGHT);
138#endif
139
140	struct mInputAxis description = { GBA_KEY_RIGHT, GBA_KEY_LEFT, 0x4000, -0x4000 };
141	mInputBindAxis(inputMap, SDL_BINDING_BUTTON, 0, &description);
142	description = (struct mInputAxis) { GBA_KEY_DOWN, GBA_KEY_UP, 0x4000, -0x4000 };
143	mInputBindAxis(inputMap, SDL_BINDING_BUTTON, 1, &description);
144
145	mInputBindHat(inputMap, SDL_BINDING_BUTTON, 0, &GBAInputInfo.hat);
146}
147
148bool mSDLAttachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
149	player->joystick = 0;
150
151	if (events->playersAttached >= MAX_PLAYERS) {
152		return false;
153	}
154
155#if SDL_VERSION_ATLEAST(2, 0, 0)
156	player->rumble.d.setRumble = _mSDLSetRumble;
157	CircleBufferInit(&player->rumble.history, RUMBLE_PWM);
158	player->rumble.level = 0;
159	player->rumble.activeLevel = 0;
160	player->rumble.p = player;
161#endif
162
163	player->rotation.d.readTiltX = _mSDLReadTiltX;
164	player->rotation.d.readTiltY = _mSDLReadTiltY;
165	player->rotation.d.readGyroZ = _mSDLReadGyroZ;
166	player->rotation.d.sample = _mSDLRotationSample;
167	player->rotation.axisX = 2;
168	player->rotation.axisY = 3;
169	player->rotation.gyroSensitivity = 2.2e9f;
170	player->rotation.gyroX = 0;
171	player->rotation.gyroY = 1;
172	player->rotation.zDelta = 0;
173	CircleBufferInit(&player->rotation.zHistory, sizeof(float) * GYRO_STEPS);
174	player->rotation.p = player;
175
176	player->playerId = events->playersAttached;
177	events->players[player->playerId] = player;
178	size_t firstUnclaimed = SIZE_MAX;
179	size_t index = SIZE_MAX;
180
181	size_t i;
182	for (i = 0; i < SDL_JoystickListSize(&events->joysticks); ++i) {
183		bool claimed = false;
184
185		int p;
186		for (p = 0; p < events->playersAttached; ++p) {
187			if (events->players[p]->joystick == SDL_JoystickListGetPointer(&events->joysticks, i)) {
188				claimed = true;
189				break;
190			}
191		}
192		if (claimed) {
193			continue;
194		}
195
196		if (firstUnclaimed == SIZE_MAX) {
197			firstUnclaimed = i;
198		}
199
200		const char* joystickName;
201#if SDL_VERSION_ATLEAST(2, 0, 0)
202		joystickName = SDL_JoystickName(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick);
203#else
204		joystickName = SDL_JoystickName(SDL_JoystickIndex(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick));
205#endif
206		if (events->preferredJoysticks[player->playerId] && strcmp(events->preferredJoysticks[player->playerId], joystickName) == 0) {
207			index = i;
208			break;
209		}
210	}
211
212	if (index == SIZE_MAX && firstUnclaimed != SIZE_MAX) {
213		index = firstUnclaimed;
214	}
215
216	if (index != SIZE_MAX) {
217		player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
218
219#if SDL_VERSION_ATLEAST(2, 0, 0)
220		if (player->joystick->haptic) {
221			SDL_HapticRumbleInit(player->joystick->haptic);
222		}
223#endif
224	}
225
226	++events->playersAttached;
227	return true;
228}
229
230void mSDLDetachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
231	if (player != events->players[player->playerId]) {
232		return;
233	}
234	int i;
235	for (i = player->playerId; i < events->playersAttached; ++i) {
236		if (i + 1 < MAX_PLAYERS) {
237			events->players[i] = events->players[i + 1];
238		}
239		if (i < events->playersAttached - 1) {
240			events->players[i]->playerId = i;
241		}
242	}
243	--events->playersAttached;
244	CircleBufferDeinit(&player->rotation.zHistory);
245}
246
247void mSDLPlayerLoadConfig(struct mSDLPlayer* context, const struct Configuration* config) {
248	mInputMapLoad(context->bindings, SDL_BINDING_KEY, config);
249	if (context->joystick) {
250		mInputMapLoad(context->bindings, SDL_BINDING_BUTTON, config);
251#if SDL_VERSION_ATLEAST(2, 0, 0)
252		const char* name = SDL_JoystickName(context->joystick->joystick);
253#else
254		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
255#endif
256		mInputProfileLoad(context->bindings, SDL_BINDING_BUTTON, config, name);
257
258		const char* value;
259		char* end;
260		int numAxes = SDL_JoystickNumAxes(context->joystick->joystick);
261		int axis;
262		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", name);
263		if (value) {
264			axis = strtol(value, &end, 0);
265			if (axis >= 0 && axis < numAxes && end && !*end) {
266				context->rotation.axisX = axis;
267			}
268		}
269		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", name);
270		if (value) {
271			axis = strtol(value, &end, 0);
272			if (axis >= 0 && axis < numAxes && end && !*end) {
273				context->rotation.axisY = axis;
274			}
275		}
276		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", name);
277		if (value) {
278			axis = strtol(value, &end, 0);
279			if (axis >= 0 && axis < numAxes && end && !*end) {
280				context->rotation.gyroX = axis;
281			}
282		}
283		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", name);
284		if (value) {
285			axis = strtol(value, &end, 0);
286			if (axis >= 0 && axis < numAxes && end && !*end) {
287				context->rotation.gyroY = axis;
288			}
289		}
290		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", name);
291		if (value) {
292			float sensitivity = strtof_u(value, &end);
293			if (end && !*end) {
294				context->rotation.gyroSensitivity = sensitivity;
295			}
296		}
297	}
298}
299
300void mSDLPlayerSaveConfig(const struct mSDLPlayer* context, struct Configuration* config) {
301	if (context->joystick) {
302#if SDL_VERSION_ATLEAST(2, 0, 0)
303		const char* name = SDL_JoystickName(context->joystick->joystick);
304#else
305		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
306#endif
307		char value[12];
308		snprintf(value, sizeof(value), "%i", context->rotation.axisX);
309		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", value, name);
310		snprintf(value, sizeof(value), "%i", context->rotation.axisY);
311		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", value, name);
312		snprintf(value, sizeof(value), "%i", context->rotation.gyroX);
313		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", value, name);
314		snprintf(value, sizeof(value), "%i", context->rotation.gyroY);
315		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", value, name);
316		snprintf(value, sizeof(value), "%g", context->rotation.gyroSensitivity);
317		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", value, name);
318	}
319}
320
321void mSDLPlayerChangeJoystick(struct mSDLEvents* events, struct mSDLPlayer* player, size_t index) {
322	if (player->playerId >= MAX_PLAYERS || index >= SDL_JoystickListSize(&events->joysticks)) {
323		return;
324	}
325	player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
326}
327
328void mSDLUpdateJoysticks(struct mSDLEvents* events, const struct Configuration* config) {
329	// Pump SDL joystick events without eating the rest of the events
330	SDL_JoystickUpdate();
331#if SDL_VERSION_ATLEAST(2, 0, 0)
332	SDL_Event event;
333	while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED) > 0) {
334		if (event.type == SDL_JOYDEVICEADDED) {
335			struct SDL_JoystickCombo* joystick = SDL_JoystickListAppend(&events->joysticks);
336			joystick->joystick = SDL_JoystickOpen(event.jdevice.which);
337			joystick->id = SDL_JoystickInstanceID(joystick->joystick);
338			joystick->index = SDL_JoystickListSize(&events->joysticks) - 1;
339#if SDL_VERSION_ATLEAST(2, 0, 0)
340			joystick->haptic = SDL_HapticOpenFromJoystick(joystick->joystick);
341#endif
342
343			const char* joystickName;
344#if SDL_VERSION_ATLEAST(2, 0, 0)
345			joystickName = SDL_JoystickName(joystick->joystick);
346#else
347			joystickName = SDL_JoystickName(SDL_JoystickIndex(joystick->joystick));
348#endif
349			size_t i;
350			for (i = 0; (int) i < events->playersAttached; ++i) {
351				if (events->players[i]->joystick) {
352					continue;
353				}
354				if (events->preferredJoysticks[i] && strcmp(events->preferredJoysticks[i], joystickName) == 0) {
355					events->players[i]->joystick = joystick;
356					if (config) {
357						mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
358					}
359					return;
360				}
361			}
362			for (i = 0; (int) i < events->playersAttached; ++i) {
363				if (events->players[i]->joystick) {
364					continue;
365				}
366				events->players[i]->joystick = joystick;
367				if (config) {
368					mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
369				}
370				break;
371			}
372		} else if (event.type == SDL_JOYDEVICEREMOVED) {
373			SDL_JoystickID ids[MAX_PLAYERS] = { 0 };
374			size_t i;
375			for (i = 0; (int) i < events->playersAttached; ++i) {
376				if (events->players[i]->joystick) {
377					ids[i] = events->players[i]->joystick->id;
378					events->players[i]->joystick = 0;
379				} else {
380					ids[i] = -1;
381				}
382			}
383			for (i = 0; i < SDL_JoystickListSize(&events->joysticks);) {
384				struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
385				if (joystick->id == event.jdevice.which) {
386					SDL_JoystickListShift(&events->joysticks, i, 1);
387					continue;
388				}
389				SDL_JoystickListGetPointer(&events->joysticks, i)->index = i;
390				int p;
391				for (p = 0; p < events->playersAttached; ++p) {
392					if (joystick->id == ids[p]) {
393						events->players[p]->joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
394					}
395				}
396				++i;
397			}
398		}
399	}
400#endif
401}
402
403static void _pauseAfterFrame(struct mCoreThread* context) {
404	context->frameCallback = 0;
405	mCoreThreadPauseFromThread(context);
406}
407
408static void _mSDLHandleKeypress(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_KeyboardEvent* event) {
409	int key = -1;
410	if (!event->keysym.mod) {
411		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.sym);
412	}
413	if (key != -1) {
414		if (event->type == SDL_KEYDOWN) {
415			context->core->addKeys(context->core, 1 << key);
416		} else {
417			context->core->clearKeys(context->core, 1 << key);
418		}
419		return;
420	}
421	if (event->keysym.sym == SDLK_TAB) {
422		context->sync.audioWait = event->type != SDL_KEYDOWN;
423		return;
424	}
425	if (event->keysym.sym == SDLK_BACKQUOTE) {
426		mCoreThreadSetRewinding(context, event->type == SDL_KEYDOWN);
427	}
428	if (event->type == SDL_KEYDOWN) {
429		switch (event->keysym.sym) {
430#ifdef USE_DEBUGGERS
431		case SDLK_F11:
432			if (context->core->debugger) {
433				mDebuggerEnter(context->core->debugger, DEBUGGER_ENTER_MANUAL, NULL);
434			}
435			return;
436#endif
437#ifdef USE_PNG
438		case SDLK_F12:
439			mCoreTakeScreenshot(context->core);
440			return;
441#endif
442		case SDLK_BACKSLASH:
443			mCoreThreadPause(context);
444			context->frameCallback = _pauseAfterFrame;
445			mCoreThreadUnpause(context);
446			return;
447#ifdef BUILD_PANDORA
448		case SDLK_ESCAPE:
449			mCoreThreadEnd(context);
450			return;
451#endif
452		default:
453			if ((event->keysym.mod & GUI_MOD) && (event->keysym.mod & GUI_MOD) == event->keysym.mod) {
454				switch (event->keysym.sym) {
455#if SDL_VERSION_ATLEAST(2, 0, 0)
456				case SDLK_f:
457					SDL_SetWindowFullscreen(sdlContext->window, sdlContext->fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
458					sdlContext->fullscreen = !sdlContext->fullscreen;
459					sdlContext->windowUpdated = 1;
460					break;
461#endif
462				case SDLK_p:
463					mCoreThreadTogglePause(context);
464					break;
465				case SDLK_n:
466					mCoreThreadPause(context);
467					context->frameCallback = _pauseAfterFrame;
468					mCoreThreadUnpause(context);
469					break;
470				case SDLK_r:
471					mCoreThreadReset(context);
472					break;
473				default:
474					break;
475				}
476			}
477			if (event->keysym.mod & KMOD_SHIFT) {
478				switch (event->keysym.sym) {
479				case SDLK_F1:
480				case SDLK_F2:
481				case SDLK_F3:
482				case SDLK_F4:
483				case SDLK_F5:
484				case SDLK_F6:
485				case SDLK_F7:
486				case SDLK_F8:
487				case SDLK_F9:
488					mCoreThreadInterrupt(context);
489					mCoreSaveState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SAVEDATA | SAVESTATE_SCREENSHOT);
490					mCoreThreadContinue(context);
491					break;
492				default:
493					break;
494				}
495			} else {
496				switch (event->keysym.sym) {
497				case SDLK_F1:
498				case SDLK_F2:
499				case SDLK_F3:
500				case SDLK_F4:
501				case SDLK_F5:
502				case SDLK_F6:
503				case SDLK_F7:
504				case SDLK_F8:
505				case SDLK_F9:
506					mCoreThreadInterrupt(context);
507					mCoreLoadState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT);
508					mCoreThreadContinue(context);
509					break;
510				default:
511					break;
512				}
513			}
514			return;
515		}
516	}
517}
518
519static void _mSDLHandleJoyButton(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_JoyButtonEvent* event) {
520	int key = 0;
521	key = mInputMapKey(sdlContext->bindings, SDL_BINDING_BUTTON, event->button);
522	if (key == -1) {
523		return;
524	}
525
526	if (event->type == SDL_JOYBUTTONDOWN) {
527		core->addKeys(core, 1 << key);
528	} else {
529		core->clearKeys(core, 1 << key);
530	}
531}
532
533static void _mSDLHandleJoyHat(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_JoyHatEvent* event) {
534	int allKeys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, -1);
535	if (allKeys == 0) {
536		return;
537	}
538
539	int keys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, event->value);
540
541	core->clearKeys(core, allKeys ^ keys);
542	core->addKeys(core, keys);
543}
544
545static void _mSDLHandleJoyAxis(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_JoyAxisEvent* event) {
546	int clearKeys = ~mInputClearAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, -1);
547	int newKeys = 0;
548	int key = mInputMapAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, event->value);
549	if (key != -1) {
550		newKeys |= 1 << key;
551	}
552	clearKeys &= ~newKeys;
553	core->clearKeys(core, clearKeys);
554	core->addKeys(core, newKeys);
555
556}
557
558#if SDL_VERSION_ATLEAST(2, 0, 0)
559static void _mSDLHandleWindowEvent(struct mSDLPlayer* sdlContext, const struct SDL_WindowEvent* event) {
560	switch (event->event) {
561	case SDL_WINDOWEVENT_SIZE_CHANGED:
562		sdlContext->windowUpdated = 1;
563		break;
564	}
565}
566#endif
567
568void mSDLHandleEvent(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const union SDL_Event* event) {
569	switch (event->type) {
570	case SDL_QUIT:
571		mCoreThreadEnd(context);
572		break;
573#if SDL_VERSION_ATLEAST(2, 0, 0)
574	case SDL_WINDOWEVENT:
575		_mSDLHandleWindowEvent(sdlContext, &event->window);
576		break;
577#endif
578	case SDL_KEYDOWN:
579	case SDL_KEYUP:
580		_mSDLHandleKeypress(context, sdlContext, &event->key);
581		break;
582	case SDL_JOYBUTTONDOWN:
583	case SDL_JOYBUTTONUP:
584		_mSDLHandleJoyButton(context->core, sdlContext, &event->jbutton);
585		break;
586	case SDL_JOYHATMOTION:
587		_mSDLHandleJoyHat(context->core, sdlContext, &event->jhat);
588		break;
589	case SDL_JOYAXISMOTION:
590		_mSDLHandleJoyAxis(context->core, sdlContext, &event->jaxis);
591		break;
592	}
593}
594
595#if SDL_VERSION_ATLEAST(2, 0, 0)
596static void _mSDLSetRumble(struct mRumble* rumble, int enable) {
597	struct mSDLRumble* sdlRumble = (struct mSDLRumble*) rumble;
598	if (!sdlRumble->p->joystick || !sdlRumble->p->joystick->haptic || !SDL_HapticRumbleSupported(sdlRumble->p->joystick->haptic)) {
599		return;
600	}
601	int8_t originalLevel = sdlRumble->level;
602	sdlRumble->level += enable;
603	if (CircleBufferSize(&sdlRumble->history) == RUMBLE_PWM) {
604		int8_t oldLevel;
605		CircleBufferRead8(&sdlRumble->history, &oldLevel);
606		sdlRumble->level -= oldLevel;
607	}
608	CircleBufferWrite8(&sdlRumble->history, enable);
609	if (sdlRumble->level == originalLevel) {
610		return;
611	}
612	float activeLevel = ceil(RUMBLE_STEPS * sdlRumble->level / (float) RUMBLE_PWM) / RUMBLE_STEPS;
613	if (fabsf(sdlRumble->activeLevel - activeLevel) < 0.75 / RUMBLE_STEPS) {
614		return;
615	}
616	sdlRumble->activeLevel = activeLevel;
617	if (sdlRumble->activeLevel > 0.5 / RUMBLE_STEPS) {
618		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
619		SDL_HapticRumblePlay(sdlRumble->p->joystick->haptic, activeLevel, 500);
620	} else {
621		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
622	}
623}
624#endif
625
626static int32_t _readTilt(struct mSDLPlayer* player, int axis) {
627	if (!player->joystick) {
628		return 0;
629	}
630	return SDL_JoystickGetAxis(player->joystick->joystick, axis) * 0x3800;
631}
632
633static int32_t _mSDLReadTiltX(struct mRotationSource* source) {
634	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
635	return _readTilt(rotation->p, rotation->axisX);
636}
637
638static int32_t _mSDLReadTiltY(struct mRotationSource* source) {
639	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
640	return _readTilt(rotation->p, rotation->axisY);
641}
642
643static int32_t _mSDLReadGyroZ(struct mRotationSource* source) {
644	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
645	float z = rotation->zDelta;
646	return z * rotation->gyroSensitivity;
647}
648
649static void _mSDLRotationSample(struct mRotationSource* source) {
650	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
651	SDL_JoystickUpdate();
652	if (!rotation->p->joystick) {
653		return;
654	}
655
656	int x = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroX);
657	int y = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroY);
658	union {
659		float f;
660		int32_t i;
661	} theta = { .f = atan2f(y, x) - atan2f(rotation->oldY, rotation->oldX) };
662	if (isnan(theta.f)) {
663		theta.f = 0.0f;
664	} else if (theta.f > M_PI) {
665		theta.f -= 2.0f * M_PI;
666	} else if (theta.f < -M_PI) {
667		theta.f += 2.0f * M_PI;
668	}
669	rotation->oldX = x;
670	rotation->oldY = y;
671
672	float oldZ = 0;
673	if (CircleBufferSize(&rotation->zHistory) == GYRO_STEPS * sizeof(float)) {
674		CircleBufferRead32(&rotation->zHistory, (int32_t*) &oldZ);
675	}
676	CircleBufferWrite32(&rotation->zHistory, theta.i);
677	rotation->zDelta += theta.f - oldZ;
678}
679
680#if SDL_VERSION_ATLEAST(2, 0, 0)
681void mSDLSuspendScreensaver(struct mSDLEvents* events) {
682	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
683		SDL_DisableScreenSaver();
684	}
685	++events->screensaverSuspendDepth;
686}
687
688void mSDLResumeScreensaver(struct mSDLEvents* events) {
689	--events->screensaverSuspendDepth;
690	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
691		SDL_EnableScreenSaver();
692	}
693}
694
695void mSDLSetScreensaverSuspendable(struct mSDLEvents* events, bool suspendable) {
696	bool wasSuspendable = events->screensaverSuspendable;
697	events->screensaverSuspendable = suspendable;
698	if (events->screensaverSuspendDepth > 0) {
699		if (suspendable && !wasSuspendable) {
700			SDL_DisableScreenSaver();
701		} else if (!suspendable && wasSuspendable) {
702			SDL_EnableScreenSaver();
703		}
704	} else {
705		SDL_EnableScreenSaver();
706	}
707}
708#endif