Created
June 26, 2023 11:58
-
-
Save Leowbattle/a16bad38678904621421983b8eeff659 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef struct mat4 { | |
float m[16]; | |
} mat4; | |
typedef struct vec3 { | |
float x; | |
float y; | |
float z; | |
} vec3; | |
typedef struct vec4 { | |
float x; | |
float y; | |
float z; | |
float w; | |
} vec4; | |
mat4 frustum(float l, float r, float b, float t, float n, float f) { | |
return (mat4){ | |
2 * n / (r - l), 0, -(r + l) / (r - l), 0, | |
0, 2 * n / (t - b), -(t + b) / (t - b), 0, | |
0, 0, (f + n) / (f - n), -2 * f * n / (f - n), | |
0, 0, 1, 0, | |
}; | |
} | |
vec4 mat4_mul_vec4(mat4 m, vec4 v) { | |
float* M = m.m; | |
return (vec4){ | |
v.x * M[0] + v.y * M[1] + v.z * M[2] + v.w * M[3], | |
v.x * M[4] + v.y * M[5] + v.z * M[6] + v.w * M[7], | |
v.x * M[8] + v.y * M[9] + v.z * M[10] + v.w * M[11], | |
v.x * M[12] + v.y * M[13] + v.z * M[14] + v.w * M[15], | |
}; | |
} | |
vec4 transform(mat4 m, vec4 v) { | |
v = mat4_mul_vec4(m, v); | |
v.x /= v.w; | |
v.y /= v.w; | |
v.z /= v.w; | |
v.w /= v.w; | |
return v; | |
} | |
float l = -1; | |
float r = 1; | |
float b = -1; | |
float t = 1; | |
float n = 0.1f; | |
float f = 10; | |
mat4 proj; | |
void func(float x, float y, float z) { | |
vec4 v = transform(proj, (vec4){x, y, z, 1}); | |
printf("%f %f %f %f\n", v.x, v.y, v.z, v.w); | |
} | |
int main(int argc, char** argv) { | |
proj = frustum(l, r, b, t, n, f); | |
func(l, b, n); | |
func(r, b, n); | |
func(l, t, n); | |
func(r, t, n); | |
func(l, b, f); | |
func(r, b, f); | |
func(l, t, f); | |
func(r, t, f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment