/* * ============================================================ * FILE: controls.c * * PURPOSE: Turns the physical gamepad (primary) or keyboard (fallback) * into the abstract Input struct from controls.h. Getting * the analog feel right here (the deadzone and stick scaling) * matters as much as the player code for movement feel. * * FITS IN: main.c calls controls_poll() once per fixed tick. It uses * GLFW's gamepad API directly and window_handle() (window.h) * only for keyboard reads. It's the only file that reads raw * input devices. * * IMPLEMENT: * - Private state: the previous tick's button states (for the "pressed" * edges), e.g. `static bool s_prev_jump, s_prev_reset, s_prev_quit;` * * - Finding a gamepad (keep it simple; this also handles hot-plugging): * each poll, loop GLFW_JOYSTICK_1..GLFW_JOYSTICK_LAST and use the first * jid where glfwJoystickIsGamepad(jid) is true, then read it with * glfwGetGamepadState(jid, &state). GLFW 3.4 has SDL's controller * mapping database built in, so Xbox/PlayStation/Switch pads all show * up in the standard layout. Print a line to stdout when the active * pad connects or disconnects (glfwGetGamepadName), so it's clear * which device is in use. * * - Extra built-in mappings: some pads aren't in GLFW's database under * their exact GUID (on Linux the GUID includes the driver/firmware * version), so they show up as a raw joystick with * glfwJoystickIsGamepad() == false and get ignored. Keep a short list * of SDL-format mapping strings for pads we actually use, and register * them in controls_init() with glfwUpdateGamepadMappings(). Currently: * Xbox Elite Series 2 over USB (xpad driver, GUID * 030000005e040000000b000017050000). To add a pad: find its GUID with * glfwGetJoystickGUID() and its button/axis order from the evdev codes * (/proc/bus/input/devices), or copy its line from SDL's * gamecontrollerdb.txt. * At init, also print any joystick that has sticks (>= 2 axes) but no * mapping, with its name and GUID, so a new pad that's silently ignored * is easy to diagnose. * * - Gamepad mapping: * move.x = GLFW_GAMEPAD_AXIS_LEFT_X * move.y = -GLFW_GAMEPAD_AXIS_LEFT_Y (GLFW reports up as NEGATIVE, * so flip it: up = forward = +y) * look.x = GLFW_GAMEPAD_AXIS_RIGHT_X * look.y = -GLFW_GAMEPAD_AXIS_RIGHT_Y * jump = GLFW_GAMEPAD_BUTTON_A * reset = GLFW_GAMEPAD_BUTTON_BACK * quit = GLFW_GAMEPAD_BUTTON_START * * - RADIAL deadzone (write a small static helper, used for both sticks): * len = length of the raw (x, y) * if len < deadzone -> (0, 0) * else rescale so the edge of the deadzone maps to 0 and full tilt maps * to 1: new_len = (len - deadzone) / (1 - deadzone), clamped to 1, * keeping the original direction. * WHY radial and not per-axis: a per-axis deadzone snaps diagonals * to the cardinal directions and makes slow walking feel "sticky". SM64 * also computes one magnitude from the whole stick and uses it for speed. * Also clamp the final length to 1, because some pads report corners past 1. * Use MOVE_DEADZONE / LOOK_DEADZONE from config.h. * * - Keyboard fallback, used ONLY when no gamepad is connected: * W/S/A/D -> move (normalize diagonals so the length is <= 1) * Arrow keys -> look * Space -> jump, R -> reset, Esc -> quit * Read keys with glfwGetKey(window_handle(), key). * Esc also quits when a gamepad IS connected (so you can always exit). * * - Edge detection: pressed = down_now && !down_last_tick. Then store * down_now for next tick. * * - Zero the whole Input at the start of controls_poll so no stale data leaks. * * CONVENTIONS: `s_` prefix for statics. is included here (not * in controls.h). * * NOT IN SCOPE: Rebinding, loading an external gamecontrollerdb.txt (a few * embedded mapping lines are fine; a whole database is not), * rumble, triggers/shoulder buttons (add them when a move needs * them), input recording/replay. * * DONE WHEN: With a pad: a small stick tilt gives a small |move|, full * tilt gives ~1.0, the resting stick gives exactly (0, 0), and each * A press sets jump_pressed for exactly one tick. Unplugging the * pad switches to the keyboard without a crash, and plugging it back * in switches back. * ============================================================ */ #include #include #include #include "config.h" #include "controls.h" #include "window.h" #define NO_GAMEPAD (-1) /* SDL-format mappings for pads missing from GLFW's built-in database under * their exact GUID. Without a mapping, GLFW only exposes a pad as a raw * joystick and we ignore it. One line per pad: * GUID,name,:,...,platform:, * where bN = raw button N, aN = raw axis N, h0.M = hat 0 direction bitmask M. */ static const char *EXTRA_GAMEPAD_MAPPINGS = /* Xbox Elite Series 2 over USB (xpad driver, reports version 0x0517). */ "030000005e040000000b000017050000,Xbox Elite Series 2 Controller," "a:b0,b:b1,x:b2,y:b3,leftshoulder:b4,rightshoulder:b5,back:b6,start:b7," "guide:b8,leftstick:b9,rightstick:b10,leftx:a0,lefty:a1,lefttrigger:a2," "rightx:a3,righty:a4,righttrigger:a5,dpup:h0.1,dpright:h0.2,dpdown:h0.4," "dpleft:h0.8,platform:Linux,\n"; /* Last tick's button states, for turning "down" into "pressed this tick". */ static bool s_prev_jump, s_prev_reset, s_prev_quit; /* The joystick id we're reading, or NO_GAMEPAD. Only used to notice (and * print) when a pad connects or disconnects. */ static int s_active_jid = NO_GAMEPAD; /* Raw buttons for this tick, before edge detection. */ typedef struct { bool jump, reset, quit; } Buttons; /* Radial deadzone. WHY radial and not per-axis: a per-axis deadzone snaps * diagonals to the cardinal directions and makes slow walking feel "sticky". * SM64 also computes one magnitude from the whole stick and uses it for speed. * The rescale makes the deadzone's edge 0 and full tilt 1, so the whole * 0..1 range stays usable instead of jumping from 0 to `deadzone`. */ static Vec2 apply_radial_deadzone(float x, float y, float deadzone) { float len = sqrtf(x * x + y * y); if (len < deadzone) return vec2_make(0.0f, 0.0f); /* Clamped because some pads report corners past 1. */ float new_len = clampf((len - deadzone) / (1.0f - deadzone), 0.0f, 1.0f); float scale = new_len / len; return vec2_make(x * scale, y * scale); } /* Returns the first connected gamepad, or NO_GAMEPAD. Called every poll, * which is also what makes hot-plugging work. */ static int find_gamepad(void) { for (int jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++) { if (glfwJoystickIsGamepad(jid)) return jid; } return NO_GAMEPAD; } static void report_gamepad_change(int jid) { if (jid == s_active_jid) return; if (s_active_jid != NO_GAMEPAD) printf("controls: gamepad disconnected, keyboard fallback active\n"); if (jid != NO_GAMEPAD) printf("controls: using gamepad \"%s\"\n", glfwGetGamepadName(jid)); fflush(stdout); s_active_jid = jid; } static Buttons read_gamepad(int jid, Input *out) { Buttons buttons = { false, false, false }; GLFWgamepadstate state; if (!glfwGetGamepadState(jid, &state)) return buttons; /* GLFW reports stick-up as NEGATIVE y, so flip it: up = forward = +y. */ out->move = apply_radial_deadzone(state.axes[GLFW_GAMEPAD_AXIS_LEFT_X], -state.axes[GLFW_GAMEPAD_AXIS_LEFT_Y], MOVE_DEADZONE); out->look = apply_radial_deadzone(state.axes[GLFW_GAMEPAD_AXIS_RIGHT_X], -state.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y], LOOK_DEADZONE); buttons.jump = state.buttons[GLFW_GAMEPAD_BUTTON_A] == GLFW_PRESS; buttons.reset = state.buttons[GLFW_GAMEPAD_BUTTON_BACK] == GLFW_PRESS; buttons.quit = state.buttons[GLFW_GAMEPAD_BUTTON_START] == GLFW_PRESS; out->using_gamepad = true; return buttons; } static bool key_down(int key) { return glfwGetKey(window_handle(), key) == GLFW_PRESS; } /* Turns two opposing keys into -1, 0 or +1. */ static float key_axis(int negative_key, int positive_key) { return (float)key_down(positive_key) - (float)key_down(negative_key); } /* Keyboard fallback for testing without a pad. Keys are all-or-nothing, * so diagonals are normalized to keep |move| <= 1 (otherwise diagonal * running would be ~41% faster). */ static Buttons read_keyboard(Input *out) { Buttons buttons; Vec2 move = vec2_make(key_axis(GLFW_KEY_A, GLFW_KEY_D), key_axis(GLFW_KEY_S, GLFW_KEY_W)); float len = vec2_length(move); if (len > 1.0f) move = vec2_make(move.x / len, move.y / len); out->move = move; Vec2 look = vec2_make(key_axis(GLFW_KEY_LEFT, GLFW_KEY_RIGHT), key_axis(GLFW_KEY_DOWN, GLFW_KEY_UP)); len = vec2_length(look); if (len > 1.0f) look = vec2_make(look.x / len, look.y / len); out->look = look; buttons.jump = key_down(GLFW_KEY_SPACE); buttons.reset = key_down(GLFW_KEY_R); buttons.quit = false; /* Esc is handled for every device in controls_poll */ out->using_gamepad = false; return buttons; } /* Lists joysticks that have sticks but no gamepad mapping. Headsets, mice and * keyboards also show up as joysticks, which is why anything with fewer * than 2 axes is skipped. */ static void report_unmapped_joysticks(void) { for (int jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++) { int axis_count = 0; if (!glfwJoystickPresent(jid) || glfwJoystickIsGamepad(jid)) continue; glfwGetJoystickAxes(jid, &axis_count); if (axis_count >= 2) printf("controls: \"%s\" (GUID %s) has no gamepad mapping, ignoring it\n", glfwGetJoystickName(jid), glfwGetJoystickGUID(jid)); } } void controls_init(void) { if (!glfwUpdateGamepadMappings(EXTRA_GAMEPAD_MAPPINGS)) fprintf(stderr, "controls: failed to add extra gamepad mappings\n"); report_unmapped_joysticks(); /* Report whichever pad is already plugged in at startup. */ report_gamepad_change(find_gamepad()); } void controls_poll(Input *out) { memset(out, 0, sizeof *out); /* no stale data from the last tick */ int jid = find_gamepad(); report_gamepad_change(jid); Buttons now = (jid != NO_GAMEPAD) ? read_gamepad(jid, out) : read_keyboard(out); /* Esc always quits, even with a pad connected, so you can always exit. */ if (key_down(GLFW_KEY_ESCAPE)) now.quit = true; /* Edges: "pressed" is true only on the first tick the button is down. */ out->jump_held = now.jump; out->jump_pressed = now.jump && !s_prev_jump; out->reset_pressed = now.reset && !s_prev_reset; out->quit_pressed = now.quit && !s_prev_quit; s_prev_jump = now.jump; s_prev_reset = now.reset; s_prev_quit = now.quit; }