]> git.localhorst.tv Git - blank.git/blob - src/model/geometry.hpp
make AI entities avoid world collisions
[blank.git] / src / model / geometry.hpp
1 #ifndef BLANK_MODEL_GEOMETRY_H_
2 #define BLANK_MODEL_GEOMETRY_H_
3
4 #include <algorithm>
5 #include <limits>
6 #include <glm/glm.hpp>
7
8
9 namespace blank {
10
11 constexpr float PI = 3.141592653589793238462643383279502884;
12 constexpr float PI_0p25 = PI * 0.25f;
13 constexpr float PI_0p5 = PI * 0.5f;
14 constexpr float PI_1p5 = PI * 1.5f;
15 constexpr float PI_2p0 = PI * 2.0f;
16
17 constexpr float PI_inv = 1.0f / PI;
18 constexpr float PI_0p5_inv = 1.0f / PI_0p5;
19
20 constexpr float DEG_RAD_FACTOR = PI / 180.0f;
21 constexpr float RAD_DEG_FACTOR = 180.0f / PI;
22
23 constexpr float deg2rad(float d) noexcept {
24         return d * DEG_RAD_FACTOR;
25 }
26
27 constexpr float rad2deg(float r) noexcept {
28         return r * RAD_DEG_FACTOR;
29 }
30
31
32 inline float length_squared(const glm::vec3 &v) noexcept {
33         return dot(v, v);
34 }
35
36 inline float distance_squared(const glm::vec3 &a, const glm::vec3 &b) noexcept {
37         return length_squared(a - b);
38 }
39
40
41 template <class T>
42 inline bool iszero(const T &v) noexcept {
43         return length_squared(v) < std::numeric_limits<typename T::value_type>::epsilon();
44 }
45
46
47 template<class T>
48 T manhattan_distance(const glm::tvec3<T> &a, const glm::tvec3<T> &b) noexcept {
49         glm::tvec3<T> diff(abs(a - b));
50         return diff.x + diff.y + diff.z;
51 }
52
53 template<class T>
54 T manhattan_radius(const glm::tvec3<T> &v) noexcept {
55         glm::tvec3<T> a(abs(v));
56         return std::max(a.x, std::max(a.y, a.z));
57 }
58
59
60 glm::mat3 find_rotation(const glm::vec3 &a, const glm::vec3 &b) noexcept;
61
62
63 struct AABB {
64         glm::vec3 min;
65         glm::vec3 max;
66
67         void Adjust() noexcept {
68                 if (max.x < min.x) std::swap(max.x, min.x);
69                 if (max.y < min.y) std::swap(max.y, min.y);
70                 if (max.z < min.z) std::swap(max.z, min.z);
71         }
72
73         glm::vec3 Center() const noexcept {
74                 return min + (max - min) * 0.5f;
75         }
76 };
77
78 struct Ray {
79         glm::vec3 orig;
80         glm::vec3 dir;
81 };
82
83 bool Intersection(
84         const Ray &,
85         const AABB &,
86         const glm::mat4 &M,
87         float *dist = nullptr,
88         glm::vec3 *normal = nullptr) noexcept;
89
90 bool Intersection(
91         const AABB &a_box,
92         const glm::mat4 &a_m,
93         const AABB &b_box,
94         const glm::mat4 &b_m,
95         float &depth,
96         glm::vec3 &normal) noexcept;
97
98 bool CullTest(const AABB &box, const glm::mat4 &MVP) noexcept;
99
100 }
101
102 #endif