summaryrefslogtreecommitdiff
path: root/platformer/src/camera.c
blob: b11f6bb6f5b69f94eaeeb0d1939bc5e1ed529603 (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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/*
 * ============================================================
 * FILE:        camera.c
 *
 * PURPOSE:     A player-controlled third-person camera in the spirit of SM64's
 *              "Lakitu": it orbits the player, but it does NOT glue the player
 *              to the center of the screen. The player moves around inside a
 *              screen-space zone and the camera only moves when it has to. The
 *              resulting off-center shots are what give it a cinematic feel.
 *
 * FITS IN:     Implements camera.h. Reads Input.look and Input.recenter_pressed
 *              (controls.h) and the player's position and facing (passed in
 *              by main.c).
 *              Produces matrices for render.c and a yaw for player.c.
 *
 * IMPLEMENT:
 *   - The camera is described by WHERE THE PLAYER SITS ON SCREEN (`framing`,
 *     in NDC) and HOW FAR AWAY they are (`depth`), plus yaw/pitch. The eye
 *     position is derived from those every tick. That makes the zone rules
 *     simple clamps on `framing`, and it makes orbiting keep the player at the
 *     same screen spot (the camera orbits the PLAYER, not empty space).
 *
 *   - Two screen boxes, given in window fractions (0 = left/bottom, 1 =
 *     right/top) and converted with NDC = 2 * fraction - 1:
 *       resting zone   where a stopped player may sit without the camera moving
 *                        x: 1/3 + CAMERA_ZONE_INSET .. 2/3 - CAMERA_ZONE_INSET
 *                        y: 1/3 + CAMERA_ZONE_INSET .. CAMERA_ZONE_TOP
 *       running bound  the resting zone grown by CAMERA_ZONE_INSET on every side
 *                        x: 1/3 .. 2/3   (the thirds lines)
 *                        y: 1/3 .. CAMERA_ZONE_TOP + CAMERA_ZONE_INSET
 *     The top is lower than the thirds on purpose: it keeps the view AHEAD of
 *     a player running away from the camera open, so upcoming obstacles stay
 *     visible. The "subject" is the player's feet + CAMERA_TARGET_HEIGHT.
 *
 *   - camera_init(c, follow_point): yaw 0 (camera on +Z looking toward -Z),
 *     pitch CAMERA_PITCH_DEFAULT, distance and depth CAMERA_DISTANCE, framing
 *     (0,0), not recentering, subject = follow_point + target height. Place it.
 *
 *   - Recentering is a one-shot glide to "centered, behind the player". When
 *     Input.recenter_pressed arrives, capture recenter_yaw = the yaw that puts
 *     the camera behind the player's facing (follow_facing + PI). Until the glide
 *     finishes, the camera rides along rigidly with the player (their movement
 *     does NOT change framing/depth), so it always finishes even while they run.
 *     Then the normal zone rules take over again with the player centered.
 *     The right stick still works mid-glide: it steers recenter_yaw along with
 *     the view, so there's no fight (and a wobble while clicking is harmless).
 *
 *   - Sideways runs get two extra behaviors, both scaled by the "lateral
 *     share": how much of the player's horizontal motion goes across the
 *     screen (-1 = straight left, +1 = straight right, 0 = straight toward/away
 *     from the camera or not moving horizontally). Up/down runs are untouched.
 *       lead room          the camera works AHEAD of the player so they drift to
 *                          the TRAILING side of the running bound (running right
 *                          -> left thirds line), leaving open screen in the
 *                          direction they're heading, for upcoming obstacles.
 *       back-quarter swing the camera slowly turns toward CAMERA_SWING_OFFSET
 *                          off directly-behind the player's motion, on the side
 *                          it's already on, so a side-on view becomes a view down
 *                          the run. Inside that back quarter it doesn't swing.
 *                          Controls stay camera-relative, so holding the stick
 *                          sideways while it swings makes the player arc, like
 *                          Mario circling in SM64. That's intentional.
 *
 *   - Auto-pitch: once the camera has gone CAMERA_AUTO_PITCH_DELAY seconds
 *     without being moved by hand (right stick, or a recenter click), pitch
 *     slowly heads to CAMERA_AUTO_PITCH_DEG (looking down at the player). The
 *     move eases in AND out: its speed (auto_pitch_speed) starts at 0, grows
 *     by CAMERA_AUTO_PITCH_ACCEL, is capped at CAMERA_AUTO_PITCH_SPEED, and is
 *     also capped by the braking curve sqrt(2 * accel * remaining angle), the
 *     fastest speed that can still slow to a stop exactly on the target. It
 *     only touches pitch, so it runs at the same time as the back-quarter swing
 *     (yaw) instead of taking turns with it. Touching the camera restarts the
 *     countdown and stops the tilt at once, and a pitch you set by hand is
 *     respected until the countdown runs out again.
 *
 *   - camera_update(c, in, follow_point, follow_facing, pan_locked, aspect, dt):
 *       1. Movement check: the subject counts as "moving" if it changed since
 *          last tick (this includes slowing to a stop and jumping in place).
 *          On recenter_pressed, start a recenter (see above).
 *       2. Orbit: yaw -= look.x * CAMERA_YAW_SPEED * dt (the sign is flipped so
 *          stick-right turns the view right), pitch += look.y *
 *          CAMERA_PITCH_SPEED * dt, clamp pitch, wrap yaw. `framing` is kept,
 *          so the player stays at the same screen spot while orbiting. While
 *          recentering, apply the same yaw change to recenter_yaw, then ease yaw
 *          toward recenter_yaw (the short way around) at CAMERA_RECENTER_RATE.
 *          Otherwise, while moving and NOT pan_locked, apply the back-quarter
 *          swing: approach its goal yaw at CAMERA_SWING_SPEED * |lateral share|
 *          rad/s (constant rate, so the swing is slow and even). In a
 *          locked-pan zone the camera never turns behind the player on its
 *          own; everything else below still applies. Then apply the auto-pitch (see
 *          above). Framing is kept through all of these.
 *       3. Hold still (except while recentering): the camera does NOT follow
 *          vertically or in depth by default. Project how far the subject moved
 *          onto the camera's up/forward axes. Up changes where they sit on
 *          screen, and forward changes `depth`. Sideways motion is NOT turned
 *          into screen drift: horizontally the camera keeps pace with the
 *          player, and the lead-room rule alone decides where they sit across
 *          the screen (a raw drift would push them to the LEADING side, which is
 *          exactly what lead room avoids).
 *       4. Depth: while recentering, ease `depth` to `distance` at
 *          CAMERA_RECENTER_RATE. Otherwise, only while the player moves, ease it
 *          at CAMERA_FOLLOW_RATE, so running toward/away from the camera briefly
 *          changes the player's size. Once they stop, the depth freezes too: a
 *          still player inside the zone means a still camera.
 *       5. Framing rules, in priority order:
 *            recentering -> ease framing to (0,0) at CAMERA_RECENTER_RATE; the
 *                           recenter ends once framing, depth and yaw all arrive.
 *            not moving  -> ease framing to the nearest point of the resting zone
 *                           at CAMERA_SETTLE_RATE. Inside the zone that point is
 *                           the player itself, so the camera doesn't move at all.
 *            moving      -> lead room: ease framing.x toward the running bound's
 *                           trailing edge at CAMERA_LEAD_RATE * |lateral share|.
 *            always      -> hard clamp framing to the running bound. On runs
 *                           toward/away from the camera, that's what pushes the
 *                           camera along with the player.
 *          Then keep the eye at least CAMERA_MIN_HEIGHT above the player's feet
 *          (at low pitch, putting the player high on screen would otherwise sink
 *          the eye into the floor).
 *       6. Place the eye: subject - right*side - up*lift - forward*depth, where
 *          side/lift are the framing converted to meters at `depth`. target =
 *          eye + forward * distance, which keeps the YAW CONVENTION exact.
 *       Every ease is exponential (1 - e^(-rate*dt)) and snaps when within a
 *       hair of its goal, so a settled camera is truly still.
 *
 *   - camera_view(): mat4_look_at(position, target, (0,1,0)).
 *   - camera_projection(c, aspect): mat4_perspective(CAMERA_FOV_DEG in radians,
 *     aspect, CAMERA_NEAR, CAMERA_FAR).
 *
 * CONVENTIONS: Radians internally; FOV converted from degrees where used.
 *              Framing is in NDC so it matches what you see on screen, and it
 *              converts to meters via depth * tan(fov/2) (times aspect for x).
 *
 *   - Step 7, objects (keep_eye_clear): the eye never sits INSIDE an object
 *     (world_object_at; zones never count). Objects BETWEEN the player and the
 *     eye are fine: a platform in the shot stays in the shot. Only when the
 *     spot the eye wants is inside an object does the eye jump THROUGH it, the
 *     same tick, to the object's near side, along its line to the player (so
 *     the player stays on the same screen spot and the framing model is
 *     untouched). When the wanted spot is free again, ease the eye back out:
 *     speed up at CAMERA_RETURN_ACCEL, cruise at CAMERA_RETURN_SPEED, brake to
 *     arrive exactly (like the auto-tilt). If that path would take it into an
 *     object, it jumps through to the far side instead of stopping inside.
 *
 * NOT IN SCOPE: Snapping directly behind the player on its
 *              own (only the recenter button does that), shake, vertical
 *              look-ahead. (Good candidates for later tuning, not for now.)
 *
 * DONE WHEN:   A player standing anywhere inside the resting zone never moves
 *              the camera. Running lets the player reach, but never pass, the
 *              running bound. Stopping outside the resting zone eases the camera
 *              until the player sits on the zone's edge. The recenter button
 *              glides the camera behind the player with them centered, finishes
 *              even mid-run, and leaves the zone rules working afterward. The
 *              right stick orbits around the player without moving them on screen.
 *              A sideways run slowly carries the player to the trailing thirds
 *              line and swings the camera to ~30 deg off behind them, while runs
 *              straight toward/away from the camera behave as before. After
 *              CAMERA_AUTO_PITCH_DELAY seconds hands-off, the pitch slowly tilts
 *              to CAMERA_AUTO_PITCH_DEG, alongside any swing in progress.
 * ============================================================
 */

#include "camera.h"
#include "config.h"
#include "world.h"

#define THIRD            (1.0f / 3.0f)   /* the thirds lines, as window fractions */
#define STILL_EPSILON    1e-5f           /* m moved per tick below which the player is "still" */
#define EASE_SNAP        1e-3f           /* eases jump to their goal when this close */

/* The camera's axes for a given orbit. forward points from the eye into the
 * scene; right and up are the screen's right and up in world space. */
typedef struct {
    Vec3 right, up, forward;
} Basis;

static Basis camera_basis(float yaw, float pitch)
{
    float sy = sinf(yaw), cy = cosf(yaw), sp = sinf(pitch), cp = cosf(pitch);
    Basis b;
    b.forward = vec3_make(-sy * cp, -sp, -cy * cp);   /* minus the orbit direction */
    b.right   = vec3_make(cy, 0.0f, -sy);
    b.up      = vec3_make(-sy * sp, cp, -cy * sp);
    return b;
}

/* The point we frame: a bit above the player's feet. */
static Vec3 subject_point(Vec3 follow_point)
{
    return vec3_add(follow_point, vec3_make(0.0f, CAMERA_TARGET_HEIGHT, 0.0f));
}

/* How many meters one NDC unit spans at a given depth. The screen edge
 * (NDC 1) is depth * tan(fov/2) away from the view center, and the
 * horizontal field is wider by the aspect ratio. */
static Vec2 meters_per_ndc(float depth, float aspect)
{
    float half_height = depth * tanf(CAMERA_FOV_DEG * (M3D_PI / 180.0f) * 0.5f);
    return vec2_make(half_height * aspect, half_height);
}

/* Exponential ease: covers the same fraction of the remaining gap every
 * second no matter the tick rate. Snaps when close so settling ends. */
static float ease_toward(float current, float goal, float rate, float dt)
{
    float next = current + (goal - current) * (1.0f - expf(-rate * dt));
    return fabsf(goal - next) < EASE_SNAP ? goal : next;
}

static Vec2 ease_toward_vec2(Vec2 current, Vec2 goal, float rate, float dt)
{
    return vec2_make(ease_toward(current.x, goal.x, rate, dt),
                     ease_toward(current.y, goal.y, rate, dt));
}

/* ease_toward for angles: turns the SHORT way around the circle. */
static float ease_toward_angle(float current, float goal, float rate, float dt)
{
    float next = current + wrap_angle(goal - current) * (1.0f - expf(-rate * dt));
    return fabsf(wrap_angle(goal - next)) < EASE_SNAP ? goal : wrap_angle(next);
}

/* Derives the eye and look-at point from the framing description. */
static void place_camera(Camera *c, float aspect)
{
    Basis b     = camera_basis(c->yaw, c->pitch);
    Vec2  scale = meters_per_ndc(c->depth, aspect);
    Vec3  eye   = c->subject;
    eye = vec3_sub(eye, vec3_scale(b.right,   c->framing.x * scale.x));
    eye = vec3_sub(eye, vec3_scale(b.up,      c->framing.y * scale.y));
    eye = vec3_sub(eye, vec3_scale(b.forward, c->depth));
    c->position = eye;
    c->target   = vec3_add(eye, vec3_scale(b.forward, c->distance));
}

/* Rotates around the player with the right stick. Right stick RIGHT turns the VIEW right,
 * so the camera swings LEFT around the player. Forward is
 * (-sin(yaw), 0, -cos(yaw)), so turning it toward the camera's right
 * (+X at yaw 0) needs yaw to DECREASE, hence the -=. */
static void orbit(Camera *c, const Input *in, float dt)
{
    c->yaw   -= in->look.x * CAMERA_YAW_SPEED   * dt;
    c->pitch += in->look.y * CAMERA_PITCH_SPEED * dt;
    c->pitch  = clampf(c->pitch, CAMERA_PITCH_MIN, CAMERA_PITCH_MAX);
    c->yaw    = wrap_angle(c->yaw);
}

/* Auto-pitch: after CAMERA_AUTO_PITCH_DELAY seconds of the camera not being
 * moved by hand, slowly tilt to the preferred downward viewing angle. The
 * timer is capped at the delay so it can't grow forever. */
/* Where the line from `from` along `dir` enters and leaves box b grown by
 * `radius` (the slab test: along each axis the line is inside the box's
 * range between two distances; it's inside the box where all three ranges
 * overlap). */
static void line_through_box(Vec3 from, Vec3 dir, Box b, float radius, float *enter, float *leave)
{
    float lo[3] = { b.min.x - radius, b.min.y - radius, b.min.z - radius };
    float hi[3] = { b.max.x + radius, b.max.y + radius, b.max.z + radius };
    float o[3]  = { from.x, from.y, from.z };
    float d[3]  = { dir.x, dir.y, dir.z };
    *enter = -1e9f;
    *leave =  1e9f;
    for (int axis = 0; axis < 3; axis++) {
        if (fabsf(d[axis]) < 1e-6f)
            continue;   /* parallel: the point is inside this slab (it was found inside the box) */
        float t0 = (lo[axis] - o[axis]) / d[axis];
        float t1 = (hi[axis] - o[axis]) / d[axis];
        *enter = fmaxf(*enter, fminf(t0, t1));
        *leave = fminf(*leave, fmaxf(t0, t1));
    }
}

/* Moves a distance along the eye line out of any object it's inside: toward
 * the player (`toward_player`), to that object's near side, or away from
 * them, to its far side. A few passes, since objects can touch or overlap. */
static float step_out_of_objects(Vec3 subject, Vec3 dir, float distance, bool toward_player)
{
    for (int pass = 0; pass < 4; pass++) {
        Box hit;
        if (!world_object_at(vec3_add(subject, vec3_scale(dir, distance)), CAMERA_COLLISION_RADIUS, &hit))
            break;
        float enter, leave;
        line_through_box(subject, dir, hit, CAMERA_COLLISION_RADIUS, &enter, &leave);
        distance = toward_player ? fmaxf(enter, 0.0f) : leave;
    }
    return distance;
}

/* The eye never sits inside an object. An object may be between the player
 * and the eye (a platform in the shot is fine); only when the eye itself
 * would end up inside one does it jump THROUGH it, the same tick, to the
 * object's near side (the player's side), along its line to the player, so
 * the player stays on the same screen spot and the framing is untouched.
 * When the wanted spot is free again, the eye eases back out (speed up,
 * cruise, brake, like the auto-tilt) instead of popping; if that path takes
 * it into an object, it jumps through to the far side rather than stopping
 * inside. Zones never count. */
static void keep_eye_clear(Camera *c, float dt)
{
    Vec3  to_eye = vec3_sub(c->position, c->subject);
    float wanted = vec3_length(to_eye);
    if (wanted < 1e-4f)
        return;
    Vec3  dir     = vec3_scale(to_eye, 1.0f / wanted);
    float allowed = step_out_of_objects(c->subject, dir, wanted, true);
    bool  blocked = allowed < wanted - 1e-4f;

    if (allowed <= c->eye_distance || !c->pulled_in) {
        /* The wanted spot is inside an object nearer than we are (jump in
         * now), or we're not recovering: simply sit where allowed. */
        c->eye_distance = allowed;
        c->return_speed = 0.0f;
        c->pulled_in    = blocked;
    } else {
        /* Free further out again: ease back toward it. */
        float remaining   = allowed - c->eye_distance;
        float brake_limit = sqrtf(2.0f * CAMERA_RETURN_ACCEL * remaining);
        c->return_speed = fminf(c->return_speed + CAMERA_RETURN_ACCEL * dt,
                                fminf(CAMERA_RETURN_SPEED, brake_limit));
        float next = c->eye_distance + c->return_speed * dt;
        next = fminf(step_out_of_objects(c->subject, dir, next, false), allowed);
        if (next >= allowed) {
            next            = allowed;
            c->return_speed = 0.0f;
            c->pulled_in    = blocked;
        }
        c->eye_distance = next;
    }

    Vec3 look = vec3_sub(c->target, c->position);   /* keep looking the same way */
    c->position = vec3_add(c->subject, vec3_scale(dir, c->eye_distance));
    c->target   = vec3_add(c->position, look);
}

static void auto_pitch(Camera *c, const Input *in, float dt)
{
    bool touched = in->look.x != 0.0f || in->look.y != 0.0f || in->recenter_pressed;
    if (touched) {
        c->hands_off_time   = 0.0f;
        c->auto_pitch_speed = 0.0f;   /* the player took over: stop at once */
        return;
    }
    c->hands_off_time = fminf(c->hands_off_time + dt, CAMERA_AUTO_PITCH_DELAY);
    if (c->hands_off_time < CAMERA_AUTO_PITCH_DELAY)
        return;

    float goal      = clampf(CAMERA_AUTO_PITCH_DEG * (M3D_PI / 180.0f),
                             CAMERA_PITCH_MIN, CAMERA_PITCH_MAX);
    float remaining = fabsf(goal - c->pitch);

    /* Ease in: speed up gradually. Ease out: never go faster than the speed
     * we could still brake from and stop exactly at the goal. (From physics:
     * stopping from speed v at deceleration a takes a distance of v^2 / 2a.) */
    float brake_limit = sqrtf(2.0f * CAMERA_AUTO_PITCH_ACCEL * remaining);
    c->auto_pitch_speed = fminf(c->auto_pitch_speed + CAMERA_AUTO_PITCH_ACCEL * dt,
                                fminf(CAMERA_AUTO_PITCH_SPEED, brake_limit));

    float step = c->auto_pitch_speed * dt;
    if (step >= remaining) {
        c->pitch            = goal;   /* arrived: settle exactly, at rest */
        c->auto_pitch_speed = 0.0f;
    } else {
        c->pitch += goal > c->pitch ? step : -step;
    }
}

/* A rectangle on screen, in NDC. */
typedef struct {
    Vec2 min, max;
} ScreenBox;

/* Window fraction (0 = left/bottom, 1 = right/top) -> NDC (-1 .. 1). */
static float window_to_ndc(float fraction)
{
    return 2.0f * fraction - 1.0f;
}

static ScreenBox screen_box(float left, float right, float bottom, float top)
{
    ScreenBox box;
    box.min = vec2_make(window_to_ndc(left),  window_to_ndc(bottom));
    box.max = vec2_make(window_to_ndc(right), window_to_ndc(top));
    return box;
}

/* Where a stopped player may sit without the camera moving. */
static ScreenBox resting_zone(void)
{
    return screen_box(THIRD + CAMERA_ZONE_INSET, 2.0f * THIRD - CAMERA_ZONE_INSET,
                      THIRD + CAMERA_ZONE_INSET, CAMERA_ZONE_TOP);
}

/* How far a moving player may drift before pushing the camera along: the
 * resting zone grown by CAMERA_ZONE_INSET on every side. */
static ScreenBox running_bound(void)
{
    return screen_box(THIRD, 2.0f * THIRD,
                      THIRD, CAMERA_ZONE_TOP + CAMERA_ZONE_INSET);
}

static Vec2 clamp_to_box(Vec2 p, ScreenBox box)
{
    return vec2_make(clampf(p.x, box.min.x, box.max.x),
                     clampf(p.y, box.min.y, box.max.y));
}

/* How much of the player's horizontal motion goes across the screen:
 * -1 = straight left, +1 = straight right, 0 = straight toward/away from the
 * camera (or no horizontal motion at all, like a jump in place). */
static float lateral_share(Vec3 moved_by, Vec3 right)
{
    Vec3  flat = vec3_make(moved_by.x, 0.0f, moved_by.z);
    float len  = vec3_length(flat);
    if (len < STILL_EPSILON)
        return 0.0f;
    return vec3_dot(flat, right) / len;   /* right is horizontal and unit length */
}

/* Back-quarter swing: on a sideways run, slowly turn the camera toward
 * CAMERA_SWING_OFFSET off directly-behind the player's motion, staying on the
 * side it's already on. A side-on view becomes a view down the run, without
 * ever snapping squarely behind. Inside that back quarter, nothing happens. */
static void swing_toward_back_quarter(Camera *c, Vec3 moved_by, float lateral, float dt)
{
    if (lateral == 0.0f)
        return;
    float heading = atan2f(moved_by.x, moved_by.z);    /* same convention as facing_yaw */
    float behind  = wrap_angle(heading + M3D_PI);      /* camera yaw directly behind */
    float off     = wrap_angle(c->yaw - behind);       /* signed: which side we're on */
    if (fabsf(off) <= CAMERA_SWING_OFFSET)
        return;
    float goal = behind + (off > 0.0f ? CAMERA_SWING_OFFSET : -CAMERA_SWING_OFFSET);
    c->yaw = approach_angle(c->yaw, goal, CAMERA_SWING_SPEED * fabsf(lateral) * dt);
}

/* Step 5: the framing rules (see the prompt above). */
static void apply_framing_rules(Camera *c, bool subject_moving, float lateral, float dt)
{
    if (c->recentering) {
        /* The glide is over once every part of the shot has arrived; from
         * then on the normal zone rules apply, starting from center. */
        c->framing = ease_toward_vec2(c->framing, vec2_make(0.0f, 0.0f), CAMERA_RECENTER_RATE, dt);
        if (c->framing.x == 0.0f && c->framing.y == 0.0f &&
            c->depth == c->distance && c->yaw == c->recenter_yaw)
            c->recentering = false;
    } else if (!subject_moving) {
        /* The nearest point of the resting zone. If the player is inside the
         * zone this IS the player, so nothing moves: the shot holds. If they
         * stopped outside it, the camera drifts until they're on its edge. */
        Vec2 edge = clamp_to_box(c->framing, resting_zone());
        c->framing = ease_toward_vec2(c->framing, edge, CAMERA_SETTLE_RATE, dt);
    } else if (lateral != 0.0f) {
        /* Lead room: on a sideways run, work the player toward the TRAILING
         * edge (running right -> left thirds line), so the open screen is in
         * the direction they're heading and upcoming obstacles stay visible. */
        ScreenBox bound = running_bound();
        float trailing_edge = lateral > 0.0f ? bound.min.x : bound.max.x;
        c->framing.x = ease_toward(c->framing.x, trailing_edge,
                                   CAMERA_LEAD_RATE * fabsf(lateral), dt);
    }

    /* Hard limit, always. Running toward/away from the camera, the player may
     * drift out to the running bound but never past it; past that, the camera
     * is pushed along. (Across the screen, lead room already stays inside.) */
    c->framing = clamp_to_box(c->framing, running_bound());
}

/* The highest the player may sit on screen (NDC y) before the eye would
 * drop below CAMERA_MIN_HEIGHT above their feet. The eye's height relative
 * to the feet is TARGET_HEIGHT - lift*cos(pitch) + depth*sin(pitch), solved
 * for lift (meters), then converted to NDC. */
static float max_framing_y(const Camera *c, float meters_per_ndc_y)
{
    float max_lift = (CAMERA_TARGET_HEIGHT - CAMERA_MIN_HEIGHT + c->depth * sinf(c->pitch))
                     / cosf(c->pitch);
    return max_lift / meters_per_ndc_y;
}

void camera_init(Camera *c, Vec3 follow_point)
{
    c->yaw         = 0.0f;   /* on +Z, looking toward -Z */
    c->pitch       = CAMERA_PITCH_DEFAULT;
    c->distance    = CAMERA_DISTANCE;
    c->depth       = CAMERA_DISTANCE;
    c->framing     = vec2_make(0.0f, 0.0f);
    c->subject     = subject_point(follow_point);
    c->recentering = false;
    c->recenter_yaw = 0.0f;
    c->hands_off_time = 0.0f;   /* the countdown starts when the game does */
    c->auto_pitch_speed = 0.0f;
    /* The aspect ratio only matters for a non-zero framing, which is 0 here. */
    place_camera(c, 1.0f);
    c->eye_distance = vec3_length(vec3_sub(c->position, c->subject));
    c->pulled_in    = false;
    c->return_speed = 0.0f;
    keep_eye_clear(c, 0.0f);
}

void camera_update(Camera *c, const Input *in, Vec3 follow_point, float follow_facing,
                   bool pan_locked, float aspect, float dt)
{
    /* 1. Did the player move since last tick? And start a recenter glide
     *    toward the shot from behind the player (opposite their facing). */
    Vec3 subject  = subject_point(follow_point);
    Vec3 moved_by = vec3_sub(subject, c->subject);
    bool subject_moving = vec3_length(moved_by) > STILL_EPSILON;
    c->subject = subject;
    if (in->recenter_pressed) {
        c->recentering  = true;
        c->recenter_yaw = wrap_angle(follow_facing + M3D_PI);
    }

    /* 2. Orbit around the player. Mid-recenter, the stick turns the glide's
     *    goal along with the view, so the two never fight. Otherwise a
     *    sideways run slowly swings the camera toward the back quarter,
     *    except in a locked-pan zone. After a while hands-off, the pitch also
     *    tilts to its preferred angle (in a locked-pan zone too). */
    float yaw_before = c->yaw;
    orbit(c, in, dt);
    float lateral = 0.0f;   /* sideways effects are off during a recenter glide */
    if (!c->recentering)
        lateral = lateral_share(moved_by, camera_basis(c->yaw, c->pitch).right);
    if (c->recentering) {
        c->recenter_yaw = wrap_angle(c->recenter_yaw + wrap_angle(c->yaw - yaw_before));
        c->yaw = ease_toward_angle(c->yaw, c->recenter_yaw, CAMERA_RECENTER_RATE, dt);
    } else if (!pan_locked) {
        swing_toward_back_quarter(c, moved_by, lateral, dt);
    }
    auto_pitch(c, in, dt);
    Basis b = camera_basis(c->yaw, c->pitch);

    /* 3. Hold still: with the eye fixed, the player's motion changes where
     *    they sit relative to it. Work in meters, since NDC depends on depth.
     *    Mid-recenter the camera rides along with the player instead, so their
     *    running can't stop the glide from finishing. Sideways motion is left
     *    out on purpose: horizontally the camera keeps pace, and the lead-room
     *    rule (step 5) decides where the player sits across the screen. */
    Vec2  scale = meters_per_ndc(c->depth, aspect);
    float side  = c->framing.x * scale.x;
    float lift  = c->framing.y * scale.y;
    if (!c->recentering) {
        lift     += vec3_dot(moved_by, b.up);
        c->depth += vec3_dot(moved_by, b.forward);
    }

    /* 4. Depth lag: while the player moves, the distance catches back up a
     *    little late, which lets you feel them running toward or away from you.
     *    It freezes when they stop, so a still player means a still camera. */
    if (c->recentering)
        c->depth = ease_toward(c->depth, c->distance, CAMERA_RECENTER_RATE, dt);
    else if (subject_moving)
        c->depth = ease_toward(c->depth, c->distance, CAMERA_FOLLOW_RATE, dt);

    scale = meters_per_ndc(c->depth, aspect);
    c->framing = vec2_make(side / scale.x, lift / scale.y);

    /* 5. Zone rules, then keep the eye out of the floor. */
    apply_framing_rules(c, subject_moving, lateral, dt);
    float max_y = max_framing_y(c, scale.y);
    if (c->framing.y > max_y)
        c->framing.y = max_y;

    /* 6. Derive the eye from the framing, then keep it out of objects. */
    place_camera(c, aspect);
    keep_eye_clear(c, dt);
}

float camera_yaw(const Camera *c)
{
    return c->yaw;
}

Mat4 camera_view(const Camera *c)
{
    return mat4_look_at(c->position, c->target, vec3_make(0.0f, 1.0f, 0.0f));
}

Mat4 camera_projection(const Camera *c, float aspect)
{
    (void)c;   /* every camera shares the same lens for now */
    float fovy_rad = CAMERA_FOV_DEG * (M3D_PI / 180.0f);
    return mat4_perspective(fovy_rad, aspect, CAMERA_NEAR, CAMERA_FAR);
}