From d1f29580aeb6d4e0d2e6f54bef61a9ad46a69926 Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Sat, 27 Sep 2025 14:07:41 +0100 Subject: [PATCH] Implement perspective projection matrix computation --- main.c | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/main.c b/main.c index 5eb3813..b97b41c 100644 --- a/main.c +++ b/main.c @@ -9,6 +9,9 @@ #define M_PI 3.14159265358979324 #endif +#define W 800 +#define H 600 + static const vertex_t vertices[] = { { { -1, -1 }, { 1, 0, 0 } }, { { 1, -1 }, { 0, 1, 0 } }, @@ -78,13 +81,30 @@ static void mul(mat4_t out, const mat4_t left, const mat4_t right) } } +static void persp(mat4_t out, float aspect, float fov, float ncp, float fcp) +{ + const float r = 2 * ncp * tanf(fov / 2); + const float t = r * aspect; + + // clang-format off + const mat4_t m = { + ncp / t, 0, 0, 0, + 0, -ncp / r, 0, 0, + 0, 0, fcp / (fcp - ncp), 1, + 0, 0, -fcp * ncp / (fcp - ncp), 0, + }; + // clang-format on + + memcpy(out, m, sizeof(mat4_t)); +} + int main() { // Set up window glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); - GLFWwindow *window = glfwCreateWindow(800, 800, "Foo", nullptr, nullptr); + GLFWwindow *window = glfwCreateWindow(W, H, "Foo", nullptr, nullptr); assert(window); // Register input callbacks @@ -103,10 +123,10 @@ int main() gpu_init(&gpu, &gpu_config); mvp_t mvp = { - .model = SCALE(0.2), - .view = TRANSLATE(0, 0, 0.5), - .proj = ID, + .model = ID, + .view = TRANSLATE(0, 0, 4.0), }; + persp(mvp.proj, (float)W / H, M_PI / 6, 0.1, 10.0); const mat4_t rot = ROT_Y(M_PI / 128); while (!glfwWindowShouldClose(window)) {