feat(mat4): add mat4 basic functions

This commit is contained in:
2025-06-09 21:49:58 +02:00
parent d456cbc3a7
commit 35d7f0da36
10 changed files with 130 additions and 17 deletions

11
CMakeLists.txt Normal file
View File

@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.10)
project(t3dsr C)
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra")
include_directories(src)
file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS src/*.c)
add_executable(main ${SOURCES})

View File

@@ -1,12 +1,7 @@
#include "math/vec3.h" #include "math/vec3.h"
#include <stdio.h> #include <stdio.h>
#define printVector3(v) { printf("(%f, %f, %f)", v.x, v.y, v.z); } int main(void)
int main()
{ {
Vec3 vec = vec3(1, 1, 1);
Vec3 val = vec3_add(vec, vec3(1, 2, 3));
printVector3(val);
return 0; return 0;
} }

View File

@@ -8,12 +8,12 @@ Mat3_t mat3(const float arr[9])
return mat; return mat;
} }
Mat3_t mat3_zro() Mat3_t mat3_zro(void)
{ {
return (Mat3_t){0}; return (Mat3_t){0};
} }
Mat3_t mat3_ity() Mat3_t mat3_ity(void)
{ {
return (Mat3_t) {{ return (Mat3_t) {{
1, 0, 0, 1, 0, 0,

View File

@@ -8,9 +8,9 @@ typedef struct
Mat3_t mat3(const float arr[9]); Mat3_t mat3(const float arr[9]);
Mat3_t mat3_zro(); Mat3_t mat3_zro(void);
Mat3_t mat3_ity(); Mat3_t mat3_ity(void);
Mat3_t mat3_add(const Mat3_t* m1, const Mat3_t* m2); Mat3_t mat3_add(const Mat3_t* m1, const Mat3_t* m2);

77
src/math/mat4.c Normal file
View File

@@ -0,0 +1,77 @@
#include "mat4.h"
#include <string.h>
Mat4_t mat4(const float arr[16])
{
Mat4_t mat;
memcpy(mat.m, arr, 16*sizeof(float));
return mat;
}
Mat4_t mat4_zro(void)
{
return (Mat4_t){0};
}
Mat4_t mat4_ity(void)
{
return (Mat4_t) {{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
}};
}
Mat4_t mat4_add(const Mat4_t* m1, const Mat4_t* m2)
{
Mat4_t mat;
for(int i = 0; i<16; i++) {
mat.m[i] = m1->m[i] + m2->m[i];
}
return mat;
}
Mat4_t mat4_sub(const Mat4_t* m1, const Mat4_t* m2)
{
Mat4_t mat;
for(int i = 0; i<16; i++) {
mat.m[i] = m1->m[i] - m2->m[i];
}
return mat;
}
Mat4_t mat4_scl(const Mat4_t* m, float scalar)
{
Mat4_t mat;
for(int i = 0; i<16; i++) {
mat.m[i] = m->m[i] * scalar;
}
return mat;
}
Mat4_t mat4_mul(const Mat4_t* m1, const Mat4_t* m2)
{
Mat4_t mat;
for(int i = 0; i<4; i++) {
int i3 = i * 3;
for (int j = 0; j < 4; j++) {
float sum = 0;
for (int k = 0; k < 3; k++) {
sum += m1->m[i3 + k] * m2->m[k*3 + j];
}
mat.m[i3 + j] = sum;
}
}
return mat;
}

30
src/math/mat4.h Normal file
View File

@@ -0,0 +1,30 @@
#ifndef MATRIX4_H
#define MATRIX4_H
typedef struct
{
float m[16];
} Mat4_t;
Mat4_t mat4(const float arr[16]);
Mat4_t mat4_zro(void);
Mat4_t mat4_ity(void);
Mat4_t mat4_add(const Mat4_t* m1, const Mat4_t* m2);
Mat4_t mat4_sub(const Mat4_t* m1, const Mat4_t* m2);
Mat4_t mat4_scl(const Mat4_t* m, float scalar);
// row * col
Mat4_t mat4_mul(const Mat4_t* m1, const Mat4_t* m2);
Mat4_t mat4_tpo(const Mat4_t* m);
float mat4_det(const Mat4_t* m);
Mat4_t mat4_inv(const Mat4_t* m);
#endif // MATRIX4_H