all repos — mgba @ 1cc0bdeec140cbe411020b8239f3dd47852a9e2f

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