diff options
Diffstat (limited to '')
| -rw-r--r-- | platformer/.gitignore | 3 | ||||
| -rw-r--r-- | platformer/README.md | 189 | ||||
| -rw-r--r-- | platformer/src/camera.c | 351 | ||||
| -rw-r--r-- | platformer/src/camera.h | 90 | ||||
| -rw-r--r-- | platformer/src/config.h | 153 | ||||
| -rw-r--r-- | platformer/src/controls.c | 281 | ||||
| -rw-r--r-- | platformer/src/controls.h | 66 | ||||
| -rw-r--r-- | platformer/src/main.c | 174 | ||||
| -rw-r--r-- | platformer/src/math3d.h | 273 | ||||
| -rw-r--r-- | platformer/src/physics.c | 82 | ||||
| -rw-r--r-- | platformer/src/physics.h | 48 | ||||
| -rw-r--r-- | platformer/src/player.c | 225 | ||||
| -rw-r--r-- | platformer/src/player.h | 73 | ||||
| -rw-r--r-- | platformer/src/render.c | 380 | ||||
| -rw-r--r-- | platformer/src/render.h | 40 | ||||
| -rw-r--r-- | platformer/src/window.c | 175 | ||||
| -rw-r--r-- | platformer/src/window.h | 60 | ||||
| -rw-r--r-- | platformer/src/world.c | 64 | ||||
| -rw-r--r-- | platformer/src/world.h | 48 |
19 files changed, 2775 insertions, 0 deletions
diff --git a/platformer/.gitignore b/platformer/.gitignore new file mode 100644 index 0000000..a64aa5d --- /dev/null +++ b/platformer/.gitignore @@ -0,0 +1,3 @@ +# Build output +/build/ +/platformer diff --git a/platformer/README.md b/platformer/README.md new file mode 100644 index 0000000..f97c9dd --- /dev/null +++ b/platformer/README.md @@ -0,0 +1,189 @@ +# platformer + +A small 3D platformer written from scratch in C. The only libraries are GLFW, GLEW and OpenGL. + +**Current scope:** a blank, flat world, one character (a box with a drop shadow), a third-person +camera, and a gamepad. That's everything. The only goal right now is to **dial in character movement**: +running, turning, jumping and falling should feel good before anything else gets built. + +--- + +## Guiding principles + +These rules apply to every change. If a change breaks one, it needs a very good reason. + +1. **Minimal files.** Each file has one purpose that you can explain in a sentence (`controls.c` reads + the gamepad, `physics.c` applies gravity and collision, and so on). If you can't say what a file + is for, it shouldn't exist. If a file starts doing two jobs, split it. +2. **Minimal dependencies.** We build from scratch on purpose. The runtime needs GLFW (window + gamepad), + GLEW (OpenGL function loading), OpenGL, and the C standard library, and nothing else. There are no + math libraries, no engines and no asset pipelines. This is deliberately the opposite of UE5-style + bloat: we should understand every line that runs each frame. +3. **Minimal scope.** Start super small and grow one piece at a time. Today it's a blank world plus + movement. Levels, enemies, audio and the rest wait until movement feels right. +4. **Readable implementation.** Someone with ~junior gamedev knowledge should be able to read any file + top to bottom and follow it. That means plain C99, short functions, descriptive names, a comment on + every *why*, and no clever macros or hidden control flow. + +## Inspiration: Super Mario 64 + +SM64 is the reference point for both **what** we build and **how** we build it. + +**Scope.** Before SM64 had levels, its team spent a long time in a plain test space getting Mario's +movement and the camera to feel right. We're following the same order: the blank world *is* the +game until the controls feel great. + +**Development approach.** These ideas come from SM64's design: +- **A small, purpose-built engine.** Write only what the game needs, and nothing general-purpose "just in case". +- **Fixed-rate simulation.** Game logic runs at a fixed tick rate that doesn't depend on the render + frame rate. SM64 ran its logic at 30 Hz. We use **60 Hz** because modern displays and gamepads make + the lower input latency noticeable, and the per-tick math stays the same either way. +- **An explicit player state machine.** SM64 has Mario "actions" (idle, walking, jumping, and so on). + We start with four states (`IDLE`, `RUN`, `JUMP`, `FALL`) and add more only when a move requires it. +- **Analog-magnitude movement.** How far you push the stick sets how fast you move. A radial deadzone + keeps the full 0..1 range usable. +- **Camera-relative controls.** "Up" on the stick means "away from the camera". The player orbits + the camera with the right stick. +- **A framing camera, not a leash.** Like Lakitu, the camera doesn't pin the player to the center of + the screen. A player standing inside the resting zone leaves the camera completely still. The zone + sits 5% inside the rule-of-thirds lines, except that its top edge is at half the window height, which + keeps the view ahead open for upcoming obstacles. While running, they can drift 5% past the zone + (to the thirds lines at the sides and bottom, and just above halfway at the top). When they stop, + the camera eases until they sit on the zone's edge. Off-center shots are intentional: they're + where the cinematic feel comes from. Clicking the right stick glides the camera behind the player + with them centered, and the zone rules pick up again from there. +- **A drop shadow for depth.** A dark blob directly under the character is the most important depth + cue in a 3D platformer, and it tells you where you'll land. + +--- + +## Dependencies + +| Library | Why | Gentoo package | +|---|---|---| +| GLFW 3.4 | window, GL context, keyboard, **gamepad** (`glfwGetGamepadState`, with built-in SDL controller mappings) | `media-libs/glfw` | +| GLEW | loads OpenGL 3.3 core functions | `media-libs/glew` | +| OpenGL 3.3 | rendering | `virtual/opengl` | +| libm | `sinf`, `cosf`, `sqrtf`, ... | (libc) | + +Tools: a C99 compiler (`cc`/`gcc`/`clang`), `make`, `pkg-config`. + +## Build & run + +```sh +make # build ./platformer +make run # build and run +make debug # -O0 -g with AddressSanitizer + UBSan +make clean +``` + +## Controls + +The game is designed for a gamepad (Xbox-style layout names; GLFW maps other pads to it). + +| Input | Action | +|---|---| +| Left stick | move (tilt amount = speed, relative to the camera) | +| Right stick | orbit camera (around the player; their spot on screen is kept) | +| Right stick click | recenter: swing the camera behind the player, centered | +| A (south button) | jump (hold longer to jump higher) | +| Back / Select | reset player to spawn | +| Start | quit | + +If a connected pad is ignored, the console prints `"<name>" (GUID ...) has no gamepad mapping`. Add a +mapping line for that GUID to `EXTRA_GAMEPAD_MAPPINGS` in `src/controls.c` (the Xbox Elite Series 2 over +USB is already there). + +**Keyboard fallback** (only active when no gamepad is connected, for testing): WASD = move, +arrow keys = camera, C = recenter camera, Space = jump, R = reset, Esc = quit. + +--- + +## Architecture + +| File | Purpose | +|---|---| +| `src/main.c` | Entry point. Starts every module, runs the fixed-timestep game loop, shuts down. | +| `src/config.h` | All tunable numbers in one place (speeds, gravity, camera, window). **Tune movement here.** | +| `src/math3d.h` | Tiny header-only vector/matrix math (`Vec2`, `Vec3`, `Mat4`). | +| `src/window.c/.h` | The window and OpenGL context (GLFW + GLEW), the clock, and swapping buffers. | +| `src/controls.c/.h` | Reads the gamepad (or keyboard fallback) into one abstract `Input` struct. | +| `src/world.c/.h` | The blank world: ground height and world boundaries. | +| `src/physics.c/.h` | Gravity, velocity integration and ground collision for a generic `Body`. | +| `src/player.c/.h` | The player's state machine. Turns `Input` into running, turning and jumping. | +| `src/camera.c/.h` | Third-person orbit camera that frames the player inside a screen-space zone. | +| `src/render.c/.h` | Draws the ground grid, the player box and its drop shadow. Read-only. | + +**Dependency direction** (arrows mean "includes / calls"; there are no cycles): + +``` +main ──► window, controls, world, player, camera, render +controls ──► window (keyboard fallback needs the window handle) +player ──► physics, world, controls (Input struct only) +physics ──► world +camera ──► controls (Input struct only) +render ──► player, camera, world (reads only, never modifies) +everything ──► config.h, math3d.h +``` + +**One frame:** + +``` +window_poll_events() +while (enough time has built up for a tick): // fixed 60 Hz + controls_poll() -> Input + player_update() (uses Input + the camera's yaw) + camera_update() (re-frames the player's new position) +render_frame() // once per display frame +window_swap() +``` + +**Conventions:** Y is up, right-handed coordinates. 1 unit = 1 meter. Angles are in radians. +`dt` is in seconds. Public functions are named `module_verb` (`player_update`, `camera_yaw`). +A module keeps its private state in `static` variables inside its `.c` file, and there are no +cross-file globals. + +--- + +## Scaffolding workflow (current stage) + +Right now the files contain **prompts, not code**. Each file opens with a comment block made of these sections: + +- `PURPOSE` +- `FITS IN` +- `INTERFACE` (headers) or `IMPLEMENT` (sources) +- `CONVENTIONS` +- `NOT IN SCOPE` +- `DONE WHEN` + +An implementing agent (or person) fills in each file from its prompt. + +Rules for filling in: +1. **Follow the interfaces in the headers exactly.** The names, struct fields and signatures are shared + across files, so changing one breaks the others. If an interface truly has to change, update + every prompt that mentions it. +2. **Keep the prompt block** at the top of each file. It becomes that file's documentation. +3. Respect `NOT IN SCOPE`. Leave it out, even when it's tempting to add. + +Suggested fill-in order (each step can be compiled before moving on): + +1. `config.h`, `math3d.h` +2. `window.c/.h` +3. `controls.c/.h` +4. `world.c/.h` +5. `physics.c/.h` +6. `camera.c/.h` +7. `player.c/.h` +8. `render.c/.h` +9. `main.c` +10. `Makefile` + +## Roadmap (explicitly *not* now) + +- Collision with real geometry (platforms, walls, slopes) +- Loading levels +- SM64-style extra moves: double/triple jump, long jump, wall kick, ground pound +- Character model and animation +- Audio +- On-screen text/HUD +- Interpolating render state between ticks diff --git a/platformer/src/camera.c b/platformer/src/camera.c new file mode 100644 index 0000000..8f436f5 --- /dev/null +++ b/platformer/src/camera.c @@ -0,0 +1,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); +} diff --git a/platformer/src/camera.h b/platformer/src/camera.h new file mode 100644 index 0000000..84897d7 --- /dev/null +++ b/platformer/src/camera.h @@ -0,0 +1,90 @@ +/* + * ============================================================ + * FILE: camera.h + * + * PURPOSE: Public interface for the third-person "framing" camera: it + * orbits the player (right stick), and instead of pinning the player + * to the center of the screen it lets them wander inside a screen- + * space zone, SM64-style. Off-center framing is intentional. + * + * FITS IN: main.c calls camera_update() each tick AFTER player_update(). + * player_update() receives camera_yaw() so "stick up" means "away + * from the camera". render.c reads camera_view()/camera_projection(). + * + * INTERFACE: Use these exact names: + * + * typedef struct Camera { + * Vec3 target; derived look-at point, `distance` ahead of the eye + * float yaw; orbit angle around the player, radians + * float pitch; angle above horizontal, radians + * float distance; resting distance from eye to player, meters + * Vec3 position; derived eye position (recomputed in camera_update) + * Vec2 framing; where the player sits on screen, in NDC: + * (0,0) = center, +x = right, +y = up, edges = +-1 + * float depth; current eye-to-player distance along the view + * direction; eases toward `distance` (follow lag) + * Vec3 subject; the point we frame (player feet + target height) + * as of last tick, to detect whether they moved + * bool recentering; true during the recenter glide + * float recenter_yaw; where the glide is headed: behind the player + * } Camera; + * + * void camera_init(Camera *c, Vec3 follow_point); + * void camera_update(Camera *c, const Input *in, Vec3 follow_point, + * float follow_facing, float aspect, float dt); + * follow_point = the player's feet position; the camera adds + * CAMERA_TARGET_HEIGHT itself. follow_facing = the player's + * facing_yaw, used by recenter to swing behind them. aspect = + * framebuffer width/height, needed because the framing zone is + * defined in screen space. + * float camera_yaw(const Camera *c); + * Mat4 camera_view(const Camera *c); + * Mat4 camera_projection(const Camera *c, float aspect); + * + * YAW CONVENTION (player.c relies on this, so keep it exact): + * position = target + distance * ( sin(yaw)*cos(pitch), + * sin(pitch), + * cos(yaw)*cos(pitch) ) + * So on the ground plane, the camera's + * forward (toward target) = (-sin(yaw), 0, -cos(yaw)) + * right = ( cos(yaw), 0, -sin(yaw)) + * + * Include <stdbool.h>, "math3d.h" and "controls.h". + * + * CONVENTIONS: Include guard: CAMERA_H. + * + * NOT IN SCOPE: Collision with geometry, automatic "behind the player" + * rotation, cutscene/fixed cameras, zoom levels. + * + * DONE WHEN: player.c and render.c can be written against this header alone. + * ============================================================ + */ +#ifndef CAMERA_H +#define CAMERA_H + +#include <stdbool.h> + +#include "controls.h" +#include "math3d.h" + +typedef struct Camera { + Vec3 target; /* derived look-at point, `distance` ahead of the eye */ + float yaw; /* orbit angle around the player, radians */ + float pitch; /* angle above horizontal, radians */ + float distance; /* resting distance from eye to player, meters */ + Vec3 position; /* derived eye position (recomputed in camera_update) */ + Vec2 framing; /* player's screen position in NDC: (0,0) = center, edges = +-1 */ + float depth; /* current eye-to-player distance along the view; eases to `distance` */ + Vec3 subject; /* last tick's framed point (feet + target height) */ + bool recentering; /* gliding to "centered, behind the player" */ + float recenter_yaw; /* the yaw that glide is headed for */ +} Camera; + +void camera_init(Camera *c, Vec3 follow_point); +void camera_update(Camera *c, const Input *in, Vec3 follow_point, float follow_facing, + float aspect, float dt); +float camera_yaw(const Camera *c); +Mat4 camera_view(const Camera *c); +Mat4 camera_projection(const Camera *c, float aspect); + +#endif /* CAMERA_H */ diff --git a/platformer/src/config.h b/platformer/src/config.h new file mode 100644 index 0000000..c71ae35 --- /dev/null +++ b/platformer/src/config.h @@ -0,0 +1,153 @@ +/* + * ============================================================ + * FILE: config.h + * + * PURPOSE: Every tunable number in the game, in one place. When movement + * "feels wrong", this is the first (and usually only) file to edit. + * + * FITS IN: Included by almost every .c file. Contains only #defines, + * with no functions, no types and no includes. + * Nothing in the game should hard-code a number that appears here. + * + * INTERFACE: Plain #define constants, float literals with an `f` suffix. + * Give EVERY constant a one-line comment that says what it + * changes about the *feel*, e.g. "higher = snappier stops". + * Use these exact names (other files depend on them). The + * values are starting points for tuning: + * + * Window + * WINDOW_WIDTH 1280 + * WINDOW_HEIGHT 720 + * WINDOW_TITLE "platformer" + * SKY_COLOR_R/G/B 0.45f 0.65f 0.90f (clear color) + * + * Simulation timing + * TICK_HZ 60 (fixed logic rate; SM64 used 30) + * TICK_DT (1.0f / TICK_HZ) (seconds per tick) + * MAX_FRAME_TIME 0.25f (clamp to avoid a "spiral of death" + * after a stall / breakpoint) + * + * Input + * MOVE_DEADZONE 0.20f (radial, left stick) + * LOOK_DEADZONE 0.20f (radial, right stick) + * + * Player: ground movement + * PLAYER_MAX_SPEED 9.0f m/s at full stick tilt + * PLAYER_GROUND_ACCEL 30.0f m/s^2 speeding up toward target speed + * PLAYER_GROUND_FRICTION 40.0f m/s^2 slowing down with no input + * PLAYER_TURN_RATE 12.0f rad/s max facing rotation on ground + * + * Player: air movement + * PLAYER_AIR_CONTROL 0.30f 0..1 multiplier on accel + turn rate in air + * PLAYER_JUMP_VELOCITY 14.0f m/s upward at jump start (~2.4 m apex) + * PLAYER_JUMP_CUT 0.50f vel.y multiplier when A released while rising + * + * Physics + * GRAVITY 40.0f m/s^2 (stronger than real 9.8 on purpose: + * platformers feel floaty with real gravity) + * TERMINAL_VELOCITY 50.0f m/s max fall speed + * + * Player: size (used by render, and later by collision) + * PLAYER_HALF_WIDTH 0.4f m + * PLAYER_HEIGHT 1.6f m (body.pos is the player's FEET) + * + * Camera + * CAMERA_DISTANCE 10.0f m from target + * CAMERA_TARGET_HEIGHT 1.0f m above player's feet to look at + * CAMERA_PITCH_DEFAULT 0.35f rad above horizontal + * CAMERA_PITCH_MIN 0.05f rad + * CAMERA_PITCH_MAX 1.20f rad + * CAMERA_YAW_SPEED 2.5f rad/s at full right-stick tilt + * CAMERA_PITCH_SPEED 1.5f rad/s at full right-stick tilt + * CAMERA_FOLLOW_RATE 8.0f 1/s; how fast the camera's DISTANCE catches up + * when the player runs toward/away from it + * CAMERA_ZONE_INSET 0.05f fraction of the window between the resting + * zone and the running bound, on every side + * CAMERA_ZONE_TOP 0.50f window fraction (0 = bottom) of the resting + * zone's top edge; lower = more view ahead + * CAMERA_SETTLE_RATE 3.0f 1/s; how fast the camera re-frames a player + * who stopped outside the resting zone + * CAMERA_RECENTER_RATE 6.0f 1/s; how fast the recenter button swings + * behind the player and centers them + * CAMERA_MIN_HEIGHT 0.5f m; lowest the eye may go above the player's feet + * CAMERA_FOV_DEG 60.0f vertical field of view + * CAMERA_NEAR 0.1f + * CAMERA_FAR 500.0f + * + * World + * WORLD_HALF_EXTENT 100.0f m; the ground is a square of 2x this per side + * GRID_SPACING 1.0f m between grid lines + * GRID_MAJOR_EVERY 10 every Nth line drawn brighter + * + * CONVENTIONS: 1 unit = 1 meter, seconds, radians (degrees only for the FOV, + * converted where it's used). Include guard: CONFIG_H. + * + * NOT IN SCOPE: Runtime config files, command-line parsing, hot-reload. + * + * DONE WHEN: Every constant above exists with a comment, and no other + * file contains a magic number for any of these concepts. + * ============================================================ + */ +#ifndef CONFIG_H +#define CONFIG_H + +/* ---- Window ------------------------------------------------------------ */ +#define WINDOW_WIDTH 1280 /* starting window width, pixels */ +#define WINDOW_HEIGHT 720 /* starting window height, pixels */ +#define WINDOW_TITLE "platformer" /* base title; main.c appends the debug readout */ +#define SKY_COLOR_R 0.45f /* clear color: the "sky" behind everything */ +#define SKY_COLOR_G 0.65f +#define SKY_COLOR_B 0.90f + +/* ---- Simulation timing ------------------------------------------------- */ +#define TICK_HZ 60 /* logic ticks per second; higher = lower input latency (SM64 used 30) */ +#define TICK_DT (1.0f / TICK_HZ) /* seconds per tick; derived, don't edit */ +#define MAX_FRAME_TIME 0.25f /* longest frame we catch up on; stops a "spiral of death" after a stall */ + +/* ---- Input ------------------------------------------------------------- */ +#define MOVE_DEADZONE 0.20f /* left stick radius ignored; higher = less drift, less fine control */ +#define LOOK_DEADZONE 0.20f /* right stick radius ignored; higher = camera harder to nudge */ + +/* ---- Player: ground movement ------------------------------------------- */ +#define PLAYER_MAX_SPEED 9.0f /* m/s at full stick tilt; higher = faster top run speed */ +#define PLAYER_GROUND_ACCEL 30.0f /* m/s^2 toward target speed; higher = snappier starts */ +#define PLAYER_GROUND_FRICTION 40.0f /* m/s^2 slowdown with stick released; higher = snappier stops */ +#define PLAYER_TURN_RATE 12.0f /* rad/s max facing rotation on ground; higher = tighter turns */ + +/* ---- Player: air movement ---------------------------------------------- */ +#define PLAYER_AIR_CONTROL 0.30f /* 0..1 multiplier on accel + turn rate in air; higher = more steerable jumps */ +#define PLAYER_JUMP_VELOCITY 14.0f /* m/s upward at jump start; higher = taller jumps (~2.4 m apex at 14) */ +#define PLAYER_JUMP_CUT 0.50f /* vel.y multiplier on early A release; lower = shorter taps */ + +/* ---- Physics ----------------------------------------------------------- */ +#define GRAVITY 40.0f /* m/s^2; stronger than real 9.8 on purpose, real gravity feels floaty */ +#define TERMINAL_VELOCITY 50.0f /* m/s max fall speed; lower = long falls feel more controlled */ + +/* ---- Player: size (used by render, and later by collision) ------------- */ +#define PLAYER_HALF_WIDTH 0.4f /* m; half the box's width/depth */ +#define PLAYER_HEIGHT 1.6f /* m; box height (body.pos is the player's FEET) */ + +/* ---- Camera ------------------------------------------------------------ */ +#define CAMERA_DISTANCE 10.0f /* m from target; higher = see more, player looks smaller */ +#define CAMERA_TARGET_HEIGHT 1.0f /* m above player's feet the camera looks at */ +#define CAMERA_PITCH_DEFAULT 0.35f /* rad above horizontal at start */ +#define CAMERA_PITCH_MIN 0.05f /* rad; lowest the camera can swing (just above the ground) */ +#define CAMERA_PITCH_MAX 1.20f /* rad; highest the camera can swing (near top-down) */ +#define CAMERA_YAW_SPEED 2.5f /* rad/s orbit at full right-stick tilt; higher = faster spin */ +#define CAMERA_PITCH_SPEED 1.5f /* rad/s tilt at full right-stick tilt */ +#define CAMERA_FOLLOW_RATE 8.0f /* 1/s; how fast the distance catches up when running toward/away; lower = more lag */ +#define CAMERA_ZONE_INSET 0.05f /* window fraction between resting zone and running bound; higher = tighter zone */ +#define CAMERA_ZONE_TOP 0.50f /* resting zone's top edge (0 = bottom, 1 = top); lower = more view ahead of the player */ +#define CAMERA_SETTLE_RATE 3.0f /* 1/s; re-framing after stopping outside the zone; lower = lazier, more cinematic */ +#define CAMERA_RECENTER_RATE 6.0f /* 1/s; how fast recenter swings behind the player and centers them */ +#define CAMERA_MIN_HEIGHT 0.5f /* m; lowest the eye may sit above the player's feet (keeps it out of the floor) */ +#define CAMERA_FOV_DEG 60.0f /* vertical field of view, degrees; higher = wider, faster-feeling view */ +#define CAMERA_NEAR 0.1f /* m; near clip plane */ +#define CAMERA_FAR 500.0f /* m; far clip plane (must reach past the world edge) */ + +/* ---- World ------------------------------------------------------------- */ +#define WORLD_HALF_EXTENT 100.0f /* m; the ground is a square of 2x this per side */ +#define GRID_SPACING 1.0f /* m between grid lines; the grid is how you read speed */ +#define GRID_MAJOR_EVERY 10 /* every Nth line drawn brighter, for reading distances */ + +#endif /* CONFIG_H */ diff --git a/platformer/src/controls.c b/platformer/src/controls.c new file mode 100644 index 0000000..3bcf7b7 --- /dev/null +++ b/platformer/src/controls.c @@ -0,0 +1,281 @@ +/* + * ============================================================ + * 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_recenter, + * 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 + * recenter = GLFW_GAMEPAD_BUTTON_RIGHT_THUMB (click the right stick) + * 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, C -> recenter camera, 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_recenter, 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, recenter, 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, 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.recenter = state.buttons[GLFW_GAMEPAD_BUTTON_RIGHT_THUMB] == 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.recenter = key_down(GLFW_KEY_C); + 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->recenter_pressed = now.recenter && !s_prev_recenter; + out->quit_pressed = now.quit && !s_prev_quit; + + s_prev_jump = now.jump; + s_prev_reset = now.reset; + s_prev_recenter = now.recenter; + s_prev_quit = now.quit; +} diff --git a/platformer/src/controls.h b/platformer/src/controls.h new file mode 100644 index 0000000..972ce9e --- /dev/null +++ b/platformer/src/controls.h @@ -0,0 +1,66 @@ +/* + * ============================================================ + * FILE: controls.h + * + * PURPOSE: Defines `Input`, the one abstract snapshot of what the player + * is asking for this tick. Gameplay code reads Input and never + * reads a raw device, so the player and camera don't care whether + * a gamepad or the keyboard produced it. + * + * FITS IN: main.c calls controls_poll() once per fixed tick and passes the + * Input to player_update() and camera_update(). + * + * INTERFACE: Use these exact names: + * + * typedef struct Input { + * Vec2 move; left stick after the deadzone. Length is 0..1. + * +x = right, +y = FORWARD (stick pushed up). + * Vec2 look; right stick after the deadzone. Length is 0..1. + * +x = orbit camera right, +y = tilt camera up. + * bool jump_held; A is down this tick + * bool jump_pressed; A went down THIS tick (true for one tick only) + * bool reset_pressed; Back/Select went down this tick (one tick only) + * bool recenter_pressed; right stick click went down this tick (one tick + * only): swing the camera behind the player, centered + * bool quit_pressed; Start (or Esc) went down this tick (one tick only) + * bool using_gamepad; true if a gamepad produced this Input (debug info) + * } Input; + * + * void controls_init(void); call after window_init() + * void controls_poll(Input *out); call once per FIXED TICK (not once per + * frame). The "pressed" edges are + * worked out tick-to-tick, so a press + * is never lost or counted twice. + * + * Include <stdbool.h> and "math3d.h" (for Vec2). + * + * CONVENTIONS: Include guard: CONTROLS_H. + * + * NOT IN SCOPE: Rebinding, multiple players, mouse look, rumble. + * + * DONE WHEN: player.c and camera.c can be written against Input alone, + * without including GLFW. + * ============================================================ + */ +#ifndef CONTROLS_H +#define CONTROLS_H + +#include <stdbool.h> + +#include "math3d.h" + +typedef struct Input { + Vec2 move; /* left stick after deadzone, length 0..1. +x = right, +y = forward */ + Vec2 look; /* right stick after deadzone, length 0..1. +x = orbit right, +y = tilt up */ + bool jump_held; /* A is down this tick */ + bool jump_pressed; /* A went down THIS tick (one tick only) */ + bool reset_pressed; /* Back/Select went down this tick (one tick only) */ + bool recenter_pressed; /* right stick click went down this tick (one tick only) */ + bool quit_pressed; /* Start (or Esc) went down this tick (one tick only) */ + bool using_gamepad; /* true if a gamepad produced this Input (debug info) */ +} Input; + +void controls_init(void); +void controls_poll(Input *out); + +#endif /* CONTROLS_H */ diff --git a/platformer/src/main.c b/platformer/src/main.c new file mode 100644 index 0000000..8f5e510 --- /dev/null +++ b/platformer/src/main.c @@ -0,0 +1,174 @@ +/* + * ============================================================ + * FILE: main.c + * + * PURPOSE: Entry point. Starts every module, runs the game loop, and shuts + * everything down. It should read like a table of contents for the + * game, with NO gameplay logic of its own. + * + * FITS IN: The top of the dependency graph. Includes window.h, controls.h, + * world.h, player.h, camera.h, render.h, config.h. + * + * IMPLEMENT: + * - Startup (in this order, and if any step fails, clean up what + * already started and return 1): + * window_init() -> controls_init() -> world_init() + * player_init(&player, world_spawn_point()) + * camera_init(&camera, player.body.pos) + * render_init() + * + * - Game loop with a FIXED TIMESTEP + accumulator (explain it in a comment; + * this is the most important idea in the file): + * + * previous = window_time(); accumulator = 0; + * while (!window_should_close()): + * now = window_time(); + * frame_time = now - previous; previous = now; + * if frame_time > MAX_FRAME_TIME: frame_time = MAX_FRAME_TIME + * accumulator += frame_time; + * + * window_poll_events(); + * + * while accumulator >= TICK_DT: // 0, 1 or several ticks + * controls_poll(&input); + * if input.quit_pressed: window_request_close(); + * if input.reset_pressed: + * player_reset(&player, world_spawn_point()); + * camera_init(&camera, player.body.pos); // see WHY below + * player_update(&player, &input, camera_yaw(&camera), TICK_DT); + * camera_update(&camera, &input, player.body.pos, player.facing_yaw, + * window_aspect(), TICK_DT); + * accumulator -= TICK_DT; + * + * render_frame(&camera, &player, window_aspect()); + * window_swap(); + * + * WHY the fixed timestep: the game behaves the same (identical jump + * height, identical speeds) no matter the monitor's refresh rate or a + * dropped frame, which is exactly what you need when tuning movement. SM64 + * ran logic at 30 Hz; we use TICK_HZ (60). + * WHY player before camera: the camera then follows where the player IS, + * not where it was a tick ago. SM64 updates Mario before the camera too. + * WHY reset the camera too: the camera frames the player by tracking how + * far they moved each tick, so a teleport back to spawn would look like a + * 100 m sprint. Re-initializing gives a clean, centered start instead. + * + * - Debug readout for tuning (a few times per second, not every frame): + * window_set_title() with something like + * "platformer | RUN | speed 7.42 m/s | y 1.83 | pad" + * using player_state_name(), forward_speed, body.pos.y and + * input.using_gamepad. This is our "HUD" until text rendering exists. + * + * - Shutdown in reverse order: render_shutdown() -> window_shutdown(). + * + * CONVENTIONS: `int main(void)`. Game objects (Player, Camera, Input) are + * local variables in main, passed by pointer. No globals. + * + * NOT IN SCOPE: Menus, pause, command-line args, state interpolation. + * + * DONE WHEN: `make run` opens the window. The player can run, turn and jump + * with a gamepad, the camera orbits and frames them (right stick + * click recenters behind them), Back resets, Start quits, and + * the title bar shows live state/speed. + * ============================================================ + */ + +#include <stdio.h> + +#include "camera.h" +#include "config.h" +#include "controls.h" +#include "player.h" +#include "render.h" +#include "window.h" +#include "world.h" + +#define TITLE_UPDATE_INTERVAL 0.25 /* seconds between debug title refreshes */ + +/* Our "HUD" until text rendering exists: live state in the title bar. + * Updating a few times per second keeps it readable (and cheap). */ +static void update_debug_title(const Player *player, const Input *input) +{ + char title[128]; + snprintf(title, sizeof title, "%s | %s | speed %.2f m/s | y %.2f | %s", + WINDOW_TITLE, + player_state_name(player->state), + player->forward_speed, + player->body.pos.y, + input->using_gamepad ? "pad" : "keyboard"); + window_set_title(title); +} + +int main(void) +{ + if (!window_init()) + return 1; + controls_init(); + world_init(); + + Player player; + player_init(&player, world_spawn_point()); + Camera camera; + camera_init(&camera, player.body.pos); + + if (!render_init()) { + window_shutdown(); + return 1; + } + + /* FIXED TIMESTEP with an accumulator. Real time comes in uneven chunks + * (one display frame at a time), but the game logic always advances in + * exact TICK_DT steps. Each frame adds the elapsed time to the + * accumulator, then runs as many whole ticks as fit (0, 1 or several); + * the leftover carries into the next frame. The payoff: identical jump + * heights and speeds no matter the monitor's refresh rate or a dropped + * frame, which is exactly what you need when tuning movement. SM64 ran its + * logic at 30 Hz; we use TICK_HZ. */ + Input input = { 0 }; + double previous = window_time(); + double accumulator = 0.0; + double last_title_time = 0.0; + + while (!window_should_close()) { + double now = window_time(); + double frame_time = now - previous; + previous = now; + /* After a stall (breakpoint, window drag) don't try to simulate the + * whole gap at once: that would take even longer and fall further behind. */ + if (frame_time > MAX_FRAME_TIME) + frame_time = MAX_FRAME_TIME; + accumulator += frame_time; + + window_poll_events(); + + while (accumulator >= TICK_DT) { + controls_poll(&input); + if (input.quit_pressed) + window_request_close(); + if (input.reset_pressed) { + /* The camera tracks per-tick movement, so a teleport needs a + * fresh camera rather than a 100 m "sprint" to follow. */ + player_reset(&player, world_spawn_point()); + camera_init(&camera, player.body.pos); + } + /* Player before camera, so the camera follows where the player IS, + * not where it was a tick ago. SM64 updates Mario before the camera too. */ + player_update(&player, &input, camera_yaw(&camera), TICK_DT); + camera_update(&camera, &input, player.body.pos, player.facing_yaw, + window_aspect(), TICK_DT); + accumulator -= TICK_DT; + } + + render_frame(&camera, &player, window_aspect()); + window_swap(); + + if (now - last_title_time >= TITLE_UPDATE_INTERVAL) { + update_debug_title(&player, &input); + last_title_time = now; + } + } + + render_shutdown(); + window_shutdown(); + return 0; +} diff --git a/platformer/src/math3d.h b/platformer/src/math3d.h new file mode 100644 index 0000000..e0f89a5 --- /dev/null +++ b/platformer/src/math3d.h @@ -0,0 +1,273 @@ +/* + * ============================================================ + * FILE: math3d.h + * + * PURPOSE: The small amount of vector/matrix math the game needs, written + * by hand so we don't pull in a math library. + * + * FITS IN: Header-only (every function is `static inline`). Included by + * any file that does math. Depends only on <math.h>. + * + * INTERFACE: Use these exact names: + * + * Constants + * M3D_PI 3.14159265358979f (C99 doesn't guarantee M_PI) + * + * Types (plain structs, passed and returned BY VALUE since they're small) + * typedef struct { float x, y; } Vec2; + * typedef struct { float x, y, z; } Vec3; + * typedef struct { float m[16]; } Mat4; COLUMN-MAJOR, element (row r, + * col c) is m[c*4 + r], so it can + * go straight to glUniformMatrix4fv + * with transpose = GL_FALSE. + * + * Scalar helpers + * float clampf(float v, float lo, float hi); + * float approachf(float current, float target, float max_step); + * moves current toward target by at most max_step, never overshoots. + * (Used for acceleration/friction.) + * float wrap_angle(float a); + * returns a in (-PI, PI]. + * float approach_angle(float current, float target, float max_step); + * like approachf but takes the SHORT way around the circle. + * (Used for turning the player.) + * + * Vec2 + * Vec2 vec2_make(float x, float y); + * float vec2_length(Vec2 v); + * + * Vec3 + * Vec3 vec3_make(float x, float y, float z); + * Vec3 vec3_add(Vec3 a, Vec3 b); + * Vec3 vec3_sub(Vec3 a, Vec3 b); + * Vec3 vec3_scale(Vec3 v, float s); + * float vec3_dot(Vec3 a, Vec3 b); + * Vec3 vec3_cross(Vec3 a, Vec3 b); + * float vec3_length(Vec3 v); + * Vec3 vec3_normalize(Vec3 v); returns (0,0,0) for zero-length input + * Vec3 vec3_lerp(Vec3 a, Vec3 b, float t); + * + * Mat4 + * Mat4 mat4_identity(void); + * Mat4 mat4_mul(Mat4 a, Mat4 b); result = a * b (b is applied first) + * Mat4 mat4_translate(Vec3 t); + * Mat4 mat4_scale(Vec3 s); + * Mat4 mat4_rotate_y(float angle); rotates +Z toward +X, i.e. + * (0,0,1) -> (sin a, 0, cos a) + * Mat4 mat4_perspective(float fovy_rad, float aspect, float near, float far); + * standard OpenGL (gluPerspective) form + * Mat4 mat4_look_at(Vec3 eye, Vec3 target, Vec3 up); + * standard OpenGL (gluLookAt) form + * + * CONVENTIONS: Right-handed, Y up. Radians everywhere. Keep each function a + * few lines with a short comment; this is a learning resource. + * Include guard: MATH3D_H. + * + * NOT IN SCOPE: Quaternions, matrix inverse, SIMD, Vec4, generic N-dim math. + * Add a function only when a caller needs it. + * + * DONE WHEN: All functions above compile cleanly under -std=c99 -Wall + * -Wextra, and mat4_perspective * mat4_look_at produces a + * correct view of the ground grid in render.c. + * ============================================================ + */ +#ifndef MATH3D_H +#define MATH3D_H + +#include <math.h> + +#define M3D_PI 3.14159265358979f /* C99 doesn't guarantee M_PI */ + +typedef struct { float x, y; } Vec2; +typedef struct { float x, y, z; } Vec3; +typedef struct { float m[16]; } Mat4; /* column-major: (row r, col c) = m[c*4 + r] */ + +/* ---- Scalar helpers ---------------------------------------------------- */ + +static inline float clampf(float v, float lo, float hi) +{ + if (v < lo) return lo; + if (v > hi) return hi; + return v; +} + +/* Moves current toward target by at most max_step, never overshooting. + * This is how speeds accelerate and brake at a fixed rate per tick. */ +static inline float approachf(float current, float target, float max_step) +{ + if (current < target) { + current += max_step; + return current > target ? target : current; + } + current -= max_step; + return current < target ? target : current; +} + +/* Returns a in (-PI, PI]. */ +static inline float wrap_angle(float a) +{ + a = fmodf(a + M3D_PI, 2.0f * M3D_PI); /* now in (-2PI, 2PI) */ + if (a <= 0.0f) a += 2.0f * M3D_PI; /* now in (0, 2PI] */ + return a - M3D_PI; +} + +/* Like approachf, but for angles: turns the SHORT way around the circle, + * so facing 170 deg and turning to -170 deg is a 20 deg turn, not 340. */ +static inline float approach_angle(float current, float target, float max_step) +{ + float diff = wrap_angle(target - current); + return wrap_angle(current + clampf(diff, -max_step, max_step)); +} + +/* ---- Vec2 -------------------------------------------------------------- */ + +static inline Vec2 vec2_make(float x, float y) +{ + Vec2 v = { x, y }; + return v; +} + +static inline float vec2_length(Vec2 v) +{ + return sqrtf(v.x * v.x + v.y * v.y); +} + +/* ---- Vec3 -------------------------------------------------------------- */ + +static inline Vec3 vec3_make(float x, float y, float z) +{ + Vec3 v = { x, y, z }; + return v; +} + +static inline Vec3 vec3_add(Vec3 a, Vec3 b) +{ + return vec3_make(a.x + b.x, a.y + b.y, a.z + b.z); +} + +static inline Vec3 vec3_sub(Vec3 a, Vec3 b) +{ + return vec3_make(a.x - b.x, a.y - b.y, a.z - b.z); +} + +static inline Vec3 vec3_scale(Vec3 v, float s) +{ + return vec3_make(v.x * s, v.y * s, v.z * s); +} + +static inline float vec3_dot(Vec3 a, Vec3 b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +static inline Vec3 vec3_cross(Vec3 a, Vec3 b) +{ + return vec3_make(a.y * b.z - a.z * b.y, + a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x); +} + +static inline float vec3_length(Vec3 v) +{ + return sqrtf(vec3_dot(v, v)); +} + +/* Returns (0,0,0) for a zero-length input instead of dividing by zero. */ +static inline Vec3 vec3_normalize(Vec3 v) +{ + float len = vec3_length(v); + if (len <= 0.0f) return vec3_make(0.0f, 0.0f, 0.0f); + return vec3_scale(v, 1.0f / len); +} + +/* t = 0 gives a, t = 1 gives b. */ +static inline Vec3 vec3_lerp(Vec3 a, Vec3 b, float t) +{ + return vec3_add(a, vec3_scale(vec3_sub(b, a), t)); +} + +/* ---- Mat4 -------------------------------------------------------------- */ + +static inline Mat4 mat4_identity(void) +{ + Mat4 r = {{ 0 }}; + r.m[0] = r.m[5] = r.m[10] = r.m[15] = 1.0f; + return r; +} + +/* result = a * b, so b is applied to a point first, then a. */ +static inline Mat4 mat4_mul(Mat4 a, Mat4 b) +{ + Mat4 r; + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + float sum = 0.0f; + for (int k = 0; k < 4; k++) + sum += a.m[k * 4 + row] * b.m[col * 4 + k]; + r.m[col * 4 + row] = sum; + } + } + return r; +} + +/* The translation lives in the last column. */ +static inline Mat4 mat4_translate(Vec3 t) +{ + Mat4 r = mat4_identity(); + r.m[12] = t.x; + r.m[13] = t.y; + r.m[14] = t.z; + return r; +} + +static inline Mat4 mat4_scale(Vec3 s) +{ + Mat4 r = mat4_identity(); + r.m[0] = s.x; + r.m[5] = s.y; + r.m[10] = s.z; + return r; +} + +/* Rotates around +Y, turning +Z toward +X: (0,0,1) -> (sin a, 0, cos a). + * This matches the player's facing vector (sin(yaw), 0, cos(yaw)). */ +static inline Mat4 mat4_rotate_y(float angle) +{ + float c = cosf(angle), s = sinf(angle); + Mat4 r = mat4_identity(); + r.m[0] = c; /* row 0, col 0 */ + r.m[8] = s; /* row 0, col 2 */ + r.m[2] = -s; /* row 2, col 0 */ + r.m[10] = c; /* row 2, col 2 */ + return r; +} + +/* Standard OpenGL (gluPerspective) projection. Maps the view frustum to + * clip space, with the camera looking down -Z. */ +static inline Mat4 mat4_perspective(float fovy_rad, float aspect, float near, float far) +{ + float f = 1.0f / tanf(fovy_rad * 0.5f); + Mat4 r = {{ 0 }}; + r.m[0] = f / aspect; + r.m[5] = f; + r.m[10] = (far + near) / (near - far); + r.m[11] = -1.0f; /* row 3, col 2: w = -z */ + r.m[14] = 2.0f * far * near / (near - far); + return r; +} + +/* Standard OpenGL (gluLookAt) view matrix: moves the world so the eye sits + * at the origin looking down -Z, with `up` roughly +Y on screen. */ +static inline Mat4 mat4_look_at(Vec3 eye, Vec3 target, Vec3 up) +{ + Vec3 f = vec3_normalize(vec3_sub(target, eye)); /* forward */ + Vec3 s = vec3_normalize(vec3_cross(f, up)); /* right */ + Vec3 u = vec3_cross(s, f); /* true up */ + Mat4 r = mat4_identity(); + r.m[0] = s.x; r.m[4] = s.y; r.m[8] = s.z; r.m[12] = -vec3_dot(s, eye); + r.m[1] = u.x; r.m[5] = u.y; r.m[9] = u.z; r.m[13] = -vec3_dot(u, eye); + r.m[2] = -f.x; r.m[6] = -f.y; r.m[10] = -f.z; r.m[14] = vec3_dot(f, eye); + return r; +} + +#endif /* MATH3D_H */ diff --git a/platformer/src/physics.c b/platformer/src/physics.c new file mode 100644 index 0000000..b04a78e --- /dev/null +++ b/platformer/src/physics.c @@ -0,0 +1,82 @@ +/* + * ============================================================ + * FILE: physics.c + * + * PURPOSE: Moves a Body forward one fixed tick: gravity, integration, + * landing on the ground, and staying inside the world. + * + * FITS IN: Implements physics.h. Called by player.c inside player_update(), + * AFTER the player has chosen its velocity for this tick. Uses + * world_ground_height() and world_clamp_to_bounds() from world.h. + * + * IMPLEMENT physics_step(b, dt), in this order: + * 1. Gravity: if !b->on_ground, vel.y -= GRAVITY * dt, then clamp vel.y to + * no lower than -TERMINAL_VELOCITY. + * (When on the ground, vel.y is left alone. A jump sets it positive + * before this call, and that's what lifts the body off the ground.) + * 2. Integrate (semi-implicit Euler: velocity was updated first, then position): + * pos += vel * dt + * Add a comment explaining why this order is stable enough for a + * fixed timestep. + * 3. Ground: ground = world_ground_height(pos.x, pos.z). + * if pos.y <= ground: pos.y = ground; if vel.y < 0, vel.y = 0; + * on_ground = true + * else: on_ground = false + * Note: on_ground must become false the moment a jump lifts the body, + * and walking off a ledge will also set it false once terrain exists. + * 4. Bounds: pos = world_clamp_to_bounds(pos). If x or z got clamped, + * zero that velocity component so the body doesn't "stick" against + * the edge while pushing into it. + * + * CONVENTIONS: dt is always TICK_DT in practice, but use the parameter rather + * than the constant so the function stays general. + * + * NOT IN SCOPE: Friction/acceleration (that's player movement *intent*, in + * player.c), wall/ceiling collision, slopes, sub-stepping. + * + * DONE WHEN: A body placed at y = 10 falls, speeds up, lands exactly on + * y = 0 with on_ground = true, and stays there. + * ============================================================ + */ + +#include "config.h" +#include "physics.h" +#include "world.h" + +void physics_step(Body *b, float dt) +{ + /* 1. Gravity. On the ground vel.y is left alone: a jump sets it positive + * before this call, and that's what lifts the body off the ground. */ + if (!b->on_ground) { + b->vel.y -= GRAVITY * dt; + if (b->vel.y < -TERMINAL_VELOCITY) + b->vel.y = -TERMINAL_VELOCITY; + } + + /* 2. Integrate with semi-implicit Euler: velocity was updated above, and + * position now moves with that NEW velocity. Unlike plain Euler (which + * uses the old velocity) this doesn't gain energy over time, and with a + * fixed dt the result is identical every run, so a jump always + * reaches the same height. */ + b->pos = vec3_add(b->pos, vec3_scale(b->vel, dt)); + + /* 3. Ground. Landing snaps the feet to the surface and kills the downward + * speed. on_ground goes false the moment a jump lifts the body (and, + * once terrain exists, when walking off a ledge). */ + float ground = world_ground_height(b->pos.x, b->pos.z); + if (b->pos.y <= ground) { + b->pos.y = ground; + if (b->vel.y < 0.0f) + b->vel.y = 0.0f; + b->on_ground = true; + } else { + b->on_ground = false; + } + + /* 4. Bounds. Zero the velocity into an edge we got clamped against, so + * the body doesn't "stick" to it while pushing into it. */ + Vec3 clamped = world_clamp_to_bounds(b->pos); + if (clamped.x != b->pos.x) b->vel.x = 0.0f; + if (clamped.z != b->pos.z) b->vel.z = 0.0f; + b->pos = clamped; +} diff --git a/platformer/src/physics.h b/platformer/src/physics.h new file mode 100644 index 0000000..580d09b --- /dev/null +++ b/platformer/src/physics.h @@ -0,0 +1,48 @@ +/* + * ============================================================ + * FILE: physics.h + * + * PURPOSE: Public interface for generic physical motion: a `Body` that + * falls, moves and lands on the ground. It knows nothing about + * players or controllers, so enemies and objects can reuse it later. + * + * FITS IN: player.c owns a Body, sets its horizontal velocity from input, + * then calls physics_step() once per tick. physics.c asks world.h + * about the ground and the bounds. + * + * INTERFACE: Use these exact names: + * + * typedef struct Body { + * Vec3 pos; position of the body's FEET (bottom center), meters + * Vec3 vel; velocity, meters/second + * bool on_ground; true if the body ended the last step standing on ground + * } Body; + * + * void physics_step(Body *b, float dt); + * + * Include <stdbool.h> and "math3d.h". + * + * CONVENTIONS: Include guard: PHYSICS_H. + * + * NOT IN SCOPE: Rigid bodies, rotation, mass, forces/impulses API, collision + * between bodies. + * + * DONE WHEN: player.c can move and land using only Body + physics_step. + * ============================================================ + */ +#ifndef PHYSICS_H +#define PHYSICS_H + +#include <stdbool.h> + +#include "math3d.h" + +typedef struct Body { + Vec3 pos; /* position of the body's FEET (bottom center), meters */ + Vec3 vel; /* velocity, meters/second */ + bool on_ground; /* true if the body ended the last step standing on ground */ +} Body; + +void physics_step(Body *b, float dt); + +#endif /* PHYSICS_H */ diff --git a/platformer/src/player.c b/platformer/src/player.c new file mode 100644 index 0000000..ed8da51 --- /dev/null +++ b/platformer/src/player.c @@ -0,0 +1,225 @@ +/* + * ============================================================ + * FILE: player.c + * + * PURPOSE: The heart of the current milestone: how the character runs, + * turns and jumps. Modeled on SM64's approach: an explicit state + * machine, speed that follows the analog stick, and a facing + * direction that turns toward the stick instead of snapping. + * + * FITS IN: Implements player.h. Reads Input (controls.h). Writes the + * Body's velocity, then calls physics_step() (physics.h) to do the + * actual motion. Tunables all come from config.h. + * + * IMPLEMENT: + * - player_init / player_reset: body.pos = spawn, vel = 0, on_ground = true, + * facing_yaw = 0, forward_speed = 0, state = PLAYER_IDLE. + * + * - player_update(p, in, camera_yaw, dt). Use one static helper per state + * (update_idle / update_run / update_jump / update_fall), dispatched by a + * `switch (p->state)`. Keep each helper short. Shared steps: + * + * A. Stick -> world direction (camera-relative). Using camera.h's convention: + * fwd = (-sin(camera_yaw), 0, -cos(camera_yaw)) + * right = ( cos(camera_yaw), 0, -sin(camera_yaw)) + * wish = fwd * in->move.y + right * in->move.x + * mag = vec2_length(in->move) (0..1, already deadzoned) + * wish_yaw = atan2f(wish.x, wish.z) (only meaningful if mag > 0) + * + * B. Ground movement (IDLE / RUN): + * - If mag > 0: facing_yaw = approach_angle(facing_yaw, wish_yaw, + * PLAYER_TURN_RATE * dt); forward_speed = approachf(forward_speed, + * PLAYER_MAX_SPEED * mag, PLAYER_GROUND_ACCEL * dt) + * - Else: forward_speed = approachf(forward_speed, 0, + * PLAYER_GROUND_FRICTION * dt) + * - State: forward_speed > 0 -> RUN, otherwise IDLE. + * + * C. Jump (from IDLE / RUN): if in->jump_pressed and body.on_ground: + * body.vel.y = PLAYER_JUMP_VELOCITY; on_ground = false; state = JUMP. + * + * D. Air movement (JUMP / FALL): the same as B, but turn rate and accel are + * multiplied by PLAYER_AIR_CONTROL, and there's NO friction when the + * stick is released (you keep your momentum, like SM64). + * - Variable jump height: in JUMP, if !in->jump_held and vel.y > 0, + * multiply vel.y by PLAYER_JUMP_CUT ONCE (don't repeat it every tick; + * either switch to FALL right away or keep a flag). Comment WHY: tapping A + * gives a hop, holding it gives a full jump. + * - JUMP -> FALL when vel.y <= 0. + * - FALL -> IDLE/RUN when body.on_ground (landing). + * - If the player is on the ground state-wise but body.on_ground is false + * (walked off an edge, once edges exist) -> FALL. + * + * E. Apply: body.vel.x = sin(facing_yaw) * forward_speed + * body.vel.z = cos(facing_yaw) * forward_speed + * then physics_step(&p->body, dt). + * + * - player_state_name: a switch that returns string literals. + * + * CONVENTIONS: Facing vector = (sin(yaw), 0, cos(yaw)). Speeds are in m/s, + * accelerations in m/s^2, and every one of them multiplies by dt. + * No magic numbers; everything comes from config.h. + * + * NOT IN SCOPE: Double/triple jump, long jump, wall kick, ground pound, + * skidding/turnaround, slopes, coyote time, jump buffering. + * Leave a short comment at the state enum pointing to the + * README roadmap as the place to grow. + * + * DONE WHEN: Small stick tilts walk slowly and full tilt runs at + * PLAYER_MAX_SPEED. Turning is quick but not instant, and letting go + * of the stick brings the player to a short, smooth stop. A tap of A + * gives a short hop and holding A gives a full ~2.4 m jump. The + * player lands cleanly back in IDLE/RUN. + * ============================================================ + */ + +#include "config.h" +#include "player.h" + +/* What the stick is asking for this tick, in world space. */ +typedef struct { + float mag; /* 0..1, how far the stick is pushed */ + float yaw; /* world direction to move in; only meaningful if mag > 0 */ +} Wish; + +static void update_ground(Player *p, const Input *in, Wish wish, float dt); +static void update_fall(Player *p, const Input *in, Wish wish, float dt); + +/* A. Stick -> world direction. "Up" on the stick means "away from the + * camera", so the stick is rotated by the camera's yaw (camera.h's + * convention for forward/right on the ground plane). */ +static Wish compute_wish(const Input *in, float camera_yaw) +{ + Vec3 fwd = vec3_make(-sinf(camera_yaw), 0.0f, -cosf(camera_yaw)); + Vec3 right = vec3_make( cosf(camera_yaw), 0.0f, -sinf(camera_yaw)); + Vec3 dir = vec3_add(vec3_scale(fwd, in->move.y), vec3_scale(right, in->move.x)); + + Wish wish; + wish.mag = vec2_length(in->move); + wish.yaw = atan2f(dir.x, dir.z); /* inverse of facing = (sin(yaw), 0, cos(yaw)) */ + return wish; +} + +/* Turns toward the stick and speeds up toward a speed set by how far it's + * pushed. Shared by ground and air movement; the air passes smaller rates. */ +static void steer(Player *p, Wish wish, float turn_rate, float accel, float dt) +{ + p->facing_yaw = approach_angle(p->facing_yaw, wish.yaw, turn_rate * dt); + p->forward_speed = approachf(p->forward_speed, PLAYER_MAX_SPEED * wish.mag, accel * dt); +} + +/* Standing still vs walking vs running is only a matter of speed. */ +static PlayerState grounded_state(const Player *p) +{ + return p->forward_speed > 0.0f ? PLAYER_RUN : PLAYER_IDLE; +} + +/* B + C. IDLE and RUN: full control, friction when the stick is released, + * and the only place a jump can start. */ +static void update_ground(Player *p, const Input *in, Wish wish, float dt) +{ + /* Walked off an edge (once edges exist): start falling. */ + if (!p->body.on_ground) { + p->state = PLAYER_FALL; + update_fall(p, in, wish, dt); + return; + } + + if (wish.mag > 0.0f) + steer(p, wish, PLAYER_TURN_RATE, PLAYER_GROUND_ACCEL, dt); + else + p->forward_speed = approachf(p->forward_speed, 0.0f, PLAYER_GROUND_FRICTION * dt); + p->state = grounded_state(p); + + if (in->jump_pressed) { + p->body.vel.y = PLAYER_JUMP_VELOCITY; + p->body.on_ground = false; + p->state = PLAYER_JUMP; + } +} + +/* D. Air movement: weaker steering, and NO friction when the stick is + * released, so you keep your momentum like in SM64. */ +static void air_steer(Player *p, Wish wish, float dt) +{ + if (wish.mag > 0.0f) + steer(p, wish, + PLAYER_TURN_RATE * PLAYER_AIR_CONTROL, + PLAYER_GROUND_ACCEL * PLAYER_AIR_CONTROL, dt); +} + +/* FALL: in the air, going down. Landing hands straight over to the ground + * logic on the same tick, so a jump pressed on the landing tick isn't lost. */ +static void update_fall(Player *p, const Input *in, Wish wish, float dt) +{ + if (p->body.on_ground) { + p->state = grounded_state(p); + update_ground(p, in, wish, dt); + return; + } + air_steer(p, wish, dt); +} + +/* JUMP: in the air, still rising from a jump. */ +static void update_jump(Player *p, const Input *in, Wish wish, float dt) +{ + /* Past the apex (or landed already): it's a fall now. */ + if (p->body.vel.y <= 0.0f) { + p->state = PLAYER_FALL; + update_fall(p, in, wish, dt); + return; + } + + air_steer(p, wish, dt); + + /* Variable jump height: letting go of A while rising cuts the upward speed. + * Tapping A gives a short hop, holding it gives the full jump. Switching to + * FALL right away makes sure the cut happens only once. */ + if (!in->jump_held) { + p->body.vel.y *= PLAYER_JUMP_CUT; + p->state = PLAYER_FALL; + } +} + +void player_init(Player *p, Vec3 spawn) +{ + p->body.pos = spawn; + p->body.vel = vec3_make(0.0f, 0.0f, 0.0f); + p->body.on_ground = true; + p->facing_yaw = 0.0f; + p->forward_speed = 0.0f; + p->state = PLAYER_IDLE; +} + +void player_reset(Player *p, Vec3 spawn) +{ + player_init(p, spawn); +} + +void player_update(Player *p, const Input *in, float camera_yaw, float dt) +{ + Wish wish = compute_wish(in, camera_yaw); + + /* IDLE and RUN share one helper: they differ only in speed. */ + switch (p->state) { + case PLAYER_IDLE: + case PLAYER_RUN: update_ground(p, in, wish, dt); break; + case PLAYER_JUMP: update_jump(p, in, wish, dt); break; + case PLAYER_FALL: update_fall(p, in, wish, dt); break; + } + + /* E. Turn "speed along facing" into a velocity, then let physics move us. */ + p->body.vel.x = sinf(p->facing_yaw) * p->forward_speed; + p->body.vel.z = cosf(p->facing_yaw) * p->forward_speed; + physics_step(&p->body, dt); +} + +const char *player_state_name(PlayerState s) +{ + switch (s) { + case PLAYER_IDLE: return "IDLE"; + case PLAYER_RUN: return "RUN"; + case PLAYER_JUMP: return "JUMP"; + case PLAYER_FALL: return "FALL"; + } + return "?"; +} diff --git a/platformer/src/player.h b/platformer/src/player.h new file mode 100644 index 0000000..35e5b6a --- /dev/null +++ b/platformer/src/player.h @@ -0,0 +1,73 @@ +/* + * ============================================================ + * FILE: player.h + * + * PURPOSE: Public interface for the player character: its state and the + * one function that advances it each tick. + * + * FITS IN: main.c owns one Player, calls player_update() each tick, and + * calls player_reset() on Input.reset_pressed. render.c reads it + * to draw it. + * + * INTERFACE: Use these exact names: + * + * typedef enum PlayerState { + * PLAYER_IDLE, on ground, not moving + * PLAYER_RUN, on ground, moving (walk vs run is just speed) + * PLAYER_JUMP, in air, going up after a jump + * PLAYER_FALL in air, going down (or walked off something) + * } PlayerState; + * + * typedef struct Player { + * Body body; position / velocity / on_ground (physics.h) + * float facing_yaw; direction the player faces, radians. + * Facing vector = (sin(yaw), 0, cos(yaw)), + * which matches mat4_rotate_y in math3d.h. + * float forward_speed; ground speed along facing_yaw, m/s (>= 0) + * PlayerState state; + * } Player; + * + * void player_init(Player *p, Vec3 spawn); + * void player_reset(Player *p, Vec3 spawn); + * void player_update(Player *p, const Input *in, float camera_yaw, float dt); + * camera_yaw is a plain float so player.c doesn't depend on camera.h. + * const char *player_state_name(PlayerState s); "IDLE", "RUN", ... for debug + * + * Include "math3d.h", "physics.h", "controls.h". + * + * CONVENTIONS: Include guard: PLAYER_H. + * + * NOT IN SCOPE: Health, animation, extra moves (see README roadmap). + * + * DONE WHEN: main.c and render.c compile against this header alone. + * ============================================================ + */ +#ifndef PLAYER_H +#define PLAYER_H + +#include "controls.h" +#include "math3d.h" +#include "physics.h" + +/* SM64-style "actions". Add states here only when a new move needs one; + * see the README roadmap (double jump, long jump, wall kick, ...). */ +typedef enum PlayerState { + PLAYER_IDLE, /* on ground, not moving */ + PLAYER_RUN, /* on ground, moving (walk vs run is just speed) */ + PLAYER_JUMP, /* in air, going up after a jump */ + PLAYER_FALL /* in air, going down (or walked off something) */ +} PlayerState; + +typedef struct Player { + Body body; /* position / velocity / on_ground */ + float facing_yaw; /* radians; facing vector = (sin(yaw), 0, cos(yaw)) */ + float forward_speed; /* ground speed along facing_yaw, m/s (>= 0) */ + PlayerState state; +} Player; + +void player_init(Player *p, Vec3 spawn); +void player_reset(Player *p, Vec3 spawn); +void player_update(Player *p, const Input *in, float camera_yaw, float dt); +const char *player_state_name(PlayerState s); + +#endif /* PLAYER_H */ diff --git a/platformer/src/render.c b/platformer/src/render.c new file mode 100644 index 0000000..a91b561 --- /dev/null +++ b/platformer/src/render.c @@ -0,0 +1,380 @@ +/* + * ============================================================ + * FILE: render.c + * + * PURPOSE: Draws the whole scene with modern OpenGL 3.3 core and as little + * code as possible: a ground grid, the player as a box, and the + * player's drop shadow. + * + * FITS IN: Implements render.h. Reads Camera (camera.h), Player (player.h) + * and world_half_extent()/world_ground_height() (world.h). Uses the + * GL functions that window.c loaded through GLEW. + * + * IMPLEMENT: + * - ONE shader program, source written as string literals in this file + * (no shader files to load): + * vertex: in vec3 a_pos; uniform mat4 u_mvp; gl_Position = u_mvp * vec4(a_pos,1) + * fragment: uniform vec4 u_color; out vec4 frag; frag = u_color + * Add a static helper that compiles a shader and prints the info log + * on failure. Look up the uniform locations once in render_init. + * + * - Three meshes, each a VAO + VBO built once in render_init: + * 1. Ground grid: GL_LINES in the XZ plane at y = 0, one line every + * GRID_SPACING from -world_half_extent() to +world_half_extent(), in + * both directions. Put "major" lines (every GRID_MAJOR_EVERY-th) in a + * SEPARATE draw range so they can get a brighter color. The grid is + * what makes motion readable in a blank world, so explain that in a comment. + * 2. Unit cube: 36 vertices (GL_TRIANGLES), spanning x,z in [-0.5, 0.5] + * and y in [0, 1] so its origin is at the BOTTOM center, matching + * Body.pos being the feet. + * 3. Shadow disc: a GL_TRIANGLE_FAN circle of radius 1 in the XZ plane + * (~24 segments). + * + * - render_frame(cam, player, aspect): + * 1. glClearColor(SKY_COLOR_R/G/B), clear color + depth. + * 2. vp = camera_projection(cam, aspect) * camera_view(cam). + * 3. Grid: u_mvp = vp. Draw minor lines in a dim color, major lines brighter. + * 4. Shadow (drawn BEFORE the player): + * model = translate(player x, ground_y + 0.01, player z) * scale(r, 1, r) + * with r around PLAYER_HALF_WIDTH * 1.2. Dark color. The +0.01 lift + * stops z-fighting with the ground. Comment WHY the shadow exists: + * in SM64 the blob under Mario is the main cue for where you'll land. + * Without it, jumps in 3D are very hard to judge. + * ground_y = world_ground_height(player x, player z). + * 5. Player box: + * model = translate(body.pos) * rotate_y(facing_yaw) + * * scale(2*PLAYER_HALF_WIDTH, PLAYER_HEIGHT, 2*PLAYER_HALF_WIDTH) + * Bright color (e.g. red). Also draw a small second box as a "nose" on + * the front face (+Z in model space) so the facing direction is visible. + * That makes the turn rate tunable by eye. + * Everything uses the one shader, changing only u_mvp and u_color. + * + * - render_shutdown: delete the VAOs, VBOs and the program. + * + * CONVENTIONS: `s_` statics for GL handles. Model matrices built from + * math3d.h helpers. There's no lighting, so flat colors are fine. + * + * NOT IN SCOPE: Lighting, textures, models, text/HUD, anti-aliasing, + * interpolating between ticks (a README roadmap item). + * + * DONE WHEN: The scene shows a sky-colored background, a grid ground plane + * stretching to the world edge, a box with a visible nose that faces + * where it runs, and a shadow that stays on the ground under the + * box during a jump. + * ============================================================ + */ + +#include <GL/glew.h> + +#include <math.h> +#include <stdio.h> +#include <stdlib.h> + +#include "config.h" +#include "render.h" +#include "world.h" + +/* Purely visual sizes (not movement tuning, so they live here, not config.h). */ +#define SHADOW_RADIUS_SCALE 1.2f /* shadow radius relative to PLAYER_HALF_WIDTH */ +#define SHADOW_LIFT 0.01f /* m above ground, so the shadow doesn't z-fight it */ +#define SHADOW_SEGMENTS 24 /* triangles in the shadow circle */ +#define NOSE_SIZE 0.3f /* m, edge length of the facing-direction "nose" box */ +#define NOSE_HEIGHT 0.6f /* nose height as a fraction of PLAYER_HEIGHT */ +#define GROUND_THICKNESS 1.0f /* m, the ground slab under the grid */ + +/* Flat colors, RGBA. */ +static const float COLOR_GROUND[4] = { 0.36f, 0.56f, 0.32f, 1.0f }; +static const float COLOR_GRID_MINOR[4] = { 0.30f, 0.48f, 0.27f, 1.0f }; +static const float COLOR_GRID_MAJOR[4] = { 0.62f, 0.82f, 0.55f, 1.0f }; +static const float COLOR_SHADOW[4] = { 0.12f, 0.16f, 0.12f, 1.0f }; +static const float COLOR_PLAYER[4] = { 0.85f, 0.15f, 0.15f, 1.0f }; +static const float COLOR_NOSE[4] = { 1.00f, 0.85f, 0.20f, 1.0f }; + +/* A VAO + VBO of positions only (3 floats per vertex). */ +typedef struct { + GLuint vao, vbo; + GLsizei vertex_count; +} Mesh; + +static GLuint s_program; +static GLint s_u_mvp, s_u_color; +static Mesh s_grid, s_cube, s_disc; +static GLsizei s_grid_minor_count; /* grid VBO holds minor lines first, then major */ + +static const char *VERTEX_SRC = + "#version 330 core\n" + "in vec3 a_pos;\n" + "uniform mat4 u_mvp;\n" + "void main() { gl_Position = u_mvp * vec4(a_pos, 1.0); }\n"; + +static const char *FRAGMENT_SRC = + "#version 330 core\n" + "uniform vec4 u_color;\n" + "out vec4 frag;\n" + "void main() { frag = u_color; }\n"; + +/* ---- Setup helpers ----------------------------------------------------- */ + +/* Compiles one shader stage; prints the driver's error log on failure. */ +static GLuint compile_shader(GLenum type, const char *source) +{ + GLuint shader = glCreateShader(type); + glShaderSource(shader, 1, &source, NULL); + glCompileShader(shader); + + GLint ok; + glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); + if (!ok) { + char log[1024]; + glGetShaderInfoLog(shader, sizeof log, NULL, log); + fprintf(stderr, "render: %s shader failed to compile:\n%s\n", + type == GL_VERTEX_SHADER ? "vertex" : "fragment", log); + glDeleteShader(shader); + return 0; + } + return shader; +} + +static GLuint build_program(void) +{ + GLuint vs = compile_shader(GL_VERTEX_SHADER, VERTEX_SRC); + GLuint fs = compile_shader(GL_FRAGMENT_SHADER, FRAGMENT_SRC); + if (!vs || !fs) { + glDeleteShader(vs); /* deleting 0 is a no-op */ + glDeleteShader(fs); + return 0; + } + + GLuint program = glCreateProgram(); + glAttachShader(program, vs); + glAttachShader(program, fs); + glBindAttribLocation(program, 0, "a_pos"); /* every mesh uses attribute 0 */ + glLinkProgram(program); + glDeleteShader(vs); /* the linked program keeps what it needs */ + glDeleteShader(fs); + + GLint ok; + glGetProgramiv(program, GL_LINK_STATUS, &ok); + if (!ok) { + char log[1024]; + glGetProgramInfoLog(program, sizeof log, NULL, log); + fprintf(stderr, "render: shader program failed to link:\n%s\n", log); + glDeleteProgram(program); + return 0; + } + return program; +} + +/* Uploads xyz positions into a new VAO + VBO. */ +static Mesh make_mesh(const float *xyz, int vertex_count) +{ + Mesh mesh; + mesh.vertex_count = vertex_count; + glGenVertexArrays(1, &mesh.vao); + glGenBuffers(1, &mesh.vbo); + glBindVertexArray(mesh.vao); + glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo); + glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)(vertex_count * 3 * sizeof(float)), xyz, GL_STATIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0); + glBindVertexArray(0); + return mesh; +} + +static void delete_mesh(Mesh *mesh) +{ + glDeleteVertexArrays(1, &mesh->vao); + glDeleteBuffers(1, &mesh->vbo); +} + +/* Writes a line segment (2 vertices) at out[0..5]; returns the next slot. */ +static float *put_line(float *out, float x0, float z0, float x1, float z1) +{ + out[0] = x0; out[1] = 0.0f; out[2] = z0; + out[3] = x1; out[4] = 0.0f; out[5] = z1; + return out + 6; +} + +/* The ground grid. In a blank world the grid is the ONLY thing that shows + * motion: without it, running looks like standing still. Lines are indexed + * from the origin, so the origin is always on a major line. Minor lines go + * first in the buffer and major lines after, so each group can be drawn with + * its own color. */ +static bool build_grid(void) +{ + float extent = world_half_extent(); + int half_lines = (int)(extent / GRID_SPACING); + int lines = (2 * half_lines + 1) * 2; /* both directions */ + float *verts = malloc((size_t)lines * 6 * sizeof(float)); + if (!verts) { + fprintf(stderr, "render: out of memory building the grid\n"); + return false; + } + + float *out = verts; + for (int pass = 0; pass < 2; pass++) { /* pass 0 = minor, 1 = major */ + for (int k = -half_lines; k <= half_lines; k++) { + bool major = (k % GRID_MAJOR_EVERY) == 0; + if (major != (pass == 1)) + continue; + float c = (float)k * GRID_SPACING; + out = put_line(out, c, -extent, c, extent); /* runs along Z */ + out = put_line(out, -extent, c, extent, c); /* runs along X */ + } + if (pass == 0) + s_grid_minor_count = (GLsizei)((out - verts) / 3); + } + + s_grid = make_mesh(verts, lines * 2); + free(verts); + return true; +} + +/* Unit cube, x/z in [-0.5, 0.5] and y in [0, 1]: the origin is the BOTTOM + * center, like Body.pos being the feet. Corner i has x = bit 0, y = bit 1, + * z = bit 2. */ +static void build_cube(void) +{ + static const int FACES[36] = { + 0, 4, 6, 0, 6, 2, /* -X */ + 1, 3, 7, 1, 7, 5, /* +X */ + 0, 1, 5, 0, 5, 4, /* -Y */ + 2, 6, 7, 2, 7, 3, /* +Y */ + 0, 2, 3, 0, 3, 1, /* -Z */ + 4, 5, 7, 4, 7, 6, /* +Z */ + }; + float verts[36 * 3]; + for (int i = 0; i < 36; i++) { + int corner = FACES[i]; + verts[i * 3 + 0] = (corner & 1) ? 0.5f : -0.5f; + verts[i * 3 + 1] = (corner & 2) ? 1.0f : 0.0f; + verts[i * 3 + 2] = (corner & 4) ? 0.5f : -0.5f; + } + s_cube = make_mesh(verts, 36); +} + +/* Radius-1 circle in the XZ plane as a triangle fan: center, then the rim, + * with the first rim point repeated at the end to close the circle. */ +static void build_disc(void) +{ + float verts[(SHADOW_SEGMENTS + 2) * 3]; + verts[0] = verts[1] = verts[2] = 0.0f; + for (int i = 0; i <= SHADOW_SEGMENTS; i++) { + float a = 2.0f * M3D_PI * (float)i / (float)SHADOW_SEGMENTS; + verts[(i + 1) * 3 + 0] = sinf(a); + verts[(i + 1) * 3 + 1] = 0.0f; + verts[(i + 1) * 3 + 2] = cosf(a); + } + s_disc = make_mesh(verts, SHADOW_SEGMENTS + 2); +} + +/* ---- Drawing helpers --------------------------------------------------- */ + +static void set_uniforms(Mat4 mvp, const float color[4]) +{ + glUniformMatrix4fv(s_u_mvp, 1, GL_FALSE, mvp.m); + glUniform4fv(s_u_color, 1, color); +} + +static void draw_mesh(const Mesh *mesh, GLenum mode, Mat4 mvp, const float color[4]) +{ + set_uniforms(mvp, color); + glBindVertexArray(mesh->vao); + glDrawArrays(mode, 0, mesh->vertex_count); +} + +/* A flat slab whose top face is the ground plane, so the world isn't just + * grid lines floating in the sky. It is drawn first without writing depth: + * everything else is on or above the ground, so it never hides anything, + * and that means the grid lines lying exactly on its surface can't z-fight it. */ +static void draw_ground(Mat4 vp) +{ + float size = 2.0f * world_half_extent(); + Mat4 model = mat4_mul(mat4_translate(vec3_make(0.0f, -GROUND_THICKNESS, 0.0f)), + mat4_scale(vec3_make(size, GROUND_THICKNESS, size))); + glDepthMask(GL_FALSE); + draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, model), COLOR_GROUND); + glDepthMask(GL_TRUE); +} + +static void draw_grid(Mat4 vp) +{ + glBindVertexArray(s_grid.vao); + set_uniforms(vp, COLOR_GRID_MINOR); + glDrawArrays(GL_LINES, 0, s_grid_minor_count); + set_uniforms(vp, COLOR_GRID_MAJOR); + glDrawArrays(GL_LINES, s_grid_minor_count, s_grid.vertex_count - s_grid_minor_count); +} + +/* The drop shadow. In SM64 the blob under Mario is the main cue for where + * you'll land: without it, depth is very hard to judge in 3D and jumps become + * guesswork. It sits on the GROUND below the player, not at the player's height. */ +static void draw_shadow(Mat4 vp, const Player *player) +{ + Vec3 pos = player->body.pos; + float ground_y = world_ground_height(pos.x, pos.z); + float r = PLAYER_HALF_WIDTH * SHADOW_RADIUS_SCALE; + Mat4 model = mat4_mul(mat4_translate(vec3_make(pos.x, ground_y + SHADOW_LIFT, pos.z)), + mat4_scale(vec3_make(r, 1.0f, r))); + draw_mesh(&s_disc, GL_TRIANGLE_FAN, mat4_mul(vp, model), COLOR_SHADOW); +} + +/* The player box, plus a small "nose" box on its front (+Z in model space) + * so you can see which way it faces and tune the turn rate by eye. */ +static void draw_player(Mat4 vp, const Player *player) +{ + Mat4 placed = mat4_mul(mat4_translate(player->body.pos), mat4_rotate_y(player->facing_yaw)); + + Mat4 body = mat4_mul(placed, mat4_scale(vec3_make(2.0f * PLAYER_HALF_WIDTH, + PLAYER_HEIGHT, + 2.0f * PLAYER_HALF_WIDTH))); + draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, body), COLOR_PLAYER); + + Vec3 nose_offset = vec3_make(0.0f, PLAYER_HEIGHT * NOSE_HEIGHT, PLAYER_HALF_WIDTH); + Mat4 nose = mat4_mul(placed, mat4_mul(mat4_translate(nose_offset), + mat4_scale(vec3_make(NOSE_SIZE, NOSE_SIZE, NOSE_SIZE)))); + draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, nose), COLOR_NOSE); +} + +/* ---- Public interface -------------------------------------------------- */ + +bool render_init(void) +{ + s_program = build_program(); + if (!s_program) + return false; + s_u_mvp = glGetUniformLocation(s_program, "u_mvp"); + s_u_color = glGetUniformLocation(s_program, "u_color"); + + if (!build_grid()) { + glDeleteProgram(s_program); + return false; + } + build_cube(); + build_disc(); + return true; +} + +void render_frame(const Camera *cam, const Player *player, float aspect) +{ + glClearColor(SKY_COLOR_R, SKY_COLOR_G, SKY_COLOR_B, 1.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glUseProgram(s_program); + + Mat4 vp = mat4_mul(camera_projection(cam, aspect), camera_view(cam)); + + draw_ground(vp); + draw_grid(vp); + draw_shadow(vp, player); /* before the player, so the player is drawn over it */ + draw_player(vp, player); + + glBindVertexArray(0); +} + +void render_shutdown(void) +{ + delete_mesh(&s_grid); + delete_mesh(&s_cube); + delete_mesh(&s_disc); + glDeleteProgram(s_program); +} diff --git a/platformer/src/render.h b/platformer/src/render.h new file mode 100644 index 0000000..24dcf5e --- /dev/null +++ b/platformer/src/render.h @@ -0,0 +1,40 @@ +/* + * ============================================================ + * FILE: render.h + * + * PURPOSE: Public interface for drawing a frame. Rendering only READS game + * state; it never changes the player, the camera or the world. + * + * FITS IN: main.c calls render_init() after window_init(), render_frame() + * once per display frame, and render_shutdown() before + * window_shutdown(). + * + * INTERFACE: Use these exact signatures: + * + * bool render_init(void); compiles shaders, builds meshes. Returns + * false (after printing why) on failure. + * void render_frame(const Camera *cam, const Player *player, float aspect); + * void render_shutdown(void); frees GL objects + * + * Include <stdbool.h>, "camera.h", "player.h". + * + * CONVENTIONS: Include guard: RENDER_H. + * + * NOT IN SCOPE: A general renderer / scene graph, materials, textures, text. + * + * DONE WHEN: main.c can draw everything with these three calls. + * ============================================================ + */ +#ifndef RENDER_H +#define RENDER_H + +#include <stdbool.h> + +#include "camera.h" +#include "player.h" + +bool render_init(void); +void render_frame(const Camera *cam, const Player *player, float aspect); +void render_shutdown(void); + +#endif /* RENDER_H */ diff --git a/platformer/src/window.c b/platformer/src/window.c new file mode 100644 index 0000000..1f4d517 --- /dev/null +++ b/platformer/src/window.c @@ -0,0 +1,175 @@ +/* + * ============================================================ + * FILE: window.c + * + * PURPOSE: Creates and owns the single game window and its OpenGL context. + * This is the ONLY file that calls GLFW window/context functions + * and glewInit. (controls.c calls GLFW input functions.) + * + * FITS IN: main.c calls window_init() first and window_shutdown() last. + * Every frame main.c calls window_poll_events() and window_swap(). + * Implements the interface in window.h. + * + * IMPLEMENT: + * - Private state: `static GLFWwindow *s_window;` + * - Include order matters: <GL/glew.h> BEFORE <GLFW/glfw3.h>. + * - window_init(): + * 1. glfwSetErrorCallback -> print GLFW errors to stderr. + * 2. glfwInit(). Note that this also initializes GLFW's joystick/gamepad + * support, which controls.c depends on. + * 3. Hints: GL 3.3, GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_FORWARD_COMPAT. + * 4. Create a WINDOW_WIDTH x WINDOW_HEIGHT window titled WINDOW_TITLE + * (config.h), make its context current. + * 5. glewExperimental = GL_TRUE; glewInit(). With a core profile, glewInit + * can leave a harmless GL_INVALID_ENUM behind, so call glGetError() + * once to clear it and add a comment explaining why. + * 6. glfwSwapInterval(1) for vsync. + * 7. Framebuffer-size callback -> glViewport(0, 0, w, h). + * 8. Enable GL_DEPTH_TEST here (it's global GL state set once). + * On any failure: print a clear message, clean up, return false. + * - window_framebuffer_size / window_aspect: use glfwGetFramebufferSize + * (NOT the window size, because they differ on HiDPI displays). Guard against + * height == 0 (minimized window) so the aspect never divides by zero. + * - Everything else is a thin wrapper over the matching glfw* call. + * + * CONVENTIONS: `s_` prefix for file-private statics. Messages go to stderr. + * + * NOT IN SCOPE: Input handling (that's controls.c), drawing (render.c), + * fullscreen, window icons, resizable-minimum-size logic. + * + * DONE WHEN: A window opens at the configured size and title with a + * 3.3 core context, closes cleanly, and resizing it keeps the + * viewport correct. + * ============================================================ + */ + +/* GLEW must come before GLFW: it defines the GL headers GLFW would include. */ +#include <GL/glew.h> +#include <GLFW/glfw3.h> + +#include <stdio.h> + +#include "config.h" +#include "window.h" + +static GLFWwindow *s_window; + +static void on_glfw_error(int code, const char *description) +{ + fprintf(stderr, "GLFW error %d: %s\n", code, description); +} + +static void on_framebuffer_resize(GLFWwindow *window, int w, int h) +{ + (void)window; + glViewport(0, 0, w, h); +} + +bool window_init(void) +{ + glfwSetErrorCallback(on_glfw_error); + + /* Also initializes GLFW's joystick/gamepad support, used by controls.c. */ + if (!glfwInit()) { + fprintf(stderr, "window: glfwInit failed\n"); + return false; + } + + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); + + s_window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, NULL, NULL); + if (!s_window) { + fprintf(stderr, "window: could not create a %dx%d window with an OpenGL 3.3 core context\n", + WINDOW_WIDTH, WINDOW_HEIGHT); + glfwTerminate(); + return false; + } + glfwMakeContextCurrent(s_window); + + /* glewExperimental makes GLEW load core-profile functions it would + * otherwise skip because it can't find them in the extension string. */ + glewExperimental = GL_TRUE; + GLenum glew_status = glewInit(); + if (glew_status != GLEW_OK) { + fprintf(stderr, "window: glewInit failed: %s\n", glewGetErrorString(glew_status)); + glfwDestroyWindow(s_window); + s_window = NULL; + glfwTerminate(); + return false; + } + /* In a core profile, glewInit calls glGetString(GL_EXTENSIONS), which no + * longer exists, so it leaves a harmless GL_INVALID_ENUM behind. Clear it + * so it doesn't look like a bug in our own code later. */ + glGetError(); + + glfwSwapInterval(1); /* vsync: no tearing, and no burning a CPU core */ + + glfwSetFramebufferSizeCallback(s_window, on_framebuffer_resize); + int w, h; + glfwGetFramebufferSize(s_window, &w, &h); + glViewport(0, 0, w, h); + + glEnable(GL_DEPTH_TEST); + return true; +} + +void window_shutdown(void) +{ + if (s_window) { + glfwDestroyWindow(s_window); + s_window = NULL; + } + glfwTerminate(); +} + +bool window_should_close(void) +{ + return glfwWindowShouldClose(s_window); +} + +void window_request_close(void) +{ + glfwSetWindowShouldClose(s_window, GLFW_TRUE); +} + +void window_poll_events(void) +{ + glfwPollEvents(); +} + +void window_swap(void) +{ + glfwSwapBuffers(s_window); +} + +double window_time(void) +{ + return glfwGetTime(); +} + +/* Framebuffer size, NOT window size: they differ on HiDPI displays. */ +void window_framebuffer_size(int *w, int *h) +{ + glfwGetFramebufferSize(s_window, w, h); +} + +float window_aspect(void) +{ + int w, h; + window_framebuffer_size(&w, &h); + if (h <= 0) return 1.0f; /* minimized window: avoid dividing by zero */ + return (float)w / (float)h; +} + +void window_set_title(const char *title) +{ + glfwSetWindowTitle(s_window, title); +} + +struct GLFWwindow *window_handle(void) +{ + return s_window; +} diff --git a/platformer/src/window.h b/platformer/src/window.h new file mode 100644 index 0000000..06ca163 --- /dev/null +++ b/platformer/src/window.h @@ -0,0 +1,60 @@ +/* + * ============================================================ + * FILE: window.h + * + * PURPOSE: Public interface for the OS window, the OpenGL context and the + * clock. Hides GLFW/GLEW setup from the rest of the game. + * + * FITS IN: Called by main.c (lifecycle, loop), render.c (aspect ratio / + * framebuffer size), and controls.c (window handle, only for + * the keyboard fallback). + * + * INTERFACE: Use these exact signatures: + * + * bool window_init(void); + * Creates the window + GL 3.3 core context, loads GL via GLEW. + * Returns false (after printing why to stderr) on failure. + * void window_shutdown(void); + * bool window_should_close(void); + * void window_request_close(void); e.g. when Start/Esc is pressed + * void window_poll_events(void); once per display frame + * void window_swap(void); present the finished frame + * double window_time(void); seconds since start (double for + * precision over long sessions) + * void window_framebuffer_size(int *w, int *h); in PIXELS (for glViewport) + * float window_aspect(void); framebuffer width / height + * void window_set_title(const char *title); used for a debug readout + * struct GLFWwindow *window_handle(void); ONLY controls.c may use this + * + * Include <stdbool.h>. Forward-declare `struct GLFWwindow;` rather than + * including GLFW here, so files that include window.h don't pull in GLFW. + * + * CONVENTIONS: Include guard: WINDOW_H. + * + * NOT IN SCOPE: Fullscreen toggle, multiple windows, mouse capture. + * + * DONE WHEN: The header compiles on its own and main.c can drive the whole + * window lifecycle through it. + * ============================================================ + */ +#ifndef WINDOW_H +#define WINDOW_H + +#include <stdbool.h> + +/* Forward declaration, so including window.h doesn't pull in GLFW. */ +struct GLFWwindow; + +bool window_init(void); +void window_shutdown(void); +bool window_should_close(void); +void window_request_close(void); +void window_poll_events(void); +void window_swap(void); +double window_time(void); +void window_framebuffer_size(int *w, int *h); +float window_aspect(void); +void window_set_title(const char *title); +struct GLFWwindow *window_handle(void); /* ONLY controls.c may use this */ + +#endif /* WINDOW_H */ diff --git a/platformer/src/world.c b/platformer/src/world.c new file mode 100644 index 0000000..4ae0d00 --- /dev/null +++ b/platformer/src/world.c @@ -0,0 +1,64 @@ +/* + * ============================================================ + * FILE: world.c + * + * PURPOSE: The blank test world: an empty, flat square of ground where we + * tune movement. It stays empty on purpose, like the test space + * SM64's team used before building real levels. + * + * FITS IN: Implements world.h. Has no dependencies besides config.h and + * math3d.h. physics.c is its main caller. + * + * IMPLEMENT: + * - world_init(): nothing to do yet. Leave a comment saying this is where + * level data would be loaded. + * - world_ground_height(x, z): return 0.0f. Mark the unused parameters with + * (void)x; (void)z; so -Wextra stays quiet, and add a comment saying this + * is where a heightmap/platform lookup will go. + * - world_clamp_to_bounds(p): clamp p.x and p.z with clampf from math3d.h. + * - world_spawn_point(): return vec3_make(0, 0, 0). + * - world_half_extent(): return WORLD_HALF_EXTENT. + * + * CONVENTIONS: Y up. The ground surface is the plane y = world_ground_height. + * + * NOT IN SCOPE: Anything that isn't flat ground. Don't build a collision + * system "for later"; add it when the first platform shows up. + * + * DONE WHEN: It compiles warning-free, and the player can't leave the square. + * ============================================================ + */ + +#include "config.h" +#include "world.h" + +void world_init(void) +{ + /* Nothing to do yet. This is where level data would be loaded. */ +} + +float world_ground_height(float x, float z) +{ + /* The world is flat for now. This is where a heightmap/platform lookup + * will go once there's terrain to stand on. */ + (void)x; + (void)z; + return 0.0f; +} + +/* Keeps x and z on the ground square; y (height) is untouched. */ +Vec3 world_clamp_to_bounds(Vec3 p) +{ + p.x = clampf(p.x, -WORLD_HALF_EXTENT, WORLD_HALF_EXTENT); + p.z = clampf(p.z, -WORLD_HALF_EXTENT, WORLD_HALF_EXTENT); + return p; +} + +Vec3 world_spawn_point(void) +{ + return vec3_make(0.0f, 0.0f, 0.0f); +} + +float world_half_extent(void) +{ + return WORLD_HALF_EXTENT; +} diff --git a/platformer/src/world.h b/platformer/src/world.h new file mode 100644 index 0000000..af60feb --- /dev/null +++ b/platformer/src/world.h @@ -0,0 +1,48 @@ +/* + * ============================================================ + * FILE: world.h + * + * PURPOSE: Public interface for "the level". Today the level is a blank, + * flat square of ground, and this API is how other modules ask + * questions about it. + * + * FITS IN: physics.c asks for the ground height and bounds. main.c asks + * for the spawn point. render.c asks for the extent so it knows + * how big a grid to draw. + * + * INTERFACE: Use these exact signatures: + * + * void world_init(void); + * float world_ground_height(float x, float z); + * Height of the ground at (x, z). Returns 0.0f for now. This is + * the one hook where terrain/platforms will plug in later. + * Vec3 world_clamp_to_bounds(Vec3 p); + * Returns p with x and z clamped to [-WORLD_HALF_EXTENT, + * +WORLD_HALF_EXTENT]. y is untouched. + * Vec3 world_spawn_point(void); + * Where the player starts / resets to: (0, 0, 0) for now. + * float world_half_extent(void); + * Returns WORLD_HALF_EXTENT (so render.c doesn't need config + * knowledge of the world's shape). + * + * Include "math3d.h". + * + * CONVENTIONS: Include guard: WORLD_H. + * + * NOT IN SCOPE: Level files, platforms, walls, slopes, objects. + * + * DONE WHEN: physics.c and render.c can be written using only this header. + * ============================================================ + */ +#ifndef WORLD_H +#define WORLD_H + +#include "math3d.h" + +void world_init(void); +float world_ground_height(float x, float z); +Vec3 world_clamp_to_bounds(Vec3 p); +Vec3 world_spawn_point(void); +float world_half_extent(void); + +#endif /* WORLD_H */ |
