6#include <glm/gtc/constants.hpp>
8namespace Vkm::Engine::Math {
12inline constexpr float BOUNDS_EPSILON_SQ = 1e-8f;
27 const glm::vec3 extent = max - min;
28 return glm::dot(extent, extent) > BOUNDS_EPSILON_SQ;
31 glm::vec3 center() const noexcept {
return (min + max) * 0.5f; }
33 glm::vec3 halfExtent() const noexcept {
return (max - min) * 0.5f; }
43inline AABB transform(
const glm::mat4& matrix,
const AABB& local) {
45 world.min = glm::vec3(matrix[3]);
46 world.max = glm::vec3(matrix[3]);
48 for (
int j = 0; j < 3; ++j) {
49 const glm::vec3 col(matrix[j]);
50 const glm::vec3 a = col * local.min[j];
51 const glm::vec3 b = col * local.max[j];
52 world.min += glm::min(a, b);
53 world.max += glm::max(a, b);
62 glm::vec3 origin{0.0f};
76inline Ray rayThroughNdc(
const glm::mat4& invViewProj,
const glm::vec2& ndc) {
77 glm::vec4 nearPoint = invViewProj * glm::vec4(ndc, -1.0f, 1.0f);
78 glm::vec4 farPoint = invViewProj * glm::vec4(ndc, 1.0f, 1.0f);
79 nearPoint /= nearPoint.w;
80 farPoint /= farPoint.w;
81 return Ray{glm::vec3(nearPoint), glm::normalize(glm::vec3(farPoint - nearPoint))};
94inline bool rayIntersectsAABB(
95 const glm::vec3& origin,
96 const glm::vec3& invDir,
100 const glm::vec3 t0 = (box.min - origin) * invDir;
101 const glm::vec3 t1 = (box.max - origin) * invDir;
103 const glm::vec3 tMinV = glm::min(t0, t1);
104 const glm::vec3 tMaxV = glm::max(t0, t1);
106 float tMin = glm::max(glm::max(tMinV.x, tMinV.y), tMinV.z);
107 float tMax = glm::min(glm::min(tMaxV.x, tMaxV.y), tMaxV.z);
111 tHit = tMin > 0.0f ? tMin : tMax;
112 return tMax >= tMin && tMax >= 0.0f;
123inline std::optional<glm::vec3> rayHitsLevel(
const Ray& ray,
float y)
noexcept {
124 if (glm::abs(ray.direction.y) < glm::epsilon<float>())
return std::nullopt;
125 const float t = (y - ray.origin.y) / ray.direction.y;
126 if (t <= 0.0f)
return std::nullopt;
127 return ray.origin + ray.direction * t;
An axis-aligned box.
Definition bounds.h:17
bool valid() const noexcept
True when the box has non-degenerate extent.
Definition bounds.h:26
A half-line in world space.
Definition bounds.h:61
glm::vec3 direction
Unit length.
Definition bounds.h:63