summaryrefslogtreecommitdiff
path: root/platformer
diff options
context:
space:
mode:
Diffstat (limited to 'platformer')
-rw-r--r--platformer/README.md4
-rw-r--r--platformer/game_feel.md46
-rw-r--r--platformer/src/config.h23
-rw-r--r--platformer/src/main.c26
-rw-r--r--platformer/src/player.c33
-rw-r--r--platformer/src/render.c145
-rw-r--r--platformer/src/render.h9
7 files changed, 245 insertions, 41 deletions
diff --git a/platformer/README.md b/platformer/README.md
index 6baef89..73fd75f 100644
--- a/platformer/README.md
+++ b/platformer/README.md
@@ -117,7 +117,7 @@ arrow keys = camera, C = recenter camera, Space = jump, R = reset, Esc = quit.
| `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 platforms, the player box and its drop shadow. Read-only. |
+| `src/render.c/.h` | Draws the ground grid, the platforms, the player box, its drop shadow, and the FPS counter. Read-only. |
**Dependency direction** (arrows mean "includes / calls"; there are no cycles):
@@ -191,5 +191,5 @@ Suggested fill-in order (each step can be compiled before moving on):
- SM64-style extra moves: double/triple jump, long jump, wall kick, ground pound
- Character model and animation
- Audio
-- On-screen text/HUD
+- On-screen text/HUD beyond the FPS counter in the top-right corner
- Interpolating render state between ticks
diff --git a/platformer/game_feel.md b/platformer/game_feel.md
index 2d96731..166d476 100644
--- a/platformer/game_feel.md
+++ b/platformer/game_feel.md
@@ -40,15 +40,29 @@ and eased, not snappier.
## Character movement
-- **Speed follows the stick.** Tilt amount sets target speed (`PLAYER_MAX_SPEED` 9 m/s at full tilt).
+- **Speed follows the stick.** Tilt amount sets target speed (`PLAYER_MAX_SPEED` 6 m/s at full tilt).
+ The top run speed is kept modest **on purpose**: future moves will be how players go faster, and a
+ slower base run makes precise movement easier.
The left stick uses a **radial** deadzone so diagonals and slow walking stay smooth. Never snap
the left stick to axes; movement must stay free in every direction.
- **Camera-relative controls.** Stick up = away from the camera.
-- **Turning is quick but not instant** (`PLAYER_TURN_RATE` 12 rad/s, about 0.26 s for 180°). The nose on
- the player box exists so the turn rate can be judged by eye.
-- **Stops are short and smooth:** from full speed, friction stops the player in about 14 ticks (0.23 s).
-- **Air keeps momentum.** Air control is 30% of ground accel and turn rate, with no friction when the
- stick is released (SM64-style).
+- **The character is heavy.** Starts build up and stops skid: the player should feel like a real,
+ tangible object, but never like they're on ice. From rest, full tilt reaches top speed in 43 ticks
+ (0.72 s, `PLAYER_GROUND_ACCEL` 8.4 m/s²). Releasing the stick at full speed skids to a stop in 32 ticks
+ (0.53 s, 1.54 m, `PLAYER_GROUND_FRICTION` 11.3 m/s²). Heaviness is felt as *time*, so if you change
+ `PLAYER_MAX_SPEED`, rescale accel and friction to keep these times (at a lower top speed, the same
+ accel reaches it sooner and feels snappier).
+- **Turning is quick but not instant while moving** (`PLAYER_TURN_RATE` 12 rad/s, about 0.26 s for 180°).
+ The nose on the player box exists so the turn rate can be judged by eye.
+- **Turning on a dime from a standstill.** On the ground at speed 0, a stick push more than 90°
+ (`PLAYER_SNAP_TURN_DEG`) away from the facing direction faces it on the very first tick. Pushes of
+ 90° or less use the normal quick turn rate (a 90° turn takes 8 ticks, 0.13 s), so small aim
+ adjustments stay smooth. This applies only on the ground; in the air the reduced turn rate always
+ applies.
+- **Air keeps momentum.** In the air the turn rate is 30% of the ground rate (`PLAYER_AIR_CONTROL`), and
+ acceleration has its own constant (`PLAYER_AIR_ACCEL` 9 m/s², the old 30% of the ground accel, kept when
+ the ground got heavier so jumps steer the same). There's no friction when the stick is released
+ (SM64-style).
- **Variable jump height.** Holding A gives a full jump; releasing early multiplies upward speed
by `PLAYER_JUMP_CUT` once. Measured at 60 Hz: a full jump reaches **2.33 m** (the "~2.4 m" in comments
is the continuous-physics figure) and a tap gives about 0.72 m. Level geometry is sized against 2.33 m.
@@ -56,7 +70,7 @@ and eased, not snappier.
logic on the same tick it detects landing.
- **SM64-style circling is intentional.** Controls stay purely camera-relative even while the camera
swings on its own, so holding the stick sideways during a camera swing makes the player run a
- wide arc (about 18 m radius, 36 m across). The user explicitly chose this over locking the stick direction.
+ wide arc (about 12 m radius, 24 m across, at 6 m/s). The user explicitly chose this over locking the stick direction.
**Don't "fix" it without asking.**
---
@@ -144,7 +158,9 @@ New automatic camera behaviors should follow the same approach: slow, eased, and
platforms (`WORLD_SEED`, so every run is the same layout). Spawn is kept clear (4 m).
- **Heights are sized to the jump:** ground blocks top out at 2.0 m (below the 2.33 m jump); floating
slabs sit at 2.6–4.2 m, reached by jumping from a block. Only 9 of 16 floating slabs have a block close
- enough to jump from; reachability isn't guaranteed yet.
+ enough to jump from; reachability isn't guaranteed yet. That count was made at a 9 m/s run. At 6 m/s a
+ full running jump covers only about 4.0 m horizontally (it was about 6 m), so fewer slabs may be
+ reachable now.
- **Collision behaviors worth preserving:**
- Gravity *always* pulls and the floor pushes back, so walking off a ledge falls without special cases.
- Movement is resolved one axis at a time, so running diagonally into a wall **slides** along it.
@@ -168,11 +184,16 @@ New automatic camera behaviors should follow the same approach: slow, eased, and
with the camera, so the swing chases forever. It only settles when the player steers to hold a line.
- **The starting pitch (20°) differs from the auto-tilt target (15°),** so every session begins with a
small upward tilt. Setting `CAMERA_PITCH_DEFAULT` to 0.26 rad would skip it.
+- **Heavy stops, but not heavy reversals.** Letting go skids, yet pushing the stick the opposite way
+ at full speed keeps all the speed and swings around in a tight 0.26 s U-turn, since velocity always
+ points along the facing direction. SM64 solves this with a turnaround skid (brake, then turn). That's
+ listed under `NOT IN SCOPE` in `player.c` for now, but it's the natural next step if reversals feel
+ too light next to the stops.
- **High-angle auto-tilt resets are long** (60° → 15° takes about 15.7 s of motion). For big tilts the
top speed (`CAMERA_AUTO_PITCH_SPEED`) sets the time; for small ones, the acceleration does.
- **No camera collision:** the camera can pass through tall platforms (it's on the roadmap).
- **Rough edges not yet addressed:** there's no step-up (even a 0.6 m block needs a jump);
- `forward_speed` isn't reduced by walls (the title shows 9 m/s while pushing into one); the drawn
+ `forward_speed` isn't reduced by walls (the title shows 6 m/s while pushing into one); the drawn
box rotates but the collision box doesn't (up to about 17 cm visual overlap with walls at
diagonals).
@@ -191,6 +212,11 @@ New automatic camera behaviors should follow the same approach: slow, eased, and
| Auto-tilt motion | linear 0.15 rad/s → eased, much slower → accel slightly quicker → all 10% slower | 0.054 rad/s cap, 0.045 rad/s² |
| Manual pitch speed | 1.5 → 1.125 rad/s | 1.125 |
| Right-stick snap | none → 15° → 10° → 5° → back to 15° | 15° |
+| Top run speed | 9 → 7 → 5 → 6 m/s (slower on purpose; later moves add speed) | 6 m/s |
+| Ground accel | 30 → 12 → 7 → 8.4 m/s² (0.30 → 0.60 → 0.72 s to top speed; the last step kept 0.72 s at 6 m/s) | 8.4 m/s² |
+| Ground friction | 40 → 16 → 9.5 → 11.3 m/s² (0.23 → 0.45 → 0.53 s stop; the last step kept 0.53 s at 6 m/s) | 11.3 m/s² |
+| Air accel | 30% of ground accel → its own constant, value kept | 9 m/s² |
+| Standstill turn | turn rate → instant at speed 0 → instant only past 90° (ground only) | > 90° instant |
---
@@ -209,7 +235,7 @@ New automatic camera behaviors should follow the same approach: slow, eased, and
times. The user tunes with both numbers and feel.
- **Say what you couldn't test.** Agents can't press the gamepad. Live checks are limited to
launching (`timeout 2.5 ./platformer`), reading the title-bar readout (state, speed, height,
- pad/keyboard), and screenshots (e.g. `ffmpeg -f x11grab`).
+ pad/keyboard), the FPS counter in the top-right corner (vsync caps it at the display rate), and screenshots (e.g. `ffmpeg -f x11grab`).
- **The development pad** is an Xbox Elite Series 2 over USB. GLFW's built-in database lacks its exact
GUID, so an embedded mapping line lives in `controls.c` (`EXTRA_GAMEPAD_MAPPINGS`). Unmapped pads are
printed at startup with their GUID.
diff --git a/platformer/src/config.h b/platformer/src/config.h
index 346b2b8..8816e98 100644
--- a/platformer/src/config.h
+++ b/platformer/src/config.h
@@ -35,13 +35,18 @@
* become exactly that direction)
*
* 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_MAX_SPEED 6.0f m/s at full stick tilt (kept modest on purpose:
+ * later moves will be the way to go faster)
+ * PLAYER_GROUND_ACCEL 8.4f m/s^2 speeding up toward target speed
+ * PLAYER_GROUND_FRICTION 11.3f m/s^2 slowing down with no input (a short skid)
* PLAYER_TURN_RATE 12.0f rad/s max facing rotation on ground
+ * PLAYER_SNAP_TURN_DEG 90.0f degrees; from a standstill, stick pushes
+ * more than this away from facing turn
+ * instantly (smaller ones use the turn rate)
*
* Player: air movement
- * PLAYER_AIR_CONTROL 0.30f 0..1 multiplier on accel + turn rate in air
+ * PLAYER_AIR_CONTROL 0.30f 0..1 multiplier on turn rate in air
+ * PLAYER_AIR_ACCEL 9.0f m/s^2 speeding up toward target speed 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
*
@@ -130,13 +135,15 @@
#define LOOK_AXIS_SNAP_DEG 15.0f /* right stick pushes this close to an axis become pure up/down/left/right; 0 = off, keep < 45 */
/* ---- 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_MAX_SPEED 6.0f /* m/s at full stick tilt; higher = faster top run speed (kept modest: later moves go faster) */
+#define PLAYER_GROUND_ACCEL 8.4f /* m/s^2 toward target speed; lower = heavier, slower starts */
+#define PLAYER_GROUND_FRICTION 11.3f /* m/s^2 slowdown with stick released; lower = longer skid to a stop */
#define PLAYER_TURN_RATE 12.0f /* rad/s max facing rotation on ground; higher = tighter turns */
+#define PLAYER_SNAP_TURN_DEG 90.0f /* degrees; standing still, bigger turns than this are instant; lower = more snapping */
/* ---- Player: air movement ---------------------------------------------- */
-#define PLAYER_AIR_CONTROL 0.30f /* 0..1 multiplier on accel + turn rate in air; higher = more steerable jumps */
+#define PLAYER_AIR_CONTROL 0.30f /* 0..1 multiplier on turn rate in air; higher = jumps turn more sharply */
+#define PLAYER_AIR_ACCEL 9.0f /* m/s^2 toward target speed 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 */
diff --git a/platformer/src/main.c b/platformer/src/main.c
index 8f5e510..0435737 100644
--- a/platformer/src/main.c
+++ b/platformer/src/main.c
@@ -40,8 +40,9 @@
* window_aspect(), TICK_DT);
* accumulator -= TICK_DT;
*
- * render_frame(&camera, &player, window_aspect());
+ * render_frame(&camera, &player, window_aspect(), fps);
* window_swap();
+ * count the frame toward the FPS reading (below)
*
* WHY the fixed timestep: the game behaves the same (identical jump
* height, identical speeds) no matter the monitor's refresh rate or a
@@ -53,6 +54,11 @@
* 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.
*
+ * - FPS counter: count rendered frames, and every FPS_UPDATE_INTERVAL
+ * seconds set fps = frames / elapsed time (rounded), then start counting
+ * again. Averaging over a window keeps the number steady enough to read.
+ * fps starts at 0, which render_frame() takes as "not measured yet".
+ *
* - 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"
@@ -69,7 +75,8 @@
* 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.
+ * the title bar shows live state/speed, and the top-right corner
+ * shows the FPS.
* ============================================================
*/
@@ -84,6 +91,7 @@
#include "world.h"
#define TITLE_UPDATE_INTERVAL 0.25 /* seconds between debug title refreshes */
+#define FPS_UPDATE_INTERVAL 0.5 /* seconds of frames averaged into each FPS reading */
/* Our "HUD" until text rendering exists: live state in the title bar.
* Updating a few times per second keeps it readable (and cheap). */
@@ -128,6 +136,9 @@ int main(void)
double previous = window_time();
double accumulator = 0.0;
double last_title_time = 0.0;
+ double fps_start = previous; /* when the current FPS count began */
+ int fps_frames = 0; /* frames rendered since fps_start */
+ int fps = 0; /* last FPS reading; 0 = not measured yet */
while (!window_should_close()) {
double now = window_time();
@@ -159,9 +170,18 @@ int main(void)
accumulator -= TICK_DT;
}
- render_frame(&camera, &player, window_aspect());
+ render_frame(&camera, &player, window_aspect(), fps);
window_swap();
+ /* FPS averaged over FPS_UPDATE_INTERVAL: a per-frame number would
+ * flicker too fast to read. */
+ fps_frames++;
+ if (now - fps_start >= FPS_UPDATE_INTERVAL) {
+ fps = (int)(fps_frames / (now - fps_start) + 0.5);
+ fps_frames = 0;
+ fps_start = now;
+ }
+
if (now - last_title_time >= TITLE_UPDATE_INTERVAL) {
update_debug_title(&player, &input);
last_title_time = now;
diff --git a/platformer/src/player.c b/platformer/src/player.c
index 16924ec..cbb2c1c 100644
--- a/platformer/src/player.c
+++ b/platformer/src/player.c
@@ -28,18 +28,26 @@
* wish_yaw = atan2f(wish.x, wish.z) (only meaningful if mag > 0)
*
* B. Ground movement (IDLE / RUN):
+ * - If mag > 0, forward_speed == 0 and wish_yaw is more than
+ * PLAYER_SNAP_TURN_DEG away from facing_yaw: facing_yaw = wish_yaw
+ * at once (standing still, a big turn happens on a dime). Smaller
+ * turns still use the quick turn rate below, so small stick
+ * adjustments stay smooth instead of twitching.
* - 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)
+ * PLAYER_GROUND_FRICTION * dt). Accel and friction are low on
+ * purpose: starts build up and stops skid briefly, so the player
+ * feels like a heavy, real object rather than a cursor.
* - 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
+ * D. Air movement (JUMP / FALL): the same as B, but the turn rate is
+ * multiplied by PLAYER_AIR_CONTROL, accel is PLAYER_AIR_ACCEL, there's
+ * no instant turn from a standstill, 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;
@@ -66,8 +74,9 @@
* 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
+ * PLAYER_MAX_SPEED after a noticeable build-up. Turning is quick but
+ * not instant while moving, and instant for big turns from a standstill. Letting go
+ * of the stick skids 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.
* ============================================================
@@ -125,10 +134,17 @@ static void update_ground(Player *p, const Input *in, Wish wish, float dt)
return;
}
- if (wish.mag > 0.0f)
+ if (wish.mag > 0.0f) {
+ /* Standing still there's no momentum to swing around, so a big turn
+ * faces the stick right away. Small ones keep the quick turn rate so
+ * nudging the stick to adjust your aim still looks smooth. */
+ float turn = fabsf(wrap_angle(wish.yaw - p->facing_yaw));
+ if (p->forward_speed == 0.0f && turn > PLAYER_SNAP_TURN_DEG * (M3D_PI / 180.0f))
+ p->facing_yaw = wish.yaw;
steer(p, wish, PLAYER_TURN_RATE, PLAYER_GROUND_ACCEL, dt);
- else
+ } else {
p->forward_speed = approachf(p->forward_speed, 0.0f, PLAYER_GROUND_FRICTION * dt);
+ }
p->state = grounded_state(p);
if (in->jump_pressed) {
@@ -144,8 +160,7 @@ 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);
+ PLAYER_TURN_RATE * PLAYER_AIR_CONTROL, PLAYER_AIR_ACCEL, dt);
}
/* FALL: in the air, going down. Landing hands straight over to the ground
diff --git a/platformer/src/render.c b/platformer/src/render.c
index 381a018..127806b 100644
--- a/platformer/src/render.c
+++ b/platformer/src/render.c
@@ -3,8 +3,8 @@
* 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.
+ * code as possible: a ground grid, the player as a box, the
+ * player's drop shadow, and an FPS counter in the top right.
*
* FITS IN: Implements render.h. Reads Camera (camera.h), Player (player.h)
* and the level (world_half_extent(), world_box_count()/world_box()
@@ -33,7 +33,7 @@
* 3. Shadow disc: a GL_TRIANGLE_FAN circle of radius 1 in the XZ plane
* (~24 segments).
*
- * - render_frame(cam, player, aspect):
+ * - render_frame(cam, player, aspect, fps):
* 1. glClearColor(SKY_COLOR_R/G/B), clear color + depth.
* 2. vp = camera_projection(cam, aspect) * camera_view(cam).
* 3. Ground: the cube scaled into a flat slab whose top is y = 0, drawn
@@ -61,6 +61,17 @@
* 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.
+ * 8. FPS counter (skipped while fps <= 0, i.e. not measured yet): the text
+ * "<fps> FPS", right-aligned in the top-right corner, white with a
+ * dark drop shadow so it reads over both sky and ground. Glyphs come
+ * from a tiny built-in 3x5 pixel font (only the digits, F, P and S,
+ * written as "#" strings so you can see each letter in the source).
+ * Each lit font pixel is a quad in a small mesh that is rebuilt ONLY
+ * when the number changes, so the counter costs two draw calls a
+ * frame. It's drawn last with the depth test off, in screen space
+ * measured in window heights so the font pixels stay square at any
+ * window shape. WHY it exists: to watch the cost of later
+ * optimization work at a glance.
* Everything uses the one shader, changing only u_mvp and u_color.
*
* - render_shutdown: delete the VAOs, VBOs and the program.
@@ -69,13 +80,14 @@
* 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,
+ * NOT IN SCOPE: Lighting, textures, models, general text/HUD (only the FPS
+ * counter's characters exist), font files, 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.
+ * box during a jump. The top-right corner shows the current FPS.
* ============================================================
*/
@@ -84,6 +96,7 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include "config.h"
#include "render.h"
@@ -96,6 +109,13 @@
#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 */
+#define HUD_PIXEL 0.006f /* size of one font pixel, as a fraction of the window height */
+#define HUD_MARGIN 0.02f /* gap between the FPS text and the window corner, in window heights */
+#define HUD_SHADOW_OFFSET 0.5f /* text shadow offset down and right, in font pixels */
+#define HUD_MAX_CHARS 16 /* longest text the FPS counter can hold */
+#define GLYPH_W 3 /* font pixels per glyph, across */
+#define GLYPH_H 5 /* font pixels per glyph, down */
+#define GLYPH_ADVANCE 4 /* glyph width plus a one-pixel gap */
/* Flat colors, RGBA. */
static const float COLOR_GROUND[4] = { 0.36f, 0.56f, 0.32f, 1.0f };
@@ -104,6 +124,8 @@ 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 };
+static const float COLOR_HUD_TEXT[4] = { 1.00f, 1.00f, 1.00f, 1.0f };
+static const float COLOR_HUD_SHADOW[4] = { 0.00f, 0.00f, 0.00f, 1.0f };
/* Platform colors, picked per platform by index so neighbors vary. */
static const float PLATFORM_PALETTE[][3] = {
@@ -120,6 +142,30 @@ static const float PLATFORM_PALETTE[][3] = {
static const float FACE_SHADE[6] = { 0.70f, 0.82f, 0.45f, 1.00f, 0.60f, 0.90f };
#define CUBE_FACE_VERTS 6
+/* A tiny pixel font holding only what the FPS counter spells. Each glyph is
+ * GLYPH_H rows, top row first, and "#" marks a lit pixel. */
+typedef struct {
+ char ch;
+ const char *rows[GLYPH_H];
+} Glyph;
+
+static const Glyph FONT[] = {
+ { '0', { "###", "#.#", "#.#", "#.#", "###" } },
+ { '1', { ".#.", "##.", ".#.", ".#.", "###" } },
+ { '2', { "###", "..#", "###", "#..", "###" } },
+ { '3', { "###", "..#", "###", "..#", "###" } },
+ { '4', { "#.#", "#.#", "###", "..#", "..#" } },
+ { '5', { "###", "#..", "###", "..#", "###" } },
+ { '6', { "###", "#..", "###", "#.#", "###" } },
+ { '7', { "###", "..#", "..#", "..#", "..#" } },
+ { '8', { "###", "#.#", "###", "#.#", "###" } },
+ { '9', { "###", "#.#", "###", "..#", "###" } },
+ { 'F', { "###", "#..", "##.", "#..", "#.." } },
+ { 'P', { "###", "#.#", "###", "#..", "#.." } },
+ { 'S', { ".##", "#..", ".#.", "..#", "##." } },
+};
+#define FONT_SIZE ((int)(sizeof FONT / sizeof FONT[0]))
+
/* A VAO + VBO of positions only (3 floats per vertex). */
typedef struct {
GLuint vao, vbo;
@@ -130,6 +176,8 @@ 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 Mesh s_hud_text; /* the FPS text, in font pixels; rebuilt when the number changes */
+static int s_hud_fps = -1; /* the number s_hud_text currently spells (-1 = none yet) */
static const char *VERTEX_SRC =
"#version 330 core\n"
@@ -391,6 +439,88 @@ static void draw_player(Mat4 vp, const Player *player)
draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, nose), COLOR_NOSE);
}
+/* ---- FPS counter ------------------------------------------------------- */
+
+/* Returns the font's glyph for ch, or NULL (e.g. a space) to leave a gap. */
+static const Glyph *find_glyph(char ch)
+{
+ for (int i = 0; i < FONT_SIZE; i++)
+ if (FONT[i].ch == ch)
+ return &FONT[i];
+ return NULL;
+}
+
+/* Writes one font pixel (a unit square as two triangles, hanging down and to
+ * the right of its top-left corner x, y) at out[0..17]; returns the next slot. */
+static float *put_pixel(float *out, float x, float y)
+{
+ static const float CORNERS[6][2] = {
+ { 0, 0 }, { 1, 0 }, { 1, -1 },
+ { 0, 0 }, { 1, -1 }, { 0, -1 },
+ };
+ for (int i = 0; i < 6; i++) {
+ out[i * 3 + 0] = x + CORNERS[i][0];
+ out[i * 3 + 1] = y + CORNERS[i][1];
+ out[i * 3 + 2] = 0.0f;
+ }
+ return out + 18;
+}
+
+/* Rebuilds s_hud_text to spell `text`, measured in font pixels with the
+ * origin at the text's TOP-RIGHT corner, so it's right-aligned for free. */
+static void build_hud_text(const char *text)
+{
+ static float verts[HUD_MAX_CHARS * GLYPH_W * GLYPH_H * 6 * 3];
+ int len = (int)strlen(text);
+ float left = -(float)(len * GLYPH_ADVANCE - 1); /* no gap after the last glyph */
+ float *out = verts;
+
+ for (int i = 0; i < len && i < HUD_MAX_CHARS; i++) {
+ const Glyph *glyph = find_glyph(text[i]);
+ if (!glyph)
+ continue;
+ float x = left + (float)(i * GLYPH_ADVANCE);
+ for (int row = 0; row < GLYPH_H; row++)
+ for (int col = 0; col < GLYPH_W; col++)
+ if (glyph->rows[row][col] == '#')
+ out = put_pixel(out, x + (float)col, -(float)row);
+ }
+
+ s_hud_text.vertex_count = (GLsizei)((out - verts) / 3);
+ glBindBuffer(GL_ARRAY_BUFFER, s_hud_text.vbo);
+ glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)((size_t)(out - verts) * sizeof(float)), verts, GL_DYNAMIC_DRAW);
+}
+
+/* "<fps> FPS" in the top-right corner, for keeping an eye on performance. */
+static void draw_fps(int fps, float aspect)
+{
+ if (fps <= 0) /* not measured yet */
+ return;
+ if (fps != s_hud_fps) {
+ char text[HUD_MAX_CHARS + 1];
+ snprintf(text, sizeof text, "%d FPS", fps);
+ build_hud_text(text);
+ s_hud_fps = fps;
+ }
+
+ /* Screen space in window heights: x in [0, aspect], y in [0, 1] from the
+ * bottom left. Using the height as the unit keeps font pixels square. */
+ Mat4 screen = mat4_mul(mat4_translate(vec3_make(-1.0f, -1.0f, 0.0f)),
+ mat4_scale(vec3_make(2.0f / aspect, 2.0f, 1.0f)));
+ Vec3 corner = vec3_make(aspect - HUD_MARGIN, 1.0f - HUD_MARGIN, 0.0f);
+ Vec3 shadow = vec3_add(corner, vec3_make(HUD_SHADOW_OFFSET * HUD_PIXEL,
+ -HUD_SHADOW_OFFSET * HUD_PIXEL, 0.0f));
+ Mat4 pixel = mat4_scale(vec3_make(HUD_PIXEL, HUD_PIXEL, 1.0f));
+
+ /* Drawn last with no depth test, so the scene can never cover it. */
+ glDisable(GL_DEPTH_TEST);
+ draw_mesh(&s_hud_text, GL_TRIANGLES, mat4_mul(screen, mat4_mul(mat4_translate(shadow), pixel)),
+ COLOR_HUD_SHADOW);
+ draw_mesh(&s_hud_text, GL_TRIANGLES, mat4_mul(screen, mat4_mul(mat4_translate(corner), pixel)),
+ COLOR_HUD_TEXT);
+ glEnable(GL_DEPTH_TEST);
+}
+
/* ---- Public interface -------------------------------------------------- */
bool render_init(void)
@@ -407,10 +537,11 @@ bool render_init(void)
}
build_cube();
build_disc();
+ s_hud_text = make_mesh(NULL, 0); /* filled in by build_hud_text() once FPS is known */
return true;
}
-void render_frame(const Camera *cam, const Player *player, float aspect)
+void render_frame(const Camera *cam, const Player *player, float aspect, int fps)
{
glClearColor(SKY_COLOR_R, SKY_COLOR_G, SKY_COLOR_B, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -423,6 +554,7 @@ void render_frame(const Camera *cam, const Player *player, float aspect)
draw_platforms(vp);
draw_shadow(vp, player); /* before the player, so the player is drawn over it */
draw_player(vp, player);
+ draw_fps(fps, aspect); /* last: it sits on top of everything */
glBindVertexArray(0);
}
@@ -432,5 +564,6 @@ void render_shutdown(void)
delete_mesh(&s_grid);
delete_mesh(&s_cube);
delete_mesh(&s_disc);
+ delete_mesh(&s_hud_text);
glDeleteProgram(s_program);
}
diff --git a/platformer/src/render.h b/platformer/src/render.h
index 24dcf5e..fd95f3b 100644
--- a/platformer/src/render.h
+++ b/platformer/src/render.h
@@ -13,14 +13,17 @@
*
* 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_frame(const Camera *cam, const Player *player, float aspect,
+ * int fps); fps is shown in the top-right corner;
+ * pass 0 until it has been measured
* 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.
+ * NOT IN SCOPE: A general renderer / scene graph, materials, textures, general
+ * text (only the FPS counter).
*
* DONE WHEN: main.c can draw everything with these three calls.
* ============================================================
@@ -34,7 +37,7 @@
#include "player.h"
bool render_init(void);
-void render_frame(const Camera *cam, const Player *player, float aspect);
+void render_frame(const Camera *cam, const Player *player, float aspect, int fps);
void render_shutdown(void);
#endif /* RENDER_H */