Skip to content

Instantly share code, notes, and snippets.

@svenstaro
Last active October 9, 2020 21:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenstaro/a64045811d5dcf378b6a to your computer and use it in GitHub Desktop.
Save svenstaro/a64045811d5dcf378b6a to your computer and use it in GitHub Desktop.
inline bool intersect_ray_aabb(const glm::vec3 &origin, const glm::vec3 &dir, const AABB &aabb) {
float tmin, tmax, tymin, tymax, tzmin, tzmax;
glm::vec3 bounds[2];
bounds[0] = aabb.min();
bounds[1] = aabb.max();
glm::vec3 invdir = 1.f / dir;
glm::i8vec3 sign;
sign.x = (invdir.x < 0);
sign.y = (invdir.y < 0);
sign.z = (invdir.z < 0);
tmin = (bounds[sign.x].x - origin.x) * invdir.x;
tmax = (bounds[1 - sign.x].x - origin.x) * invdir.x;
tymin = (bounds[sign.y].y - origin.y) * invdir.y;
tymax = (bounds[1 - sign.y].y - origin.y) * invdir.y;
if ((tmin > tymax) || (tymin > tmax))
return false;
if (tymin > tmin)
tmin = tymin;
if (tymax < tmax)
tmax = tymax;
tzmin = (bounds[sign.z].z - origin.z) * invdir.z;
tzmax = (bounds[1 - sign.z].z - origin.z) * invdir.z;
if ((tmin > tzmax) || (tzmin > tmax))
return false;
if (tzmin > tmin)
tmin = tzmin;
if (tzmax < tmax)
tmax = tzmax;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment