Finish out final mat3 functions. Revert to .h library

This commit is contained in:
Alex Selimov 2026-10-28 23:30:31 -04:00
parent 7e5de6f6eb
commit 139444ccc6
3 changed files with 48 additions and 29 deletions

View file

@ -1,28 +0,0 @@
#include "mathprimitives.h"
struct Mat3 mat3_inv(struct Mat3 a) {
double inv_det = 1.0 / mat3_det(a);
struct Vec3 r1 = vec3_scale(
(struct Vec3){
a.r2.y * a.r3.z - a.r2.z * a.r3.y,
a.r1.z * a.r3.y - a.r1.y * a.r3.z,
a.r1.y * a.r2.z - a.r1.z * a.r2.y,
},
inv_det);
struct Vec3 r2 = vec3_scale(
(struct Vec3){
a.r2.z * a.r3.x - a.r2.x * a.r3.z,
a.r1.x * a.r3.z - a.r1.z * a.r3.x,
a.r1.z * a.r2.x - a.r1.x * a.r2.z,
},
inv_det);
struct Vec3 r3 = vec3_scale(
(struct Vec3){
a.r2.x * a.r3.y - a.r2.y * a.r3.x,
a.r1.y * a.r3.x - a.r1.x * a.r3.y,
a.r1.x * a.r2.y - a.r1.y * a.r2.x,
},
inv_det);
return (struct Mat3){r1, r2, r3};
}

View file

@ -98,6 +98,39 @@ static inline double mat3_det(struct Mat3 a) {
a.r1.z * (a.r2.x * a.r3.y - a.r2.y * a.r3.x); a.r1.z * (a.r2.x * a.r3.y - a.r2.y * a.r3.x);
} }
struct Mat3 mat3_inv(struct Mat3 a); static struct Mat3 mat3_inv(struct Mat3 a) {
double inv_det = 1.0 / mat3_det(a);
struct Vec3 r1 = vec3_scale(
(struct Vec3){
a.r2.y * a.r3.z - a.r2.z * a.r3.y,
a.r1.z * a.r3.y - a.r1.y * a.r3.z,
a.r1.y * a.r2.z - a.r1.z * a.r2.y,
},
inv_det);
struct Vec3 r2 = vec3_scale(
(struct Vec3){
a.r2.z * a.r3.x - a.r2.x * a.r3.z,
a.r1.x * a.r3.z - a.r1.z * a.r3.x,
a.r1.z * a.r2.x - a.r1.x * a.r2.z,
},
inv_det);
struct Vec3 r3 = vec3_scale(
(struct Vec3){
a.r2.x * a.r3.y - a.r2.y * a.r3.x,
a.r1.y * a.r3.x - a.r1.x * a.r3.y,
a.r1.x * a.r2.y - a.r1.y * a.r2.x,
},
inv_det);
return (struct Mat3){r1, r2, r3};
}
static inline struct Vec3 mat3_mul_vec(struct Mat3 a, struct Vec3 b) {
return (struct Vec3){
vec3_dot(a.r1, b),
vec3_dot(a.r2, b),
vec3_dot(a.r3, b),
};
}
#endif #endif

View file

@ -135,6 +135,19 @@ int test_mat3_inv() {
return mat3_eql_tol(inv_a, expected_inv, 1e-11); return mat3_eql_tol(inv_a, expected_inv, 1e-11);
} }
int test_mat3_mul_vec3() {
struct Mat3 a = {
{0.0, 1.0, 0.0},
{0.0, 1.0, 1.0},
{0.0, 0.0, 1.0},
};
struct Vec3 b = {1.0, 2.0, 3.0};
struct Vec3 expected_c = {2.0, 5.0, 3.0};
return vec3_eql_tol(expected_c, mat3_mul_vec(a, b), 1e-12);
}
int main() { int main() {
int tests_total = 0; int tests_total = 0;
int tests_passed = 0; int tests_passed = 0;
@ -152,6 +165,7 @@ int main() {
run_test(test_mat3_mul); run_test(test_mat3_mul);
run_test(test_mat3_det); run_test(test_mat3_det);
run_test(test_mat3_inv); run_test(test_mat3_inv);
run_test(test_mat3_mul_vec3);
if (tests_total == tests_passed) { if (tests_total == tests_passed) {
printf("\033[92mAll tests passed!\033[0m"); printf("\033[92mAll tests passed!\033[0m");