This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.c
98 lines (85 loc) · 2.15 KB
/
math.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#define TOLERANCE 0.0001f
typedef struct {
float x, y, z;
} v3;
static inline v3 newV3(float x, float y, float z) {
v3 result;
result.x = x;
result.y = y;
result.z = z;
return result;
}
static inline v3 mulV3(float a, v3 u) {
v3 result;
result.x = a * u.x;
result.y = a * u.y;
result.z = a * u.z;
return result;
}
static inline v3 addV3(v3 u, v3 v) {
v3 result;
result.x = u.x + v.x;
result.y = u.y + v.y;
result.z = u.z + v.z;
return result;
}
static inline v3 subtractV3(v3 u, v3 v) {
v3 result;
result.x = u.x - v.x;
result.y = u.y - v.y;
result.z = u.z - v.z;
return result;
}
static inline float dotV3(v3 u, v3 v) {
return u.x * v.x + u.y * v.y + u.z * v.z;
}
static inline v3 crossV3(v3 u, v3 v) {
v3 result;
result.x = u.y * v.z - u.z * v.y;
result.y = -(u.x * v.z - u.z * v.x);
result.z = u.x * v.y - u.y * v.x;
return result;
}
static inline v3 normalizeV3(v3 v) {
v3 result = {0};
float norm = sqrtf(dotV3(v, v));
if (norm > TOLERANCE * TOLERANCE) {
result.x = v.x / norm;
result.y = v.y / norm;
result.z = v.z / norm;
}
return result;
}
static inline v3 lookAt(v3 cP, v3 u, v3 v, v3 w, v3 p) {
v3 result;
result.x = u.x * p.x + u.y * p.y + u.z * p.z - dotV3(u, cP);
result.y = v.x * p.x + v.y * p.y + v.z * p.z - dotV3(v, cP);
result.z = w.x * p.x + w.y * p.y + w.z * p.z - dotV3(w, cP);
return result;
}
static inline v3 perspective(float f, float aspect, float zNear, float zFar, v3 p) {
v3 result;
// TODO: not sure if this is correct.
if (fabsf(p.z) < TOLERANCE) {
result.x = (f / aspect) * p.x;
result.y = f * p.y;
result.z = 1.0f;
} else {
result.x = (f / aspect) * p.x / (-p.z);
result.y = f * p.y / (-p.z);
//result.z = (zFar+zNear)/(zNear-zFar) * p.z + (2*zFar*zNear)/(zNear-zFar);
result.z = 1.0f;
}
return result;
}
typedef struct {
float x, y, z, w;
} v4;
static inline v4 fromV3(v3 v) {
v4 result;
result.x = v.x;
result.y = v.y;
result.z = v.z;
result.w = 0.0f;
return result;
}