]> git.localhorst.tv Git - blobs.git/blob - src/math/geometry.hpp
add ray/box intersect test
[blobs.git] / src / math / geometry.hpp
1 #ifndef BLOBS_MATH_GEOMETRY_HPP_
2 #define BLOBS_MATH_GEOMETRY_HPP_
3
4 #include "glm.hpp"
5
6 #include <algorithm>
7
8
9 namespace blobs {
10 namespace math {
11
12 struct AABB {
13
14         glm::dvec3 min;
15         glm::dvec3 max;
16
17         void Adjust() noexcept {
18                 if (max.x < min.x) std::swap(max.x, min.x);
19                 if (max.y < min.y) std::swap(max.y, min.y);
20                 if (max.z < min.z) std::swap(max.z, min.z);
21         }
22
23         glm::dvec3 Center() const noexcept {
24                 return min + (max - min) * 0.5;
25         }
26
27 };
28
29 /// matrices must not scale
30 bool Intersect(
31         const AABB &a_box,
32         const glm::dmat4 &a_m,
33         const AABB &b_box,
34         const glm::dmat4 &b_m,
35         glm::dvec3 &normal,
36         double &depth) noexcept;
37
38 class Ray {
39
40 public:
41         Ray(const glm::dvec3 &orig, const glm::dvec3 &dir)
42         : orig(orig), dir(dir), inv_dir(1.0 / dir) { }
43
44         void Origin(const glm::dvec3 &o) noexcept { orig = o; }
45         const glm::dvec3 &Origin() const noexcept { return orig; }
46         void Direction(const glm::dvec3 &d) noexcept { dir = d; inv_dir = 1.0 / d; }
47         const glm::dvec3 &Direction() const noexcept { return dir; }
48         const glm::dvec3 &InverseDirection() const noexcept { return inv_dir; }
49
50 private:
51         glm::dvec3 orig;
52         glm::dvec3 dir;
53         glm::dvec3 inv_dir;
54
55 };
56
57 /// oriented ray/box intersection test
58 bool Intersect(
59         const Ray &,
60         const AABB &,
61         const glm::dmat4 &M,
62         glm::dvec3 &normal,
63         double &dist) noexcept;
64
65 }
66 }
67
68 #endif