summaryrefslogtreecommitdiff
path: root/platformer
diff options
context:
space:
mode:
Diffstat (limited to 'platformer')
-rw-r--r--platformer/README.md21
-rw-r--r--platformer/src/config.h8
-rw-r--r--platformer/src/physics.c143
-rw-r--r--platformer/src/physics.h29
-rw-r--r--platformer/src/player.c19
-rw-r--r--platformer/src/render.c82
-rw-r--r--platformer/src/world.c208
-rw-r--r--platformer/src/world.h63
8 files changed, 450 insertions, 123 deletions
diff --git a/platformer/README.md b/platformer/README.md
index 370d263..ef39837 100644
--- a/platformer/README.md
+++ b/platformer/README.md
@@ -2,8 +2,8 @@
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**:
+**Current scope:** a flat test world scattered with box platforms, 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.
---
@@ -19,8 +19,8 @@ These rules apply to every change. If a change breaks one, it needs a very good
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.
+3. **Minimal scope.** Start super small and grow one piece at a time. Today it's a test world of plain
+ box platforms 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.
@@ -30,8 +30,8 @@ These rules apply to every change. If a change breaks one, it needs a very good
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.
+movement and the camera to feel right. We're following the same order: the test world (flat ground
+plus plain box platforms to jump on) *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".
@@ -113,11 +113,11 @@ arrow keys = camera, C = recenter camera, Space = jump, R = reset, Esc = quit.
| `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/world.c/.h` | The test level: ground, seeded random box platforms, geometry queries and boundaries. |
+| `src/physics.c/.h` | Gravity, velocity integration, and floor/wall/ceiling 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. |
+| `src/render.c/.h` | Draws the ground grid, the platforms, the player box and its drop shadow. Read-only. |
**Dependency direction** (arrows mean "includes / calls"; there are no cycles):
@@ -185,7 +185,8 @@ Suggested fill-in order (each step can be compiled before moving on):
## Roadmap (explicitly *not* now)
-- Collision with real geometry (platforms, walls, slopes)
+- Richer level geometry: slopes, moving platforms, step-up onto small ledges, hand-built or loaded levels
+- Camera collision (the camera can currently pass through tall platforms)
- Loading levels
- SM64-style extra moves: double/triple jump, long jump, wall kick, ground pound
- Character model and animation
diff --git a/platformer/src/config.h b/platformer/src/config.h
index 807a6be..8739dbf 100644
--- a/platformer/src/config.h
+++ b/platformer/src/config.h
@@ -89,6 +89,11 @@
* 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
+ * WORLD_SEED 20260924u seed for the platform layout; change it
+ * for a different (but repeatable) level
+ * WORLD_PLATFORM_COUNT 40 how many platforms to scatter
+ * WORLD_PLATFORM_AREA 25.0f m; platforms land within this distance of
+ * spawn in x and z (smaller = denser)
*
* CONVENTIONS: 1 unit = 1 meter, seconds, radians (degrees only for names
* ending in _DEG, which are easier to tune by eye; converted where
@@ -168,5 +173,8 @@
#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 */
+#define WORLD_SEED 20260924u /* platform layout seed; change for a different (repeatable) level */
+#define WORLD_PLATFORM_COUNT 40 /* platforms scattered around spawn; more = busier level */
+#define WORLD_PLATFORM_AREA 25.0f /* m from spawn (x and z) platforms can land; smaller = denser */
#endif /* CONFIG_H */
diff --git a/platformer/src/physics.c b/platformer/src/physics.c
index b04a78e..423550d 100644
--- a/platformer/src/physics.c
+++ b/platformer/src/physics.c
@@ -2,40 +2,50 @@
* ============================================================
* FILE: physics.c
*
- * PURPOSE: Moves a Body forward one fixed tick: gravity, integration,
- * landing on the ground, and staying inside the world.
+ * PURPOSE: Moves a Body forward one fixed tick: gravity, then movement one
+ * axis at a time with collision against the level's boxes, 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.
+ * world_floor_below(), world_ceiling_above(), world_find_overlap()
+ * 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.
+ * 1. Gravity ALWAYS pulls: vel.y -= GRAVITY * dt, clamped to no lower than
+ * -TERMINAL_VELOCITY. Standing still, the floor check in step 4 pushes
+ * right back. WHY always: that's what makes walking off a ledge fall on its
+ * own, with no special "is there still floor under me?" case.
+ * 2. Move X: pos.x += vel.x * dt. If the body now overlaps a box
+ * (world_find_overlap), push it back out on the side it came from and
+ * zero vel.x. Repeat a few times in case the push lands in another box.
+ * 3. Move Z: the same, for z. Resolving one axis at a time is what makes
+ * running diagonally into a wall SLIDE along it instead of stopping dead.
+ * 4. Move Y: remember prev_y, then pos.y += vel.y * dt (semi-implicit Euler:
+ * velocity was updated first; add a comment on why that's stable for a
+ * fixed timestep).
+ * Floor: floor = world_floor_below((x, prev_y, z), half_width), the
+ * highest surface the feet were above at the START of the move. If
+ * pos.y <= floor: land (pos.y = floor, vel.y = 0 if falling,
+ * on_ground = true). Using prev_y means a fast fall can never skip
+ * through a thin platform between two ticks.
+ * Otherwise on_ground = false, and check the ceiling the same way from
+ * the previous head height: if the head crossed a box bottom, stop at
+ * it and zero upward speed (bonk).
+ * 5. Bounds: pos = world_clamp_to_bounds(pos). If x or z got clamped,
+ * zero that velocity component so the body doesn't "stick" to the edge.
*
* 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.
+ * player.c), slopes, step-up onto small ledges, 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.
+ * y = 0 with on_ground = true, and stays there. It lands on
+ * platform tops (even at terminal velocity), can't walk through a
+ * platform's sides, slides along them when running diagonally,
+ * falls when it walks off an edge, and bonks on undersides.
* ============================================================
*/
@@ -43,37 +53,82 @@
#include "physics.h"
#include "world.h"
-void physics_step(Body *b, float dt)
+#define PUSH_SKIN 1e-3f /* m, extra gap left after a push-out so edges only touch */
+#define MAX_PUSH_PASSES 4 /* push-outs per axis per tick (boxes can overlap) */
+
+/* Pushes the body out of any box it overlaps along ONE horizontal axis,
+ * back toward where it came from. pos_axis/vel_axis point at the x or z
+ * members of the body, so the same code handles both axes. */
+static void resolve_axis(Body *b, float *pos_axis, float *vel_axis, bool axis_is_x)
{
- /* 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;
+ for (int pass = 0; pass < MAX_PUSH_PASSES; pass++) {
+ Box hit;
+ if (!world_find_overlap(b->pos, b->half_width, b->height, &hit))
+ return;
+ float box_min = axis_is_x ? hit.min.x : hit.min.z;
+ float box_max = axis_is_x ? hit.max.x : hit.max.z;
+ if (*vel_axis > 0.0f)
+ *pos_axis = box_min - b->half_width - PUSH_SKIN; /* was moving +: back off to the min side */
+ else if (*vel_axis < 0.0f)
+ *pos_axis = box_max + b->half_width + PUSH_SKIN; /* was moving -: back off to the max side */
+ else
+ return; /* not moving on this axis, so this axis didn't cause it */
+ *vel_axis = 0.0f;
}
+}
- /* 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));
+/* Step 4: vertical movement with floor and ceiling. */
+static void move_vertically(Body *b, float dt)
+{
+ float prev_y = b->pos.y;
+ /* Semi-implicit Euler: vel.y was already updated by gravity, and the
+ * position moves with that NEW velocity. Unlike plain Euler (which uses
+ * the old velocity) it 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.y += b->vel.y * 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;
+ /* The highest surface the feet were above BEFORE moving. Any top between
+ * the old and new height is at or below prev_y, so the fall lands on the
+ * first one it crossed, no matter how fast it was going. */
+ float floor_y = world_floor_below(vec3_make(b->pos.x, prev_y, b->pos.z), b->half_width);
+ if (b->pos.y <= floor_y) {
+ b->pos.y = floor_y;
if (b->vel.y < 0.0f)
b->vel.y = 0.0f;
b->on_ground = true;
- } else {
- b->on_ground = false;
+ return;
+ }
+ b->on_ground = false;
+
+ /* Same idea upward: stop the head at the first underside it crossed. */
+ float ceiling_y = world_ceiling_above(vec3_make(b->pos.x, prev_y + b->height, b->pos.z),
+ b->half_width);
+ if (b->pos.y + b->height >= ceiling_y) {
+ b->pos.y = ceiling_y - b->height;
+ if (b->vel.y > 0.0f)
+ b->vel.y = 0.0f;
}
+}
+
+void physics_step(Body *b, float dt)
+{
+ /* 1. Gravity always pulls; the floor pushes back in step 4. */
+ b->vel.y -= GRAVITY * dt;
+ if (b->vel.y < -TERMINAL_VELOCITY)
+ b->vel.y = -TERMINAL_VELOCITY;
+
+ /* 2 + 3. Horizontal movement, one axis at a time, so a diagonal run into
+ * a wall slides along it instead of stopping dead. */
+ b->pos.x += b->vel.x * dt;
+ resolve_axis(b, &b->pos.x, &b->vel.x, true);
+ b->pos.z += b->vel.z * dt;
+ resolve_axis(b, &b->pos.z, &b->vel.z, false);
+
+ /* 4. Vertical movement: land on floors, bonk on ceilings. */
+ move_vertically(b, dt);
- /* 4. Bounds. Zero the velocity into an edge we got clamped against, so
+ /* 5. 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;
diff --git a/platformer/src/physics.h b/platformer/src/physics.h
index 580d09b..f626c65 100644
--- a/platformer/src/physics.h
+++ b/platformer/src/physics.h
@@ -3,31 +3,36 @@
* 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.
+ * falls, moves, lands on floors, slides along walls and bumps its
+ * head on ceilings. 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.
+ * about floors, ceilings, overlapping boxes 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
+ * 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
+ * something (the ground or a platform top)
+ * float half_width; collision box half-size in x and z, meters
+ * float height; collision box height above the feet, meters
* } Body;
*
* void physics_step(Body *b, float dt);
*
* Include <stdbool.h> and "math3d.h".
*
- * CONVENTIONS: Include guard: PHYSICS_H.
+ * CONVENTIONS: Include guard: PHYSICS_H. The collision shape is an axis-aligned
+ * box that does not rotate (a spinning box would snag on walls).
*
* 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.
+ * DONE WHEN: player.c can move, land, and collide using only Body + physics_step.
* ============================================================
*/
#ifndef PHYSICS_H
@@ -38,9 +43,11 @@
#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 */
+ 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 something */
+ float half_width; /* collision box half-size in x and z, meters */
+ float height; /* collision box height above the feet, meters */
} Body;
void physics_step(Body *b, float dt);
diff --git a/platformer/src/player.c b/platformer/src/player.c
index ed8da51..16924ec 100644
--- a/platformer/src/player.c
+++ b/platformer/src/player.c
@@ -13,6 +13,7 @@
*
* IMPLEMENT:
* - player_init / player_reset: body.pos = spawn, vel = 0, on_ground = true,
+ * body.half_width = PLAYER_HALF_WIDTH, body.height = PLAYER_HEIGHT,
* facing_yaw = 0, forward_speed = 0, state = PLAYER_IDLE.
*
* - player_update(p, in, camera_yaw, dt). Use one static helper per state
@@ -47,7 +48,7 @@
* - 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.
+ * (walked off a platform edge) -> FALL.
*
* E. Apply: body.vel.x = sin(facing_yaw) * forward_speed
* body.vel.z = cos(facing_yaw) * forward_speed
@@ -117,7 +118,7 @@ static PlayerState grounded_state(const Player *p)
* 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. */
+ /* Walked off a platform edge: start falling. */
if (!p->body.on_ground) {
p->state = PLAYER_FALL;
update_fall(p, in, wish, dt);
@@ -182,12 +183,14 @@ static void update_jump(Player *p, const Input *in, Wish wish, float dt)
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;
+ p->body.pos = spawn;
+ p->body.vel = vec3_make(0.0f, 0.0f, 0.0f);
+ p->body.on_ground = true;
+ p->body.half_width = PLAYER_HALF_WIDTH; /* the collision box matches the drawn box */
+ p->body.height = PLAYER_HEIGHT;
+ p->facing_yaw = 0.0f;
+ p->forward_speed = 0.0f;
+ p->state = PLAYER_IDLE;
}
void player_reset(Player *p, Vec3 spawn)
diff --git a/platformer/src/render.c b/platformer/src/render.c
index a91b561..381a018 100644
--- a/platformer/src/render.c
+++ b/platformer/src/render.c
@@ -7,7 +7,8 @@
* 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
+ * and the level (world_half_extent(), world_box_count()/world_box()
+ * and world_floor_below() from world.h). Uses the
* GL functions that window.c loaded through GLEW.
*
* IMPLEMENT:
@@ -26,22 +27,35 @@
* 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.
+ * Body.pos being the feet. Its faces are stored in a fixed order
+ * (-X, +X, -Y, +Y, -Z, +Z), 6 vertices each, so a single face can be
+ * drawn on its own.
* 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)
+ * 3. Ground: the cube scaled into a flat slab whose top is y = 0, drawn
+ * first WITHOUT depth writes (everything else is on or above it, so it
+ * never hides anything, and grid lines on its surface can't z-fight it).
+ * 4. Grid: u_mvp = vp. Draw minor lines in a dim color, major lines brighter.
+ * 5. Platforms: each world_box() is the cube scaled to the box. Draw it
+ * face by face with a fixed brightness per face (top brightest, bottom
+ * darkest, sides in between and different from each other) times the
+ * platform's color from a small palette. WHY: with no lighting, a
+ * one-color box is a flat silhouette and you can't tell its top from its
+ * sides, which makes jumps impossible to judge. Per-face shading is
+ * the cheapest way to read shape, and it needs no lighting code.
+ * 6. Shadow (drawn BEFORE the player):
+ * model = translate(player x, floor_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:
+ * floor_y = world_floor_below(body.pos, body.half_width): the surface
+ * the player would land on, whether that's the ground or a platform.
+ * 7. 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
@@ -52,7 +66,8 @@
* - 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.
+ * math3d.h helpers. There's no lighting: flat colors, plus the
+ * fixed per-face shading on platforms.
*
* NOT IN SCOPE: Lighting, textures, models, text/HUD, anti-aliasing,
* interpolating between ticks (a README roadmap item).
@@ -90,6 +105,21 @@ 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 };
+/* Platform colors, picked per platform by index so neighbors vary. */
+static const float PLATFORM_PALETTE[][3] = {
+ { 0.80f, 0.72f, 0.55f }, /* sandstone */
+ { 0.62f, 0.66f, 0.74f }, /* slate */
+ { 0.78f, 0.55f, 0.42f }, /* terracotta */
+ { 0.70f, 0.70f, 0.66f }, /* concrete */
+};
+#define PLATFORM_PALETTE_SIZE ((int)(sizeof PLATFORM_PALETTE / sizeof PLATFORM_PALETTE[0]))
+
+/* Brightness per cube face, in the cube's face order (-X, +X, -Y, +Y, -Z, +Z).
+ * Top brightest, bottom darkest, and no two touching sides the same, so the
+ * box's shape reads without any lighting. */
+static const float FACE_SHADE[6] = { 0.70f, 0.82f, 0.45f, 1.00f, 0.60f, 0.90f };
+#define CUBE_FACE_VERTS 6
+
/* A VAO + VBO of positions only (3 floats per vertex). */
typedef struct {
GLuint vao, vbo;
@@ -306,15 +336,40 @@ static void draw_grid(Mat4 vp)
glDrawArrays(GL_LINES, s_grid_minor_count, s_grid.vertex_count - s_grid_minor_count);
}
+/* One platform, drawn face by face with FACE_SHADE so its top and sides
+ * read as different surfaces (see the prompt above for why). */
+static void draw_platform(Mat4 vp, Box box, const float rgb[3])
+{
+ Vec3 size = vec3_sub(box.max, box.min);
+ Vec3 bottom = vec3_make(0.5f * (box.min.x + box.max.x), box.min.y,
+ 0.5f * (box.min.z + box.max.z));
+ Mat4 mvp = mat4_mul(vp, mat4_mul(mat4_translate(bottom), mat4_scale(size)));
+
+ glBindVertexArray(s_cube.vao);
+ for (int face = 0; face < 6; face++) {
+ float s = FACE_SHADE[face];
+ float color[4] = { rgb[0] * s, rgb[1] * s, rgb[2] * s, 1.0f };
+ set_uniforms(mvp, color);
+ glDrawArrays(GL_TRIANGLES, face * CUBE_FACE_VERTS, CUBE_FACE_VERTS);
+ }
+}
+
+static void draw_platforms(Mat4 vp)
+{
+ for (int i = 0; i < world_box_count(); i++)
+ draw_platform(vp, world_box(i), PLATFORM_PALETTE[i % PLATFORM_PALETTE_SIZE]);
+}
+
/* 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. */
+ * guesswork. It sits on the surface BELOW the player (the ground or a platform
+ * top), 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)),
+ Vec3 pos = player->body.pos;
+ float floor_y = world_floor_below(pos, player->body.half_width);
+ float r = PLAYER_HALF_WIDTH * SHADOW_RADIUS_SCALE;
+ Mat4 model = mat4_mul(mat4_translate(vec3_make(pos.x, floor_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);
}
@@ -365,6 +420,7 @@ void render_frame(const Camera *cam, const Player *player, float aspect)
draw_ground(vp);
draw_grid(vp);
+ draw_platforms(vp);
draw_shadow(vp, player); /* before the player, so the player is drawn over it */
draw_player(vp, player);
diff --git a/platformer/src/world.c b/platformer/src/world.c
index 4ae0d00..fb7a840 100644
--- a/platformer/src/world.c
+++ b/platformer/src/world.c
@@ -2,47 +2,209 @@
* ============================================================
* 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.
+ * PURPOSE: The test world: a flat square of ground with a scatter of box
+ * platforms to run around and jump on. It's still a test space,
+ * like the one SM64's team tuned Mario in, just with things to
+ * jump onto now.
*
* FITS IN: Implements world.h. Has no dependencies besides config.h and
- * math3d.h. physics.c is its main caller.
+ * math3d.h. physics.c is its main caller; render.c draws its boxes.
*
* 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.
+ * - Level data: a static array of WORLD_PLATFORM_COUNT boxes, filled by
+ * world_init().
*
- * CONVENTIONS: Y up. The ground surface is the plane y = world_ground_height.
+ * - world_init(): generate the platforms with a tiny xorshift32 random
+ * generator seeded from WORLD_SEED. WHY our own instead of rand(): rand()
+ * differs between C libraries, so the "same" seed could give a different
+ * level on another machine. Two kinds of platform (ranges are named
+ * constants at the top of this file):
+ * block stands on the ground (bottom 0), top low enough to jump onto
+ * from the ground (a full jump lifts the feet ~2.3 m)
+ * floating a thin slab higher up, reached by jumping from a block
+ * Each gets a random footprint and a random spot within WORLD_PLATFORM_AREA
+ * of spawn (x and z). Re-roll the spot if the footprint comes within
+ * SPAWN_CLEAR_RADIUS of spawn, so the player never starts inside a platform.
+ * Platforms may overlap each other; that's fine for both collision and
+ * drawing.
*
- * 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.
+ * - Queries, all over the body's FOOTPRINT (a square of +-half_width, the
+ * same shape as the player's box), with edges that only touch NOT counting:
+ * world_floor_below: the highest top <= feet.y + SURFACE_EPSILON among
+ * boxes whose footprint overlaps, or 0 (the ground). The epsilon lets
+ * a body standing exactly on a top still find it.
+ * world_ceiling_above: the lowest bottom >= head.y - SURFACE_EPSILON, or
+ * WORLD_NO_CEILING.
+ * world_find_overlap: the first box that overlaps the body's full volume
+ * (footprint AND height range).
+ * - world_clamp_to_bounds, world_spawn_point, world_half_extent: as before.
*
- * DONE WHEN: It compiles warning-free, and the player can't leave the square.
+ * CONVENTIONS: Y up. Boxes are axis-aligned. The ground surface is y = 0.
+ *
+ * NOT IN SCOPE: Level files, guaranteeing every platform is reachable, slopes,
+ * moving platforms.
+ *
+ * DONE WHEN: It compiles warning-free, the same seed always builds the same
+ * level, spawn is clear, and the player can't leave the square.
* ============================================================
*/
+#include <stdint.h>
+
#include "config.h"
#include "world.h"
+/* Platform generation ranges (level design, not movement feel). */
+#define PLATFORM_MIN_SIZE 2.0f /* m, shortest footprint side */
+#define PLATFORM_MAX_SIZE 6.0f /* m, longest footprint side */
+#define BLOCK_MIN_TOP 0.6f /* m, lowest ground block */
+#define BLOCK_MAX_TOP 2.0f /* m, highest ground block (full jump reaches ~2.3) */
+#define FLOATING_MIN_TOP 2.6f /* m, lowest floating slab top */
+#define FLOATING_MAX_TOP 4.2f /* m, highest floating slab top (reachable from a block) */
+#define FLOATING_THICKNESS 0.5f /* m, floating slab thickness */
+#define FLOATING_CHANCE 0.35f /* fraction of platforms that float */
+#define SPAWN_CLEAR_RADIUS 4.0f /* m around spawn kept free of platforms */
+#define MAX_PLACEMENT_TRIES 50 /* re-rolls before giving up on a platform */
+
+#define SURFACE_EPSILON 0.01f /* m, "standing exactly on it" tolerance */
+#define OVERLAP_EPSILON 1e-4f /* m, edges closer than this only touch */
+
+static Box s_boxes[WORLD_PLATFORM_COUNT];
+static int s_box_count;
+static uint32_t s_rng_state;
+
+/* ---- Random numbers ---------------------------------------------------- */
+
+/* xorshift32: three shifts and XORs give a decent, fully repeatable sequence. */
+static uint32_t next_random(void)
+{
+ s_rng_state ^= s_rng_state << 13;
+ s_rng_state ^= s_rng_state >> 17;
+ s_rng_state ^= s_rng_state << 5;
+ return s_rng_state;
+}
+
+/* A float in [lo, hi]. */
+static float random_range(float lo, float hi)
+{
+ return lo + (hi - lo) * ((float)next_random() / 4294967295.0f);
+}
+
+/* ---- Level generation -------------------------------------------------- */
+
+/* True if the footprint comes within SPAWN_CLEAR_RADIUS of spawn. Uses the
+ * closest point of the footprint to spawn, so big platforms can't sneak in. */
+static bool too_close_to_spawn(Box b)
+{
+ Vec3 spawn = world_spawn_point();
+ float dx = clampf(spawn.x, b.min.x, b.max.x) - spawn.x;
+ float dz = clampf(spawn.z, b.min.z, b.max.z) - spawn.z;
+ return dx * dx + dz * dz < SPAWN_CLEAR_RADIUS * SPAWN_CLEAR_RADIUS;
+}
+
+/* One platform with a random size and height (but no position yet). */
+static Box random_platform_shape(void)
+{
+ float half_x = 0.5f * random_range(PLATFORM_MIN_SIZE, PLATFORM_MAX_SIZE);
+ float half_z = 0.5f * random_range(PLATFORM_MIN_SIZE, PLATFORM_MAX_SIZE);
+ float bottom, top;
+ if (random_range(0.0f, 1.0f) < FLOATING_CHANCE) {
+ top = random_range(FLOATING_MIN_TOP, FLOATING_MAX_TOP);
+ bottom = top - FLOATING_THICKNESS;
+ } else {
+ top = random_range(BLOCK_MIN_TOP, BLOCK_MAX_TOP);
+ bottom = 0.0f;
+ }
+ Box b = { { -half_x, bottom, -half_z }, { half_x, top, half_z } };
+ return b;
+}
+
+/* Moves a box so its footprint is centered on (x, z). */
+static Box place_box(Box b, float x, float z)
+{
+ Vec3 offset = vec3_make(x, 0.0f, z);
+ b.min = vec3_add(b.min, offset);
+ b.max = vec3_add(b.max, offset);
+ return b;
+}
+
void world_init(void)
{
- /* Nothing to do yet. This is where level data would be loaded. */
+ s_rng_state = WORLD_SEED ? WORLD_SEED : 1u; /* xorshift must not start at 0 */
+ s_box_count = 0;
+
+ for (int i = 0; i < WORLD_PLATFORM_COUNT; i++) {
+ Box shape = random_platform_shape();
+ for (int tries = 0; tries < MAX_PLACEMENT_TRIES; tries++) {
+ Box placed = place_box(shape,
+ random_range(-WORLD_PLATFORM_AREA, WORLD_PLATFORM_AREA),
+ random_range(-WORLD_PLATFORM_AREA, WORLD_PLATFORM_AREA));
+ if (!too_close_to_spawn(placed)) {
+ s_boxes[s_box_count++] = placed;
+ break;
+ }
+ }
+ }
+}
+
+int world_box_count(void)
+{
+ return s_box_count;
+}
+
+Box world_box(int i)
+{
+ return s_boxes[i];
+}
+
+/* ---- Geometry queries -------------------------------------------------- */
+
+/* Does the footprint around (x, z) overlap the box's footprint? Edges that
+ * only touch don't count, so a body pushed flush against a wall isn't "in" it. */
+static bool footprint_overlaps(Box b, float x, float z, float half_width)
+{
+ return x + half_width > b.min.x + OVERLAP_EPSILON &&
+ x - half_width < b.max.x - OVERLAP_EPSILON &&
+ z + half_width > b.min.z + OVERLAP_EPSILON &&
+ z - half_width < b.max.z - OVERLAP_EPSILON;
+}
+
+float world_floor_below(Vec3 feet, float half_width)
+{
+ float floor_y = 0.0f; /* the ground */
+ for (int i = 0; i < s_box_count; i++) {
+ Box b = s_boxes[i];
+ if (footprint_overlaps(b, feet.x, feet.z, half_width) &&
+ b.max.y <= feet.y + SURFACE_EPSILON && b.max.y > floor_y)
+ floor_y = b.max.y;
+ }
+ return floor_y;
+}
+
+float world_ceiling_above(Vec3 head, float half_width)
+{
+ float ceiling_y = WORLD_NO_CEILING;
+ for (int i = 0; i < s_box_count; i++) {
+ Box b = s_boxes[i];
+ if (footprint_overlaps(b, head.x, head.z, half_width) &&
+ b.min.y >= head.y - SURFACE_EPSILON && b.min.y < ceiling_y)
+ ceiling_y = b.min.y;
+ }
+ return ceiling_y;
}
-float world_ground_height(float x, float z)
+bool world_find_overlap(Vec3 feet, float half_width, float height, Box *hit)
{
- /* 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;
+ for (int i = 0; i < s_box_count; i++) {
+ Box b = s_boxes[i];
+ bool vertical = feet.y < b.max.y - OVERLAP_EPSILON &&
+ feet.y + height > b.min.y + OVERLAP_EPSILON;
+ if (vertical && footprint_overlaps(b, feet.x, feet.z, half_width)) {
+ *hit = b;
+ return true;
+ }
+ }
+ return false;
}
/* Keeps x and z on the ground square; y (height) is untouched. */
diff --git a/platformer/src/world.h b/platformer/src/world.h
index af60feb..9da16c1 100644
--- a/platformer/src/world.h
+++ b/platformer/src/world.h
@@ -2,34 +2,57 @@
* ============================================================
* 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.
+ * PURPOSE: Public interface for "the level": a flat square of ground with
+ * a scatter of box-shaped platforms on it. This API is how other
+ * modules ask questions about the level's geometry.
*
- * 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.
+ * FITS IN: physics.c asks what's under the feet, what's above the head,
+ * and what box a body overlaps. render.c asks for the extent and
+ * the boxes so it can draw them, and for the floor under the
+ * player for the shadow. main.c asks for the spawn point.
*
- * INTERFACE: Use these exact signatures:
+ * INTERFACE: Use these exact names:
+ *
+ * typedef struct Box {
+ * Vec3 min, max; axis-aligned corners, meters (min.y = bottom, max.y = top)
+ * } Box;
*
* 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.
+ * Builds the level. Platforms are placed "randomly" from
+ * WORLD_SEED, so the same seed always gives the same layout.
+ * int world_box_count(void);
+ * Box world_box(int i); 0 <= i < world_box_count()
+ *
+ * A "footprint" below is the square [x +- half_width] x [z +- half_width]
+ * around a body's center. Touching edges don't count as overlapping.
+ *
+ * float world_floor_below(Vec3 feet, float half_width);
+ * The highest surface under the footprint whose top is at or just
+ * below feet.y (a box top, or the ground at 0). This is what the
+ * feet land on, and where the shadow goes.
+ * float world_ceiling_above(Vec3 head, float half_width);
+ * The lowest box bottom over the footprint that is at or just above
+ * head.y, or WORLD_NO_CEILING if there's none.
+ * bool world_find_overlap(Vec3 feet, float half_width, float height, Box *hit);
+ * True (and *hit = that box) if a body standing at `feet` with this
+ * size overlaps any box. physics.c uses it to push bodies out of walls.
* 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.
+ * Where the player starts / resets to: (0, 0, 0). The area around
+ * it is kept clear of platforms.
* 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".
+ * #define WORLD_NO_CEILING 1e9f (far above anything)
+ *
+ * Include <stdbool.h> and "math3d.h".
*
* CONVENTIONS: Include guard: WORLD_H.
*
- * NOT IN SCOPE: Level files, platforms, walls, slopes, objects.
+ * NOT IN SCOPE: Level files, slopes, moving platforms, non-box shapes.
*
* DONE WHEN: physics.c and render.c can be written using only this header.
* ============================================================
@@ -37,10 +60,22 @@
#ifndef WORLD_H
#define WORLD_H
+#include <stdbool.h>
+
#include "math3d.h"
+#define WORLD_NO_CEILING 1e9f /* returned when nothing is overhead */
+
+typedef struct Box {
+ Vec3 min, max; /* axis-aligned corners, meters (min.y = bottom, max.y = top) */
+} Box;
+
void world_init(void);
-float world_ground_height(float x, float z);
+int world_box_count(void);
+Box world_box(int i);
+float world_floor_below(Vec3 feet, float half_width);
+float world_ceiling_above(Vec3 head, float half_width);
+bool world_find_overlap(Vec3 feet, float half_width, float height, Box *hit);
Vec3 world_clamp_to_bounds(Vec3 p);
Vec3 world_spawn_point(void);
float world_half_extent(void);