Skip to content

Instantly share code, notes, and snippets.

@svenstaro
Created December 4, 2015 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenstaro/4ebdefdfd77d7509ed62 to your computer and use it in GitHub Desktop.
Save svenstaro/4ebdefdfd77d7509ed62 to your computer and use it in GitHub Desktop.
struct Ray {
Ray(const glm::vec3 &origin, const glm::vec3 &direction)
: m_origin(origin), m_dir(direction), m_invdir(1.f / direction) {
}
glm::vec3 m_origin;
glm::vec3 m_dir;
glm::vec3 m_invdir;
};
class AABB {
public:
static bool is_null(const AABB &aabb);
static glm::vec3 min(const AABB &aabb);
static glm::vec3 max(const AABB &aabb);
static glm::vec3 diagonal(const AABB &aabb);
static glm::vec3 center(const AABB &aabb);
static std::array<glm::vec3, 8> vertices(AABB &aabb);
static void extend(AABB &aabb, glm::vec3 &point);
static bool overlaps(const AABB &first, const AABB &second);
static void reset(AABB &aabb);
private:
glm::vec3 m_min;
glm::vec3 m_max;
};
inline bool intersect_ray_aabb(const Ray &ray, const AABB &aabb) {
double t1 = (AABB::min(aabb)[0] - ray.m_origin[0]) * ray.m_invdir[0];
double t2 = (AABB::max(aabb)[0] - ray.m_origin[0]) * ray.m_invdir[0];
double tmin = glm::min(t1, t2);
double tmax = glm::max(t1, t2);
for (int i = 1; i < 3; ++i) {
t1 = (AABB::min(aabb)[i] - ray.m_origin[i]) * ray.m_invdir[i];
t2 = (AABB::max(aabb)[i] - ray.m_origin[i]) * ray.m_invdir[i];
tmin = glm::max(tmin, glm::min(t1, t2));
tmax = glm::min(tmax, glm::max(t1, t2));
}
return tmax > glm::max(tmin, 0.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment