]> git.localhorst.tv Git - blank.git/blobdiff - src/geometry/geometry.cpp
faster ray/box test for AABBs
[blank.git] / src / geometry / geometry.cpp
index 1e84fbb9068d1749fbe5a3edcc81519aa7718e87..668e72930c9bfbe91de362de09fc0f59660e9c95 100644 (file)
@@ -49,6 +49,23 @@ std::ostream &operator <<(std::ostream &out, const Ray &ray) {
        return out << "Ray(" << ray.orig << ", " << ray.dir << ')';
 }
 
+bool Intersection(
+       const Ray &ray,
+       const AABB &box,
+       float &dist
+) noexcept {
+       float t_min = 0.0f;
+       float t_max = std::numeric_limits<float>::infinity();
+       for (int i = 0; i < 3; ++i) {
+               float t1 = (box.min[i] - ray.orig[i]) * ray.inv_dir[i];
+               float t2 = (box.max[i] - ray.orig[i]) * ray.inv_dir[i];
+               t_min = std::max(t_min, std::min(t1, t2));
+               t_max = std::min(t_max, std::max(t1, t2));
+       }
+       dist = t_min;
+       return t_max >= t_min;
+}
+
 bool Intersection(
        const Ray &ray,
        const AABB &aabb,
@@ -85,12 +102,11 @@ bool Intersection(
                }
        }
 
-       glm::vec3 min_all(min(t1, t2));
-
        if (dist) {
                *dist = t_min;
        }
        if (normal) {
+               glm::vec3 min_all(min(t1, t2));
                if (min_all.x > min_all.y) {
                        if (min_all.x > min_all.z) {
                                normal->x = t2.x < t1.x ? 1 : -1;
@@ -106,7 +122,6 @@ bool Intersection(
        return true;
 }
 
-
 bool Intersection(
        const AABB &a_box,
        const glm::mat4 &a_m,