Browse code

Added gamepad support

neauoire authored on 27/12/2021 18:04:24
Showing 1 changed files
... ...
@@ -171,7 +171,7 @@ init(void)
171 171
 	as.callback = audio_callback;
172 172
 	as.samples = 512;
173 173
 	as.userdata = NULL;
174
-	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
174
+	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) < 0) {
175 175
 		error("sdl", SDL_GetError());
176 176
 		if(SDL_Init(SDL_INIT_VIDEO) < 0)
177 177
 			return error("sdl", SDL_GetError());
... ...
@@ -192,6 +192,7 @@ init(void)
192 192
 	SDL_StartTextInput();
193 193
 	SDL_ShowCursor(SDL_DISABLE);
194 194
 	SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
195
+	SDL_GameControllerEventState(SDL_ENABLE);
195 196
 	return 1;
196 197
 }
197 198
 
... ...
@@ -391,7 +392,7 @@ restart(Uxn *u)
391 392
 	start(u, "boot.rom");
392 393
 }
393 394
 
394
-Uint8
395
+static Uint8
395 396
 get_button(SDL_Event *event)
396 397
 {
397 398
 	switch(event->key.keysym.sym) {
... ...
@@ -407,7 +408,24 @@ get_button(SDL_Event *event)
407 408
 	return 0x00;
408 409
 }
409 410
 
410
-Uint8
411
+static Uint8
412
+get_button_dpad(SDL_Event *e)
413
+{
414
+	switch(e->cbutton.button) {
415
+	case SDL_CONTROLLER_BUTTON_A: return 0x01;
416
+	case SDL_CONTROLLER_BUTTON_B: return 0x02;
417
+	case SDL_CONTROLLER_BUTTON_X: return 0x04;
418
+	case SDL_CONTROLLER_BUTTON_Y:
419
+	case SDL_CONTROLLER_BUTTON_START: return 0x08;
420
+	case SDL_CONTROLLER_BUTTON_DPAD_UP: return 0x10;
421
+	case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return 0x20;
422
+	case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return 0x40;
423
+	case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return 0x80;
424
+	}
425
+	return 0x00;
426
+}
427
+
428
+static Uint8
411 429
 get_key(SDL_Event *event)
412 430
 {
413 431
 	SDL_Keymod mods = SDL_GetModState();
... ...
@@ -491,6 +509,10 @@ run(Uxn *u)
491 509
 				controller_up(devctrl, get_button(&event));
492 510
 			else if(event.type == SDL_TEXTINPUT)
493 511
 				controller_key(devctrl, event.text.text[0]);
512
+			else if(event.type == SDL_CONTROLLERBUTTONDOWN)
513
+				controller_down(devctrl, get_button_dpad(&event));
514
+			else if(event.type == SDL_CONTROLLERBUTTONUP)
515
+				controller_up(devctrl, get_button_dpad(&event));
494 516
 			/* Console */
495 517
 			else if(event.type == stdin_event)
496 518
 				console_input(u, event.cbutton.button);