summaryrefslogtreecommitdiff
path: root/platformer/src/controls.c
blob: f9f55c0acc592d9c060eae8cf891cc211abe73b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * ============================================================
 * 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. <GLFW/glfw3.h> 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 <GLFW/glfw3.h>

#include <stdio.h>
#include <string.h>

#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,<standard button/axis>:<raw index>,...,platform:<OS>,
 * 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;
}