matrix math beginnings

This commit is contained in:
Luca Conte 2025-04-02 17:26:16 +02:00
parent 40979a9a31
commit e0f3c7d2ff
4 changed files with 103 additions and 1 deletions

View File

@ -6,7 +6,8 @@ m_dep = cc.find_library('m', required : false)
src_files = [ src_files = [
'./src/main.c', './src/main.c',
'./src/shader.c', './src/shader.c',
'./src/log.c' './src/log.c',
'./src/matrix-math.c'
] ]
executable('cg1', executable('cg1',

View File

@ -10,6 +10,7 @@
#include "shader.h" #include "shader.h"
#include "log.h" #include "log.h"
#include "shader.h" #include "shader.h"
#include "matrix-math.h"
#define STATUS_INTERVAL 0.5 #define STATUS_INTERVAL 0.5
@ -78,6 +79,16 @@ void updateStatusDisplay() {
} }
void init(void) { void init(void) {
mat4 t = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16
};
mat4Print(t);
INFO("Compiling Shaders..."); INFO("Compiling Shaders...");
// create and compile vertex shader // create and compile vertex shader

67
src/matrix-math.c Normal file
View File

@ -0,0 +1,67 @@
#include "matrix-math.h"
#include <math.h>
#include <stdio.h>
/**
* overwrites a 4x4 matrix with the identity matrix
*/
void mat4Identity(mat4 mat) {
for (int i = 0; i < 16; i++) {
mat[i] = (i % 4 == i / 4) ? 1 : 0;
}
}
/**
* copies a mat4 from src to dst
*/
void mat4Copy(mat4 src, mat4 dst) {
for (int i = 0; i < 16; i++) {
dst[i] = src[i];
}
}
/**
* sets all the values in a mat4 to zero
*/
void mat4Empty(mat4 mat) {
for (int i = 0; i < 16; i++) {
mat[i] = 0;
}
}
/**
* mutliplies A with B and stores the result in results
*/
void mat4Multiply(mat4 result, mat4 A, mat4 B) {
// if result is one of the arguments, modify copy instead of result directly
if (result == A || result == B) {
mat4 tempResult;
mat4Multiply(tempResult, A, B);
mat4Copy(tempResult, result);
return;
}
for (int i = 0; i < 16; i++) {
int col = i / 4;
int row = i % 4;
GLfloat* curr = &(result[i]);
*curr = 0;
for (int j = 0; j < 4; j++) {
*curr += A[row + j * 4] * B[j + col * 4];
}
}
}
/**
* prints a mat4 to the screen
*/
void mat4Print(mat4 m) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%.2f ", m[j * 4 + i]);
}
printf("\n");
}
}

23
src/matrix-math.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef MATRIX_MATH_H
#define MATRIX_MATH_H
#include <GL/gl.h>
// TODO: figure out better type definition to avoid constant casting to GLfloat*
// possibly typedef float mat4[16];
/**
* !!! ALL matrices are in column major
*/
typedef GLfloat vec4[4];
typedef GLfloat mat4[16];
extern void mat4Identity(mat4 mat);
extern void mat4Copy(mat4 src, mat4 dst);
extern void mat4Empty(mat4 mat);
extern void mat4Multiply(mat4 result, mat4 A, mat4 B);
extern void mat4Print(mat4 m);
#endif