diff options
Diffstat (limited to 'mons_math/src/mat2.c')
-rw-r--r-- | mons_math/src/mat2.c | 123 |
1 files changed, 123 insertions, 0 deletions
diff --git a/mons_math/src/mat2.c b/mons_math/src/mat2.c new file mode 100644 index 0000000..026b165 --- /dev/null +++ b/mons_math/src/mat2.c @@ -0,0 +1,123 @@ +#include "mons_math/mat2.h" + +const mons_mat2 MONS_MAT2_ZERO = { + {0, 0}, + {0, 0}, +}; + +const mons_mat2 MONS_MAT2_IDENTITY = { + {1, 0}, + {0, 1}, +}; + +mons_mat2 mons_mat2_add(mons_mat2 a, mons_mat2 b) { + mons_mat2 result = { + mons_vec2_add(a.m1, b.m1), + mons_vec2_add(a.m2, b.m2), + }; + return result; +} + +void mons_mat2_add_inplace(mons_mat2 *a, mons_mat2 b) { + mons_vec2_add_inplace(&a->m1, b.m1); + mons_vec2_add_inplace(&a->m2, b.m2); +} + +mons_mat2 mons_mat2_mul_f(mons_mat2 a, float b) { + mons_mat2 result = { + mons_vec2_mul_f(a.m1, b), + mons_vec2_mul_f(a.m2, b), + }; + return result; +} + +mons_mat2 mons_mat2_mul_i(mons_mat2 a, int b) { + mons_mat2 result = { + mons_vec2_mul_i(a.m1, b), + mons_vec2_mul_i(a.m2, b), + }; + return result; +} + +mons_mat2 mons_mat2_mul(mons_mat2 a, mons_mat2 b) { + mons_vec2 b_n1 = mons_mat2_n1(b); + mons_vec2 b_n2 = mons_mat2_n2(b); + + mons_mat2 result = { + { + mons_vec2_dot(a.m1, b_n1), + mons_vec2_dot(a.m1, b_n2), + }, + { + mons_vec2_dot(a.m2, b_n1), + mons_vec2_dot(a.m2, b_n2), + }, + }; + return result; +} + +void mons_mat2_mul_f_inplace(mons_mat2 *a, float b) { + mons_vec2_mul_f_inplace(&a->m1, b); + mons_vec2_mul_f_inplace(&a->m2, b); +} + +void mons_mat2_mul_i_inplace(mons_mat2 *a, int b) { + mons_vec2_mul_i_inplace(&a->m1, b); + mons_vec2_mul_i_inplace(&a->m2, b); +} + +mons_mat2 mons_mat2_transpose(mons_mat2 a) { + mons_mat2 result = { + mons_mat2_n1(a), + mons_mat2_n2(a), + }; + return result; +} + +void mons_mat2_transpose_inplace(mons_mat2 *a) { *a = mons_mat2_transpose(*a); } + +mons_vec2 mons_mat2_n1(mons_mat2 a) { + mons_vec2 result = { + a.m1.x, + a.m2.x, + }; + return result; +} + +mons_vec2 mons_mat2_n2(mons_mat2 a) { + mons_vec2 result = { + a.m1.y, + a.m2.y, + }; + return result; +} + +float mons_mat2_determinant(mons_mat2 a) { + // ad - bc + return (a.m1.x * a.m2.y) - (a.m1.y * a.m2.x); +} + +mons_mat2 mons_mat2_adjoint(mons_mat2 a) { + /* + * d -b + * -c a + */ + mons_mat2 result = {{ + a.m2.y, + -a.m1.y, + }, + { + -a.m2.x, + a.m1.x, + }}; + return result; +} + +mons_mat2 mons_mat2_inverse(mons_mat2 a) { + return mons_mat2_mul_f(mons_mat2_adjoint(a), + 1.0 / mons_mat2_determinant(a)); +} + +int mons_mat2_equal(mons_mat2 a, mons_mat2 b) { + return mons_vec2_equal(a.m1, b.m1) && mons_vec2_equal(a.m2, b.m2); +} |