-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.c
116 lines (94 loc) · 2.58 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <math.h>
#include <stdlib.h>
#include "math.h" // shit, rename
float randf() {
return (float)(rand()) / (float)(RAND_MAX);
}
float clamp (float v, float min, float max) {
return v < min ? min : (v > max ? max : v);
}
float scale (float v, float in_min, float in_max, float out_min, float out_max) {
return out_min + ((out_max) - out_min) * (((v) - in_min) / ((in_max) - in_min));
}
float anglemod(float r) {
return atan2f(sinf(r), cosf(r));
}
// TODO remove both of these
vec3_t vec3(float x, float y, float z) {
return (vec3_t) {
.x = x, .y = y, .z = z
};
}
vec3_t vec3_clone(vec3_t a) {
return (vec3_t) {
.x = a.x, .y = a.y, .z = a.z
};
}
// TODO, change a lot of these to void(), pass pointers and modify
vec3_t vec3_rotate_y(vec3_t p, float rad) {
return (vec3_t) {
p.z * sinf(rad) + p.x * cosf(rad), p.y, p.z * cosf(rad) - p.x * sinf(rad)
};
}
vec3_t vec3_rotate_x(vec3_t p, float rad) {
return (vec3_t) {
p.x, p.y * cosf(rad) - p.z * sinf(rad), p.y * sinf(rad) + p.z * cosf(rad)
};
}
vec3_t vec3_rotate_yaw_pitch(vec3_t p, float yaw, float pitch) {
return vec3_rotate_y(vec3_rotate_x(p, pitch), yaw);
}
float vec3_2d_angle(vec3_t a, vec3_t b) {
return atan2f(b.x - a.x, b.z - a.z);
}
float vec3_length(vec3_t a) {
// C doesn't have a 3-argument hypot()
return sqrt(a.x*a.x+a.y*a.y+a.z*a.z);
}
vec3_t vec3_sub(vec3_t a, vec3_t b) {
return (vec3_t) {
a.x - b.x, a.y - b.y, a.z - b.z
};
}
float vec3_dist(vec3_t a, vec3_t b) {
return vec3_length(vec3_sub(a, b));
}
float vec3_dot(vec3_t a, vec3_t b) {
return (a.x * b.x + a.y * b.y + a.z * b.z);
}
vec3_t vec3_add(vec3_t a, vec3_t b) {
return (vec3_t) {
a.x + b.x, a.y + b.y, a.z + b.z
};
}
vec3_t vec3_mul(vec3_t a, vec3_t b) {
return (vec3_t) {
a.x * b.x, a.y * b.y, a.z * b.z
};
}
vec3_t vec3_mulf(vec3_t a, float b) {
return (vec3_t) {
a.x * b, a.y * b, a.z * b
};
}
vec3_t vec3_divf(vec3_t a, float b) {
return (vec3_t) {
a.x / b, a.y / b, a.z / b
};
}
vec3_t vec3_cross(vec3_t a, vec3_t b) {
return (vec3_t) {
a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x
};
}
vec3_t vec3_normalize(vec3_t v) {
// this seems like trash, but some
// of the finer models have a vlen of ~0
float vlen = vec3_length(v);
if(vlen <= 0.001f)
vlen = 0.001f;
return vec3_mulf(v, 1/vlen);
}
vec3_t vec3_face_normal(vec3_t v0, vec3_t v1, vec3_t v2) {
return vec3_normalize(vec3_cross(vec3_sub(v0, v1), vec3_sub(v2, v1)));
}