the loop
the whole program's essentially just three routines. process input, update, and render. update goes through every face of the mesh, transforms its three vertices, projects them to 2d, and pushes the resulting screen space triangle into a list. render then clears the buffer and draws every triangle in that list as three lines. the list is thrown away and rebuilt every frame.
while (is_running) {
process_input();
update();
render();
}the window
sdl's only job is to show the buffer. the colour buffer is one uint32_t per pixel in argb, uploaded into a streaming texture once per frame and copied to the window. resizing the window frees the buffer and the texture and allocates both again at the new size, so the renderer follows the window instead of stretching.
dynamic arrays in c
since the number of vertices, faces, and triangles isn't known ahead of time the renderer needs arrays that can grow dynamically. C doesn't provide built-in dynamic arrays, so we make one. some useful information about the array is its current capacity and the number of elements in use... so let's have the header include that metadata. the returned pointer skips over this metadata, allowing the array to be accessed and indexed like a regular C array. when a new element is added and the array has reached its capacity, the push macro automatically reallocates the buffer, doubling its capacity to accommodate more elements without requiring a new allocation for every insertion.
#define array_push(array, value) \
do { \
(array) = array_hold((array), 1, sizeof(*(array))); \
(array)[array_length(array) - 1] = (value); \
} while (0);
#define ARRAY_RAW_DATA(array) ((int*)(array) - 2)
#define ARRAY_CAPACITY(array) (ARRAY_RAW_DATA(array)[0])
#define ARRAY_OCCUPIED(array) (ARRAY_RAW_DATA(array)[1])
void* array_hold(void* array, int count, int item_size) {
if (array == NULL) {
int* base = (int*)malloc((sizeof(int) * 2) + (item_size * count));
base[0] = count; // capacity
base[1] = count; // occupied
return base + 2;
} else if (ARRAY_OCCUPIED(array) + count <= ARRAY_CAPACITY(array)) {
ARRAY_OCCUPIED(array) += count;
return array;
} else {
int needed_size = ARRAY_OCCUPIED(array) + count;
int double_curr = ARRAY_CAPACITY(array) * 2;
int capacity = needed_size > double_curr ? needed_size : double_curr;
int* base = (int*)realloc(ARRAY_RAW_DATA(array), sizeof(int) * 2 + item_size * capacity);
base[0] = capacity;
base[1] = needed_size;
return base + 2;
}
}the array_push macro reassigns the array pointer every call, because a realloc may move the block.
loading obj files
models come in as wavefront obj, straight out of blender. the loader only cares about two kinds of line. v x y z is a vertex. f a b c ... is a face where each token is a 1-based index into the vertex list and might carry texture and normal indices after slashes, like 12/5/9.
faces aren't always triangles. blender happily exports quads and n-gons, so every face is fan-triangulated on the way in. for a face with vertices $1, 2, 3, 4$ you get the triangles $(1,2,3)$ and $(1,3,4)$, and in general $n$ vertices give $n - 2$ triangles that all share the first vertex.
// f 1 2 3 4 becomes (1 2 3) and (1 3 4)
for (int i = 1; i < index_count - 1; i++) {
face_t face = {
.a = indices[0],
.b = indices[i],
.c = indices[i + 1]
};
array_push(mesh.faces, face);
}rotation
each frame the mesh's rotation on every axis is nudged by $0.007$ radians and every vertex is run through three rotations in turn. a rotation about the $y$ axis leaves $y$ alone and spins $x$ and $z$:
$$\begin{aligned} x' &= x \cos\theta - z \sin\theta \\ z' &= x \sin\theta + z \cos\theta \end{aligned}$$
the $x$ and $z$ rotations are the same shape with the axes permuted. doing it as three separate functions instead of one matrix makes it easier to see what each axis is doing.
vec3_t vec3_rotate_y(vec3_t v, float a) {
vec3_t rotated = {
.x = v.x * cos(a) - v.z * sin(a),
.y = v.y,
.z = v.x * sin(a) + v.z * cos(a),
};
return rotated;
}projection
after rotation the mesh is still centered on the origin which is where the camera is. so the camera sits at $z = -5$ and every vertex is pushed $5$ units away from it. perspective projection divides $x$ and $y$ by $z$, so things further away shrink toward the centre:
$$x_{screen} = \frac{f \cdot x}{z} + \frac{w}{2}, \qquad y_{screen} = -\frac{f \cdot y}{z} + \frac{h}{2}$$
$f$ is a scale factor in pixels and it's bound to the scroll wheel and clamped between $100$ and $2000$.
vec2_t project(vec3_t point) {
vec2_t projected = { .x = (fov * point.x) / point.z, .y = (fov * point.y) / point.z };
return projected;
}
// per vertex, in update()
vec3_t t = vec3_rotate_x(vert, mesh.rotation.x);
t = vec3_rotate_y(t, mesh.rotation.y);
t = vec3_rotate_z(t, mesh.rotation.z);
t.z -= camera_pos.z; // camera is at z = -5
vec2_t p = project(t);
p.x += (res_x / 2);
p.y *= -1; // blender's y is up, the buffer's y is down
p.y += (res_y / 2);
there's a check in there for vertices with $z \le 0.1$, which would be at or behind the camera and would divide to nonsense.
drawing lines
with three 2d points per triangle, drawing a wireframe is three lines. the line routine is dda: take the larger of $|\Delta x|$ and $|\Delta y|$ as the number of steps, divide both deltas by it so one axis advances exactly one pixel per step and the other advances by a fraction, and round at each step.
void draw_line(int x0, int y0, int x1, int y1, uint32_t color) {
int delta_x = (x1 - x0);
int delta_y = (y1 - y0);
int side_length = abs(delta_x) > abs(delta_y) ? abs(delta_x) : abs(delta_y);
float x_inc = delta_x / (float)side_length;
float y_inc = delta_y / (float)side_length;
float current_x = x0;
float current_y = y0;
for (int i = 0; i <= side_length; i++) {
draw_pixel(round(current_x), round(current_y), color);
current_x += x_inc;
current_y += y_inc;
}
}source
Makefile11 lines
build:
mkdir build && gcc -Wall -std=c99 ./src/*.c -o ./build/renderer -lSDL2 -lm
run:
./build/renderer 0
clean:
rm -rf ./build
dev:
make clean && make build && make runsrc/main.c218 lines
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
#include "display.h"
#include "vector.h"
#include "mesh.h"
#include "array.h"
#include <unistd.h>
triangle_t* triangles_to_render= NULL;
bool is_running = false;
bool fullscreen = false;
int previous_frame_time = 0;
vec3_t camera_pos = { 0.0, 0.0, -5.0 };
float fov = 1200;
void setup(void) {
color_buffer = (uint32_t*) malloc(sizeof(uint32_t) * res_x * res_y);
color_buffer_texture = SDL_CreateTexture(
renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
res_x,
res_y
);
//load_cube_mesh_data();
// load_obj_data("models/cube.obj");
// load_obj_data("models/ak74m.obj");
load_obj_data("models/ak74m_tri.obj");
// load_obj_data("models/ainz.obj");
// load_obj_data("models/girl.obj");
}
void process_input(void) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type)
{
case SDL_QUIT:
is_running = false;
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_ESCAPE)
is_running = false;
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
res_x = event.window.data1;
res_y = event.window.data2;
free(color_buffer);
SDL_DestroyTexture(color_buffer_texture);
color_buffer = malloc(sizeof(uint32_t) * res_x * res_y);
color_buffer_texture = SDL_CreateTexture(
renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
res_x,
res_y
);
}
break;
case SDL_MOUSEWHEEL:
fov += event.wheel.y * 25.0f;
if (fov < 100.0f) {
fov = 100.0f;
}
if (fov > 2000.0f) {
fov = 2000.0f;
}
printf("fov: %f\n", fov);
break;
}
}
}
vec2_t project(vec3_t point) {
vec2_t projected = { .x = (fov * point.x) / point.z, .y = (fov * point.y) / point.z };
return projected;
}
void update(void) {
int time_to_wait = FRAME_TARGET_TIME - (SDL_GetTicks() - previous_frame_time);
if (time_to_wait > 0 && time_to_wait <= FRAME_TARGET_TIME) {
SDL_Delay(time_to_wait);
}
previous_frame_time = SDL_GetTicks();
if (triangles_to_render != NULL) {
array_free(triangles_to_render);
triangles_to_render = NULL;
}
mesh.rotation.x += 0.007;
mesh.rotation.y += 0.007;
mesh.rotation.z += 0.007;
int n_faces = array_length(mesh.faces);
int n_vertices = array_length(mesh.vertices);
for (int i = 0; i < n_faces; i++) {
face_t mesh_face = mesh.faces[i];
if (
mesh_face.a <= 0 || mesh_face.a > n_vertices ||
mesh_face.b <= 0 || mesh_face.b > n_vertices ||
mesh_face.c <= 0 || mesh_face.c > n_vertices
) {
continue;
}
vec3_t face_verts[3];
face_verts[0] = mesh.vertices[mesh_face.a - 1];
face_verts[1] = mesh.vertices[mesh_face.b - 1];
face_verts[2] = mesh.vertices[mesh_face.c - 1];
triangle_t projected_triangle;
bool should_skip_triangle = false;
for (int j = 0; j < 3; j++) {
vec3_t vert = face_verts[j];
vec3_t transformed_vert = vec3_rotate_x(vert, mesh.rotation.x);
transformed_vert = vec3_rotate_y(transformed_vert, mesh.rotation.y);
transformed_vert = vec3_rotate_z(transformed_vert, mesh.rotation.z);
transformed_vert.z -= camera_pos.z;
if (transformed_vert.z <= 0.1f) {
should_skip_triangle = true;
break;
}
vec2_t projected_vert = project(transformed_vert);
projected_vert.x += (res_x / 2);
// flip coordinates so that y increases as you go up the screen instead of down. (useful for blender models)
projected_vert.y *= -1;
projected_vert.y += (res_y / 2);
projected_triangle.points[j] = projected_vert;
}
// if (should_skip_triangle) {
// continue;
// }
array_push(triangles_to_render, projected_triangle);
}
}
void render(void) {
clear_color_buffer(0xff363636);
draw_grid(10, 0xFF000000, true);
int n_triangles = array_length(triangles_to_render);
for (int i = 0; i < n_triangles; i++) {
triangle_t triangle = triangles_to_render[i];
for (int j = 0; j < 3; j++) {
draw_rectangle(4, 4, 0xFFFFFF00, triangle.points[j].x, triangle.points[j].y);
}
draw_triangle(triangle);
}
// draw_rectangle(200, 150, 0xFFFFFF00, res_x / 2, res_y / 2);
// draw_pixel(res_x / 2, res_y / 2, 0xFFFF0000);
render_color_buffer();
SDL_RenderPresent(renderer);
}
void free_resources(void) {
array_free(mesh.faces);
array_free(mesh.vertices);
free(color_buffer);
}
int main(int argc, char** argv) {
if (argc > 1) {
fullscreen = strcmp(argv[1], "1") == 0 ? true : false;
}
printf("arguments initialized: %d\nfullscreen: %d\n", argc, fullscreen);
is_running = init_window(fullscreen);
setup();
while (is_running) {
process_input();
update();
render();
}
destroy_window();
free_resources();
return 0;
}src/display.h33 lines
#ifndef DISPLAY_H
#define DISPLAY_H
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
#include "triangle.h"
#define FPS 60
#define FRAME_TARGET_TIME (1000 / FPS)
extern SDL_Window* window;
extern SDL_Renderer* renderer;
extern SDL_Texture* color_buffer_texture;
extern uint32_t* color_buffer;
extern int res_x;
extern int res_y;
bool init_window(bool fullscreen);
void destroy_window(void);
void clear_color_buffer(uint32_t color);
void draw_pixel(int x, int y, uint32_t color);
void draw_grid(int mult, uint32_t color, bool dot);
void draw_rectangle(int width, int height, uint32_t color, int x, int y);
// void draw_triangle(int angle_apart, int leg_length, uint32_t color, int x, int y);
void draw_circle(int radius, uint32_t color, int x, int y);
void draw_line(int x0, int y0, int x1, int y1, uint32_t color);
void draw_triangle(triangle_t triangle);
void render_color_buffer(void);
#endifsrc/display.c157 lines
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
#include "display.h"
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Texture* color_buffer_texture = NULL;
uint32_t* color_buffer = NULL;
int res_x = 500;
int res_y = 500;
bool init_window(bool fullscreen) {
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
fprintf(stderr, "error on initializing sdl...\n");
return false;
}
SDL_DisplayMode display_mode;
SDL_GetCurrentDisplayMode(0, &display_mode);
window = SDL_CreateWindow(
// NULL,
"Photis",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
fullscreen ? display_mode.w : res_x,
fullscreen ? display_mode.h : res_y,
// SDL_WINDOW_BORDERLESS
SDL_WINDOW_SHOWN
);
if (!window) {
fprintf(stderr, "error creating window...\n");
return false;
}
renderer = SDL_CreateRenderer(
window,
-1,
0
);
if (!renderer) {
fprintf(stderr, "error creating renderer...\n");
return false;
}
if (fullscreen) {
SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
}
return true;
}
void destroy_window(void) {
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void clear_color_buffer(uint32_t color) {
for (int y = 0; y < res_y; y++) {
for (int x = 0; x < res_x; x++) {
color_buffer[(res_x * y) + x] = color;
}
}
}
void draw_pixel(int x, int y, uint32_t color) {
if (x >= 0 && x < res_x && y >=0 && y < res_y) {
color_buffer[(res_x * y) + x] = color;
}
}
void draw_grid(int mult, uint32_t color, bool dot)
{
for (int row = 0; row < res_y; row++) {
for (int col = 0; col < res_x; col++) {
if (dot) {
if (row % mult == 0 && col % mult == 0) {
draw_pixel(col, row, color);
}
} else {
if (row % mult == 0 || col % mult == 0) {
draw_pixel(col, row, color);
}
}
}
}
}
void draw_rectangle(int width, int height, uint32_t color, int x, int y) {
x = x - (width / 2);
y = y - (height / 2);
for (int row = y; row < y + height; row++) {
if (row < 0 || row >= res_y) continue;
for (int col = x; col < x + width; col++) {
if (col < 0 || col >= res_x) continue;
color_buffer[row * res_x + col] = color;
}
}
}
// void draw_triangle(int angle_apart, int leg_length, uint32_t color, int x, int y) {
// //
// }
void draw_circle(int radius, uint32_t color, int x, int y) {
//
}
void draw_line(int x0, int y0, int x1, int y1, uint32_t color) {
int delta_x = (x1 - x0);
int delta_y = (y1 - y0);
int side_length = abs(delta_x) > abs(delta_y) ? abs(delta_x) : abs(delta_y);
float x_inc = delta_x / (float)side_length;
float y_inc = delta_y / (float)side_length;
float current_x = x0;
float current_y = y0;
for (int i = 0; i <= side_length; i++) {
draw_pixel(round(current_x), round(current_y), color);
current_x += x_inc;
current_y += y_inc;
}
}
void draw_triangle(triangle_t triangle) {
draw_line(triangle.points[0].x, triangle.points[0].y, triangle.points[1].x, triangle.points[1].y, 0xFFFFFFFF);
draw_line(triangle.points[1].x, triangle.points[1].y, triangle.points[2].x, triangle.points[2].y, 0xFFFFFFFF);
draw_line(triangle.points[2].x, triangle.points[2].y, triangle.points[0].x, triangle.points[0].y, 0xFFFFFFFF);
}
void render_color_buffer(void) {
SDL_UpdateTexture(
color_buffer_texture,
NULL,
color_buffer,
(int)(res_x * sizeof(uint32_t))
);
SDL_RenderCopy(
renderer,
color_buffer_texture,
NULL,
NULL
);
}src/vector.h19 lines
#ifndef VECTOR_H
#define VECTOR_H
typedef struct {
float x;
float y;
} vec2_t;
typedef struct {
float x;
float y;
float z;
} vec3_t;
vec3_t vec3_rotate_x(vec3_t v, float a);
vec3_t vec3_rotate_y(vec3_t v, float a);
vec3_t vec3_rotate_z(vec3_t v, float a);
#endifsrc/vector.c29 lines
#include "vector.h"
#include <math.h>
vec3_t vec3_rotate_x(vec3_t v, float a) {
vec3_t rotated = {
.x = v.x,
.y = v.y * cos(a) - v.z * sin(a),
.z = v.y * sin(a) + v.z * cos(a),
};
return rotated;
}
vec3_t vec3_rotate_y(vec3_t v, float a) {
vec3_t rotated = {
.x = v.x * cos(a) - v.z * sin(a),
.y = v.y,
.z = v.x * sin(a) + v.z * cos(a),
};
return rotated;
}
vec3_t vec3_rotate_z(vec3_t v, float a) {
vec3_t rotated = {
.x = v.x * cos(a) - v.y * sin(a),
.y = v.x * sin(a) + v.y * cos(a),
.z = v.z,
};
return rotated;
}src/triangle.h16 lines
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include "vector.h"
typedef struct {
int a;
int b;
int c;
} face_t;
typedef struct {
vec2_t points[3];
} triangle_t;
#endifsrc/triangle.c1 lines
#include "triangle.h"src/mesh.h26 lines
#ifndef MESH_H
#define MESH_H
#include "vector.h"
#include "triangle.h"
#include <stdbool.h>
#define N_CUBE_VERTICES 8
extern vec3_t cube_vertices[N_CUBE_VERTICES];
#define N_CUBE_FACES (6 * 2) // 6 cube faces, 2 triangles per face
extern face_t cube_faces[N_CUBE_FACES];
typedef struct {
vec3_t* vertices;
face_t* faces;
vec3_t rotation;
} mesh_t;
extern mesh_t mesh;
void load_cube_mesh_data(void);
bool load_obj_data(char* filename);
#endifsrc/mesh.c150 lines
#include "mesh.h"
#include "array.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
mesh_t mesh = {
.vertices = NULL,
.faces = NULL,
.rotation = { 0, 0, 0 }
};
vec3_t cube_vertices[N_CUBE_VERTICES] = {
{ .x = -1, .y = -1, .z = -1 }, // 1
{ .x = -1, .y = 1, .z = -1 }, // 2
{ .x = 1, .y = 1, .z = -1 }, // 3
{ .x = 1, .y = -1, .z = -1 }, // 4
{ .x = 1, .y = 1, .z = 1 }, // 5
{ .x = 1, .y = -1, .z = 1 }, // 6
{ .x = -1, .y = 1, .z = 1 }, // 7
{ .x = -1, .y = -1, .z = 1 } // 8
};
face_t cube_faces[N_CUBE_FACES] = {
// front
{ .a = 1, .b = 2, .c = 3 },
{ .a = 1, .b = 3, .c = 4 },
// right
{ .a = 4, .b = 3, .c = 5 },
{ .a = 4, .b = 5, .c = 6 },
// back
{ .a = 6, .b = 5, .c = 7 },
{ .a = 6, .b = 7, .c = 8 },
// left
{ .a = 8, .b = 7, .c = 2 },
{ .a = 8, .b = 2, .c = 1 },
// top
{ .a = 2, .b = 7, .c = 5 },
{ .a = 2, .b = 5, .c = 3 },
// bottom
{ .a = 6, .b = 8, .c = 1 },
{ .a = 6, .b = 1, .c = 4 }
};
void load_cube_mesh_data(void) {
for (int i = 0; i < N_CUBE_VERTICES; i++) {
vec3_t cube_vertex = cube_vertices[i];
array_push(mesh.vertices, cube_vertex);
}
for (int i = 0; i < N_CUBE_FACES; i++) {
face_t cube_face = cube_faces[i];
array_push(mesh.faces, cube_face);
}
}
static int parse_obj_vertex_index(char* token)
{
// token examples:
// "12"
// "12/5"
// "12/5/9"
// "12//9"
int index = 0;
sscanf(token, "%d", &index);
return index;
}
bool load_obj_data(char* filename)
{
FILE* file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Failed to open OBJ file: %s\n", filename);
return false;
}
char line[1024];
int vertices = 0;
int faces = 0;
printf("Model information:\n");
while (fgets(line, sizeof(line), file)) {
if (line[0] == 'v' && line[1] == ' ') {
vec3_t vertex;
if (sscanf(line, "v %f %f %f", &vertex.x, &vertex.y, &vertex.z) == 3) {
array_push(mesh.vertices, vertex);
vertices++;
}
}
else if (line[0] == 'f' && line[1] == ' ') {
int indices[16];
int index_count = 0;
char* token = strtok(line, " \t\n\r"); // "f"
token = strtok(NULL, " \t\n\r"); // first vertex token
while (token != NULL && index_count < 16) {
int vertex_index = parse_obj_vertex_index(token);
if (vertex_index <= 0) {
fprintf(stderr, "Invalid face index: %s\n", token);
break;
}
indices[index_count++] = vertex_index;
token = strtok(NULL, " \t\n\r");
}
if (index_count < 3) {
fprintf(stderr, "Face has fewer than 3 vertices: %s\n", line);
continue;
}
// Triangulate polygon using fan triangulation:
// f 1 2 3 4 becomes:
// triangle 1: 1 2 3
// triangle 2: 1 3 4
for (int i = 1; i < index_count - 1; i++) {
face_t face = {
.a = indices[0],
.b = indices[i],
.c = indices[i + 1]
};
array_push(mesh.faces, face);
faces++;
}
}
}
fclose(file);
printf(" - Vertices count: %d\n", vertices);
printf(" - Faces count: %d\n", faces);
return true;
}src/array.h14 lines
#ifndef ARRAY_H
#define ARRAY_H
#define array_push(array, value) \
do { \
(array) = array_hold((array), 1, sizeof(*(array))); \
(array)[array_length(array) - 1] = (value); \
} while (0);
void* array_hold(void* array, int count, int item_size);
int array_length(void* array);
void array_free(void* array);
#endifsrc/array.c40 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#define ARRAY_RAW_DATA(array) ((int*)(array) - 2)
#define ARRAY_CAPACITY(array) (ARRAY_RAW_DATA(array)[0])
#define ARRAY_OCCUPIED(array) (ARRAY_RAW_DATA(array)[1])
void* array_hold(void* array, int count, int item_size) {
if (array == NULL) {
int raw_size = (sizeof(int) * 2) + (item_size * count);
int* base = (int*)malloc(raw_size);
base[0] = count; // capacity
base[1] = count; // occupied
return base + 2;
} else if (ARRAY_OCCUPIED(array) + count <= ARRAY_CAPACITY(array)) {
ARRAY_OCCUPIED(array) += count;
return array;
} else {
int needed_size = ARRAY_OCCUPIED(array) + count;
int double_curr = ARRAY_CAPACITY(array) * 2;
int capacity = needed_size > double_curr ? needed_size : double_curr;
int occupied = needed_size;
int raw_size = sizeof(int) * 2 + item_size * capacity;
int* base = (int*)realloc(ARRAY_RAW_DATA(array), raw_size);
base[0] = capacity;
base[1] = occupied;
return base + 2;
}
}
int array_length(void* array) {
return (array != NULL) ? ARRAY_OCCUPIED(array) : 0;
}
void array_free(void* array) {
if (array != NULL) {
free(ARRAY_RAW_DATA(array));
}
}