summaryrefslogtreecommitdiff
path: root/platformer/src/camera.c
blob: 8f436f543523225a26bea171f17e55fa7268026a (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
/*
 * ============================================================
 * 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).
 *
 *   - camera_update(c, in, follow_point, follow_facing, 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.
 *       3. Hold still (except while recentering): the camera does NOT follow
 *          by default. Project how far the subject moved onto the camera's
 *          right/up/forward axes. Right/up change where they sit on screen, and
 *          forward changes `depth`.
 *       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.
 *            always      -> hard clamp framing to the running bound. While moving,
 *                           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).
 *
 * NOT IN SCOPE: Camera collision, AUTOMATIC rotate-behind-the-player, shake,
 *              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.
 * ============================================================
 */

#include "camera.h"
#include "config.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);
}

/* 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));
}

/* Step 5: the framing rules (see the prompt above). */
static void apply_framing_rules(Camera *c, bool subject_moving, 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);
    }

    /* Hard limit, always. While running, the player may drift out to the
     * running bound but never past it; past that, the camera is pushed along. */
    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;
    /* The aspect ratio only matters for a non-zero framing, which is 0 here. */
    place_camera(c, 1.0f);
}

void camera_update(Camera *c, const Input *in, Vec3 follow_point, float follow_facing,
                   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. */
    float yaw_before = c->yaw;
    orbit(c, in, dt);
    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);
    }
    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. */
    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) {
        side     += vec3_dot(moved_by, b.right);
        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, 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. */
    place_camera(c, aspect);
}

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);
}