all repos — mgba @ 12ae8ba9491b8428711cbbde50f8cc5719007cfa

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