From 519fbd131a9c3f2bf4e30c90626f6cca311ea1e6 Mon Sep 17 00:00:00 2001 From: Alex Selimov Date: Fri, 23 Oct 2026 23:01:53 -0400 Subject: [PATCH] Finish basic vec3 and start on mat3 --- mathprimitives/mathprimitives.h | 25 +++++++++++++++++++++++++ mathprimitives/test.c | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/mathprimitives/mathprimitives.h b/mathprimitives/mathprimitives.h index c6dc769..58c19c9 100644 --- a/mathprimitives/mathprimitives.h +++ b/mathprimitives/mathprimitives.h @@ -30,9 +30,34 @@ static inline double vec3_dot(struct Vec3 a, struct Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +static inline struct Vec3 vec3_scale(struct Vec3 a, double b) { + struct Vec3 c = {.x = a.x * b, .y = a.y * b, .z = a.z * b}; + return c; +} + +static inline struct Vec3 vec3_cross(struct Vec3 a, struct Vec3 b) { + double x = a.y * b.z - a.z * b.y; + double y = a.z * b.x - a.x * b.z; + double z = a.x * b.y - a.y * b.x; + struct Vec3 c = {x, y, z}; + return c; +} + static inline int vec3_eql_tol(struct Vec3 a, struct Vec3 b, double tol) { return fabs(a.x - b.x) < tol && fabs(a.y - b.y) < tol && fabs(a.z - b.z) < tol; } +struct Mat3 { + struct Vec3 r1; + struct Vec3 r2; + struct Vec3 r3; +}; + +static inline struct Mat3 mat3_identity() { + struct Mat3 i = { + .r1 = {1.0, 0.0, 0.0}, .r2 = {0.0, 1.0, 0.0}, .r3 = {0.0, 0.0, 1.0}}; + return i; +} + #endif diff --git a/mathprimitives/test.c b/mathprimitives/test.c index 1e1196f..52188f9 100644 --- a/mathprimitives/test.c +++ b/mathprimitives/test.c @@ -55,6 +55,35 @@ int test_vec3_dot() { return fabs(real_dot - expected_dot) < 1e-12; } +int test_vec3_scale() { + struct Vec3 a = {.x = 1.0, .y = 2.0, .z = 3.0}; + double b = 3.0; + struct Vec3 expected_c = {.x = 3.0, .y = 6.0, .z = 9.0}; + + struct Vec3 real_c = vec3_scale(a, b); + + return vec3_eql_tol(expected_c, real_c, 1e-12); +} + +int test_vec3_cross() { + struct Vec3 a = {.x = 1.0, .y = 2.0, .z = 3.0}; + struct Vec3 b = {.x = 3.0, .y = 1.0, .z = 0.0}; + struct Vec3 expected_c = {.x = -3.0, .y = 9.0, .z = -5.0}; + + struct Vec3 real_c = vec3_cross(a, b); + + return vec3_eql_tol(expected_c, real_c, 1e-12); +} + +int test_mat3_identity() { + struct Mat3 i = mat3_identity(); + return fabs(i.r1.x - 1.0) < 1e-12 && fabs(i.r1.y - 0.0) < 1e-12 && + fabs(i.r1.z - 0.0) < 1e-12 && fabs(i.r2.x - 0.0) < 1e-12 && + fabs(i.r2.y - 1.0) < 1e-12 && fabs(i.r2.z - 0.0) < 1e-12 && + fabs(i.r3.x - 0.0) < 1e-12 && fabs(i.r3.y - 0.0) < 1e-12 && + fabs(i.r3.z - 1.0) < 1e-12; +} + int main() { int tests_total = 0; int tests_passed = 0; @@ -63,11 +92,13 @@ int main() { run_test(test_vec3_add); run_test(test_vec3_sub); run_test(test_vec3_dot); + run_test(test_vec3_scale); + run_test(test_vec3_cross); + run_test(test_mat3_identity); if (tests_total == tests_passed) { printf("\033[92mAll tests passed!\033[0m"); } else { - printf("\033[91m%d of %d tests failed\033[0m", tests_total - tests_passed, tests_total); }