1 #include "geometry.hpp"
17 const glm::vec3 aabb_pos(M[3].x, M[3].y, M[3].z);
18 const glm::vec3 delta = aabb_pos - ray.orig;
20 glm::vec3 t1(t_min, t_min, t_min), t2(t_max, t_max, t_max);
21 bool x_swap = false, y_swap = false, z_swap = false;
24 const glm::vec3 xaxis(M[0].x, M[0].y, M[0].z);
25 const float e = glm::dot(xaxis, delta);
26 const float f = glm::dot(ray.dir, xaxis);
28 if (std::abs(f) > std::numeric_limits<float>::epsilon()) {
29 t1.x = (e + aabb.min.x) / f;
30 t2.x = (e + aabb.max.x) / f;
33 std::swap(t1.x, t2.x);
46 if (aabb.min.x - e > 0.0f || aabb.max.x < 0.0f) {
53 const glm::vec3 yaxis(M[1].x, M[1].y, M[1].z);
54 const float e = glm::dot(yaxis, delta);
55 const float f = glm::dot(ray.dir, yaxis);
57 if (std::abs(f) > std::numeric_limits<float>::epsilon()) {
58 t1.y = (e + aabb.min.y) / f;
59 t2.y = (e + aabb.max.y) / f;
62 std::swap(t1.y, t2.y);
75 if (aabb.min.y - e > 0.0f || aabb.max.y < 0.0f) {
82 const glm::vec3 zaxis(M[2].x, M[2].y, M[2].z);
83 const float e = glm::dot(zaxis, delta);
84 const float f = glm::dot(ray.dir, zaxis);
86 if (std::abs(f) > std::numeric_limits<float>::epsilon()) {
87 t1.z = (e + aabb.min.z) / f;
88 t2.z = (e + aabb.max.z) / f;
91 std::swap(t1.z, t2.z);
104 if (aabb.min.z - e > 0.0f || aabb.max.z < 0.0f) {
116 *normal = glm::vec3(x_swap ? 1 : -1, 0, 0);
118 *normal = glm::vec3(0, 0, z_swap ? 1 : -1);
120 } else if (t1.y > t1.z) {
121 *normal = glm::vec3(0, y_swap ? 1 : -1, 0);
123 *normal = glm::vec3(0, 0, z_swap ? 1 : -1);
129 bool CullTest(const AABB &box, const glm::mat4 &MVP) {
130 // transform corners into clip space
131 glm::vec4 corners[8] = {
132 { box.min.x, box.min.y, box.min.z, 1.0f },
133 { box.min.x, box.min.y, box.max.z, 1.0f },
134 { box.min.x, box.max.y, box.min.z, 1.0f },
135 { box.min.x, box.max.y, box.max.z, 1.0f },
136 { box.max.x, box.min.y, box.min.z, 1.0f },
137 { box.max.x, box.min.y, box.max.z, 1.0f },
138 { box.max.x, box.max.y, box.min.z, 1.0f },
139 { box.max.x, box.max.y, box.max.z, 1.0f },
141 for (glm::vec4 &corner : corners) {
142 corner = MVP * corner;
146 int hits[6] = { 0, 0, 0, 0, 0, 0 };
148 // check how many corners lie outside
149 for (const glm::vec4 &corner : corners) {
150 if (corner.x > 1.0f) ++hits[0];
151 if (corner.x < -1.0f) ++hits[1];
152 if (corner.y > 1.0f) ++hits[2];
153 if (corner.y < -1.0f) ++hits[3];
154 if (corner.z > 1.0f) ++hits[4];
155 if (corner.z < -1.0f) ++hits[5];
158 // if all corners are outside any given clip plane, the test is true
159 for (int hit : hits) {
160 if (hit == 8) return true;
163 // otherwise the box might still get culled completely, but can't say for sure ;)