Created
December 4, 2015 17:57
-
-
Save svenstaro/4ebdefdfd77d7509ed62 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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