| PSHOT-ENG — Build Your Own 3D Engine in ISO C89 | Contents | Chapter 02 | Going Further |
Write a pure ISO C89 3D vector and 4x4 matrix library, clip and rasterize 2D lines with Cohen-Sutherland and Bresenham, and fly around a spinning 3D wireframe cube.
| Chapter: | 02 Duration: 1 hr |
| Files: | src/math3d.h, src/math3d.c, src/draw.h, src/draw.c, src/main.c, Makefile |
| Concepts: | Left-handed 3D space, 4x4 homogeneous matrices, perspective divide, Cohen-Sutherland clipping, Bresenham lines, delta-time |
| On this page: | Coordinate System · 3D Math Library · 2D Line Rasterizer · Spinning Cube · Build & Verify · Exercises · Recap |
Before writing a single matrix, lock down the axes so signs never surprise you:
With +Z forward, a vertex in front of the camera has positive depth z > 0. Perspective projection stores that depth in w, and dividing x / w and y / w makes distant edges shrink naturally toward the center of the screen.
Create src/math3d.h and src/math3d.c. Notice two C89 details: we define PI ourselves because M_PI is POSIX (hidden under -std=c89 -pedantic), and we call sin/cos/tan/sqrt rather than C99’s sinf/cosf.
| src/math3d.h (c) |
#ifndef MATH3D_H
#define MATH3D_H
#define PI 3.14159265358979323846f
#define DEG2RAD(d) ((d) * (PI / 180.0f))
typedef struct {
float x;
float y;
float z;
} Vec3;
typedef struct {
float x;
float y;
float z;
float w;
} Vec4;
typedef struct {
float m[4][4];
} Mat4;
Vec3 v3_make(float x, float y, float z);
Vec3 v3_add(Vec3 a, Vec3 b);
Vec3 v3_sub(Vec3 a, Vec3 b);
Vec3 v3_scale(Vec3 v, float s);
float v3_dot(Vec3 a, Vec3 b);
Vec3 v3_cross(Vec3 a, Vec3 b);
float v3_len(Vec3 v);
Vec3 v3_norm(Vec3 v);
Mat4 m4_identity(void);
Mat4 m4_mul(Mat4 a, Mat4 b);
Vec4 m4_mul_v4(Mat4 m, Vec4 v);
Mat4 m4_translate(float tx, float ty, float tz);
Mat4 m4_rot_x(float rad);
Mat4 m4_rot_y(float rad);
Mat4 m4_rot_z(float rad);
Mat4 m4_perspective(float fov_deg,
float aspect,
float znear,
float zfar);
Mat4 m4_view_fps(Vec3 pos, float yaw, float pitch);
#endif |
| src/math3d.c (c) |
#include "math3d.h"
#include <math.h>
#include <string.h>
Vec3 v3_make(float x, float y, float z) {
Vec3 v;
v.x = x;
v.y = y;
v.z = z;
return v;
}
Vec3 v3_add(Vec3 a, Vec3 b) {
return v3_make(a.x + b.x, a.y + b.y, a.z + b.z);
}
Vec3 v3_sub(Vec3 a, Vec3 b) {
return v3_make(a.x - b.x, a.y - b.y, a.z - b.z);
}
Vec3 v3_scale(Vec3 v, float s) {
return v3_make(v.x * s, v.y * s, v.z * s);
}
float v3_dot(Vec3 a, Vec3 b) {
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
Vec3 v3_cross(Vec3 a, Vec3 b) {
return v3_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));
}
float v3_len(Vec3 v) {
return (float)sqrt((double)v3_dot(v, v));
}
Vec3 v3_norm(Vec3 v) {
float len;
float inv;
len = v3_len(v);
if (len < 0.000001f) { return v3_make(0.0f, 0.0f, 0.0f); }
inv = 1.0f / len;
return v3_scale(v, inv);
}
Mat4 m4_identity(void) {
Mat4 r;
memset(&r, 0, sizeof(r));
r.m[0][0] = 1.0f;
r.m[1][1] = 1.0f;
r.m[2][2] = 1.0f;
r.m[3][3] = 1.0f;
return r;
}
Mat4 m4_mul(Mat4 a, Mat4 b) {
Mat4 r;
int row;
int col;
for (row = 0; row < 4; ++row) {
for (col = 0; col < 4; ++col) {
r.m[row][col] = (a.m[row][0] * b.m[0][col]) +
(a.m[row][1] * b.m[1][col]) +
(a.m[row][2] * b.m[2][col]) +
(a.m[row][3] * b.m[3][col]);
}
}
return r;
}
Vec4 m4_mul_v4(Mat4 m, Vec4 v) {
Vec4 r;
r.x = (m.m[0][0] * v.x) + (m.m[0][1] * v.y) + (m.m[0][2] * v.z) + (m.m[0][3] * v.w);
r.y = (m.m[1][0] * v.x) + (m.m[1][1] * v.y) + (m.m[1][2] * v.z) + (m.m[1][3] * v.w);
r.z = (m.m[2][0] * v.x) + (m.m[2][1] * v.y) + (m.m[2][2] * v.z) + (m.m[2][3] * v.w);
r.w = (m.m[3][0] * v.x) + (m.m[3][1] * v.y) + (m.m[3][2] * v.z) + (m.m[3][3] * v.w);
return r;
}
Mat4 m4_translate(float tx, float ty, float tz) {
Mat4 r;
r = m4_identity();
r.m[0][3] = tx;
r.m[1][3] = ty;
r.m[2][3] = tz;
return r;
}
Mat4 m4_rot_x(float rad) {
Mat4 r;
float c;
float s;
c = (float)cos((double)rad);
s = (float)sin((double)rad);
r = m4_identity();
r.m[1][1] = c;
r.m[1][2] = -s;
r.m[2][1] = s;
r.m[2][2] = c;
return r;
}
Mat4 m4_rot_y(float rad) {
Mat4 r;
float c;
float s;
c = (float)cos((double)rad);
s = (float)sin((double)rad);
r = m4_identity();
r.m[0][0] = c;
r.m[0][2] = s;
r.m[2][0] = -s;
r.m[2][2] = c;
return r;
}
Mat4 m4_rot_z(float rad) {
Mat4 r;
float c;
float s;
c = (float)cos((double)rad);
s = (float)sin((double)rad);
r = m4_identity();
r.m[0][0] = c;
r.m[0][1] = -s;
r.m[1][0] = s;
r.m[1][1] = c;
return r;
}
Mat4 m4_perspective(float fov_deg, float aspect, float znear, float zfar) {
Mat4 r;
float f;
float inv_range;
memset(&r, 0, sizeof(r));
f = 1.0f / (float)tan((double)DEG2RAD(fov_deg * 0.5f));
inv_range = 1.0f / (zfar - znear);
r.m[0][0] = f / aspect;
r.m[1][1] = f;
r.m[2][2] = zfar * inv_range;
r.m[2][3] = -(zfar * znear) * inv_range;
r.m[3][2] = 1.0f;
return r;
}
Mat4 m4_view_fps(Vec3 pos, float yaw, float pitch) {
Mat4 rx;
Mat4 ry;
Mat4 tr;
rx = m4_rot_x(-pitch);
ry = m4_rot_y(-yaw);
tr = m4_translate(-pos.x, -pos.y, -pos.z);
return m4_mul(rx, m4_mul(ry, tr));
} |
| C89 Note: Why -lm Must Stay at the End of LDFLAGS GCC’s linker resolves symbols left to right. Because math3d.o calls sin, cos, tan, and sqrt, keeping -lm after $(OBJS) in Makefile ensures the linker pulls those functions from libm. |
A naive line drawer crashes or wraps across rows the moment a projected vertex flies outside [0..319] x [0..239]. In src/draw.c, clip_line_2d trims every segment cleanly to the screen rectangle using 4-bit region outcodes before Bresenham’s integer algorithm steps pixel by pixel with zero floating-point math inside the inner loop.
| src/draw.h (c) |
#ifndef DRAW_H
#define DRAW_H
#include "types.h"
void fb_clear(Framebuffer *fb, u32 color);
void fb_pixel(Framebuffer *fb, int x, int y, u32 color);
void fb_line(Framebuffer *fb,
int x0,
int y0,
int x1,
int y1,
u32 color);
#endif |
| src/draw.c (c) |
#include "draw.h"
#define CLIP_INSIDE 0
#define CLIP_LEFT 1
#define CLIP_RIGHT 2
#define CLIP_BOTTOM 4
#define CLIP_TOP 8
static int clip_code(int x, int y, int w, int h) {
int code;
code = CLIP_INSIDE;
if (x < 0) { code |= CLIP_LEFT; }
else if (x >= w) { code |= CLIP_RIGHT; }
if (y < 0) { code |= CLIP_TOP; }
else if (y >= h) { code |= CLIP_BOTTOM; }
return code;
}
static int clip_line_2d(int *x0, int *y0, int *x1, int *y1, int w, int h) {
int c0;
int c1;
int out;
int x;
int y;
c0 = clip_code(*x0, *y0, w, h);
c1 = clip_code(*x1, *y1, w, h);
for (;;) {
if ((c0 | c1) == 0) { return 1; }
if ((c0 & c1) != 0) { return 0; }
out = c0 ? c0 : c1;
x = 0;
y = 0;
if (out & CLIP_TOP) {
x = *x0 + ((*x1 - *x0) * (0 - *y0)) / (*y1 - *y0);
y = 0;
} else if (out & CLIP_BOTTOM) {
x = *x0 + ((*x1 - *x0) * ((h - 1) - *y0)) / (*y1 - *y0);
y = h - 1;
} else if (out & CLIP_RIGHT) {
y = *y0 + ((*y1 - *y0) * ((w - 1) - *x0)) / (*x1 - *x0);
x = w - 1;
} else if (out & CLIP_LEFT) {
y = *y0 + ((*y1 - *y0) * (0 - *x0)) / (*x1 - *x0);
x = 0;
}
if (out == c0) {
*x0 = x;
*y0 = y;
c0 = clip_code(*x0, *y0, w, h);
} else {
*x1 = x;
*y1 = y;
c1 = clip_code(*x1, *y1, w, h);
}
}
}
void fb_clear(Framebuffer *fb, u32 color) {
int i;
int count;
u32 *dst;
if (!fb || !fb -> pixels) { return; }
count = fb -> width * fb -> height;
dst = fb -> pixels;
for (i = 0; i < count; ++i) { dst[i] = color; }
}
void fb_pixel(Framebuffer *fb, int x, int y, u32 color) {
if (!fb || !fb -> pixels) { return; }
if (x < 0 || x >= fb -> width || y < 0 || y >= fb -> height) { return; }
fb -> pixels[(y * fb -> width) + x] = color;
}
void fb_line(Framebuffer *fb, int x0, int y0, int x1, int y1, u32 color) {
int dx;
int dy;
int sx;
int sy;
int err;
int e2;
if (!fb || !fb -> pixels) { return; }
if (!clip_line_2d(&x0, &y0, &x1, &y1, fb -> width, fb -> height)) { return; }
dx = x1 - x0;
dy = y1 - y0;
sx = (dx < 0) ? -1 : 1;
sy = (dy < 0) ? -1 : 1;
if (dx < 0) { dx = -dx; }
if (dy < 0) { dy = -dy; }
err = dx - dy;
for (;;) {
fb -> pixels[(y0 * fb -> width) + x0] = color;
if (x0 == x1 && y0 == y1) { break; }
e2 = err * 2;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
} |
Update Makefile so SRCS compiles the two new modules:
| Makefile (SRCS line) (makefile) |
SRCS = src/main.c src/platform.c src/math3d.c src/draw.c |
Now replace src/main.c with our first 3D loop. We compute delta time dt in seconds (clamped to 0.1f so pausing the window doesn’t teleport you), transform 8 cube corners by MVP = proj * view * model, and draw all 12 edges.
| src/main.c (c) |
#include "types.h"
#include "platform.h"
#include "math3d.h"
#include "draw.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const Vec3 g_cube_verts[8] = {
{ -1.0f, -1.0f, -1.0f },
{ 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, -1.0f },
{ -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f },
{ 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f },
{ -1.0f, 1.0f, 1.0f }
};
static const int g_cube_edges[12][2] = {
{ 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 0 },
{ 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 4 },
{ 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 }
};
static int project_point(Mat4 mvp,
Vec3 p,
int fb_w,
int fb_h,
int *sx,
int *sy) {
Vec4 v;
Vec4 c;
float inv_w;
float nx;
float ny;
v.x = p.x;
v.y = p.y;
v.z = p.z;
v.w = 1.0f;
c = m4_mul_v4(mvp, v);
if (c.w <= 0.1f) { return 0; }
inv_w = 1.0f / c.w;
nx = c.x * inv_w;
ny = c.y * inv_w;
*sx = (int)((nx + 1.0f) * 0.5f * (float)fb_w);
*sy = (int)((1.0f - ny) * 0.5f * (float)fb_h);
return 1;
}
int main(int argc, char *argv[]) {
Framebuffer fb;
InputState input;
Vec3 cam_pos;
float cam_yaw;
float angle;
u32 last_ticks;
u32 fps_timer;
u32 frames;
(void)argc;
(void)argv;
fb.width = FB_WIDTH;
fb.height = FB_HEIGHT;
fb.pixels = (u32 *)malloc((size_t)(fb.width * fb.height) * sizeof(u32));
if (!fb.pixels) {
fprintf(stderr, "OUT OF MEMORY ALLOCATING FRAME BUFFER...\n");
return 1;
}
if (!plat_init("PSHOT-ENG -- CH 02 WIREFRAME", fb.width, fb.height, WIN_SCALE)) {
free(fb.pixels);
return 1;
}
memset(&input, 0, sizeof(input));
cam_pos = v3_make(0.0f, 0.0f, -4.5f);
cam_yaw = 0.0f;
angle = 0.0f;
last_ticks = plat_get_ticks();
fps_timer = last_ticks;
frames = 0;
while (!input.quit) {
u32 now;
u32 dt_ms;
float dt;
float speed;
float sin_y;
float cos_y;
Mat4 model;
Mat4 view;
Mat4 proj;
Mat4 mvp;
int sx[8];
int sy[8];
int ok[8];
int i;
now = plat_get_ticks();
dt_ms = now - last_ticks;
last_ticks = now;
dt = (float)dt_ms * 0.001f;
if (dt > 0.1f) { dt = 0.1f; }
plat_poll_input(&input);
if (input.keys[KEY_LEFT]) { cam_yaw -= 1.8f * dt; }
if (input.keys[KEY_RIGHT]) { cam_yaw += 1.8f * dt; }
speed = 3.5f * dt;
sin_y = (float)sin((double)cam_yaw);
cos_y = (float)cos((double)cam_yaw);
if (input.keys[KEY_W]) {
cam_pos.x += sin_y * speed;
cam_pos.z += cos_y * speed;
}
if (input.keys[KEY_S]) {
cam_pos.x -= sin_y * speed;
cam_pos.z -= cos_y * speed;
}
if (input.keys[KEY_A]) {
cam_pos.x -= cos_y * speed;
cam_pos.z += sin_y * speed;
}
if (input.keys[KEY_D]) {
cam_pos.x += cos_y * speed;
cam_pos.z -= sin_y * speed;
}
angle += 1.1f * dt;
model = m4_mul(m4_rot_y(angle), m4_rot_x(angle * 0.6f));
view = m4_view_fps(cam_pos, cam_yaw, 0.0f);
proj = m4_perspective(70.0f,
(float)fb.width / (float)fb.height,
0.1f,
100.0f);
mvp = m4_mul(proj, m4_mul(view, model));
fb_clear(&fb, PACK_RGB(14, 16, 24));
for (i = 0; i < 8; ++i) {
ok[i] = project_point(mvp,
g_cube_verts[i],
fb.width,
fb.height,
&sx[i],
&sy[i]);
}
for (i = 0; i < 12; ++i) {
int a = g_cube_edges[i][0];
int b = g_cube_edges[i][1];
if (ok[a] && ok[b]) {
fb_line(&fb,
sx[a],
sy[a],
sx[b],
sy[b],
PACK_RGB(90, 235, 140));
}
}
plat_present(&fb);
++frames;
if (now - fps_timer >= 1000u) {
printf("FPS: %u\n", frames);
frames = 0;
fps_timer = now;
}
}
plat_shutdown();
free(fb.pixels);
return 0;
} |
| Pitfall: Vertices Behind the Camera (c.w <= 0.1f) If a vertex moves behind your eye, c.w becomes zero or negative and dividing by it flips the point upside down across the screen. For now, project_point rejects vertices with c.w <= 0.1f. In Chapter 03 we replace this crude drop with true 3D near-plane polygon clipping so walls passing right past your face stay rock-solid. |
| Terminal (bash) |
make run |
You should see a crisp green wireframe cube tumbling smoothly against a dark navy background. Use W/A/S/D to move around it and Left/Right Arrow keys to turn the camera.
m4_translate(3.0f, 0.0f, 2.0f) in a different color so you can judge depth parallax while strafing.y = -1.5f spanning -10 to +10 in X and Z.KEY_UP and KEY_DOWN to tilt cam_pitch and pass it into m4_view_fps.MVP = proj * view * model transforms local object corners into clip space in one matrix multiply.(x, y) by w creates perspective foreshortening.| « Ch 01: Platform Layer | Table of Contents | Ch 03: Filled Triangles & Z-Buffer » |