Advertisement
Guest User

AABB class

a guest
Apr 17th, 2024
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. enum AXIS {
  2.     X_AXIS = 0,
  3.     Y_AXIS = 1,
  4.     Z_AXIS = 2
  5. };
  6.  
  7. class AABB {
  8. public:
  9.     glm::vec3 Min{};
  10.     glm::vec3 Max{};
  11.  
  12.     AABB() = default;
  13.     AABB(glm::vec3 min, glm::vec3 max);
  14.  
  15.     void Expand(const AABB& aabb);
  16.     void Expand(const glm::vec3& point);
  17.  
  18.     AXIS GetLongestAxis() const;
  19.  
  20.     float IntersectsRay(const Ray& ray) const;
  21.     float IntersectsAABB(const AABB& aabb) const;
  22.  
  23. };
  24.  
  25. AABB::AABB(glm::vec3 min, glm::vec3 max)
  26.     : Min(min)
  27.     , Max(max)
  28. {
  29. }
  30.  
  31. void AABB::Expand(const AABB& aabb)
  32. {
  33.     Min = glm::min(Min, aabb.Min);
  34.     Max = glm::max(Max, aabb.Max);
  35. }
  36.  
  37. void AABB::Expand(const glm::vec3& point)
  38. {
  39.     Min = glm::min(Min, point);
  40.     Max = glm::max(Max, point);
  41. }
  42.  
  43. AXIS AABB::GetLongestAxis() const
  44. {
  45.  
  46.     glm::vec3 diag = Max - Min;
  47.     if (diag.x > diag.y && diag.x > diag.z)
  48.         return X_AXIS;
  49.     else if (diag.y > diag.z)
  50.         return Y_AXIS;
  51.     else
  52.         return Z_AXIS;
  53.  
  54. }
  55.  
  56. float AABB::IntersectsRay(const Ray& ray) const
  57. {
  58.  
  59.     // Ray vs AABB using 'Slab method'.
  60.     // Source: https://tavianator.com/fast-branchless-raybounding-box-intersections/
  61.  
  62.     const float rxinv = 1.0f / ray.Dir().x;
  63.     const float ryinv = 1.0f / ray.Dir().y;
  64.     const float rzinv = 1.0f / ray.Dir().z;
  65.  
  66.     const float tx1 = (Min.x - ray.Origin().x) * rxinv;
  67.     const float tx2 = (Max.x - ray.Origin().x) * rxinv;
  68.  
  69.     float tmin = std::min(tx1, tx2);
  70.     float tmax = std::max(tx1, tx2);
  71.  
  72.     float ty1 = (Min.y - ray.Origin().y) * ryinv;
  73.     float ty2 = (Max.y - ray.Origin().y) * ryinv;
  74.  
  75.     tmin = std::max(tmin, std::min(ty1, ty2));
  76.     tmax = std::min(tmax, std::max(ty1, ty2));
  77.  
  78.     float tz1 = (Min.z - ray.Origin().z) * rzinv;
  79.     float tz2 = (Max.z - ray.Origin().z) * rzinv;
  80.  
  81.     tmin = std::max(tmin, std::min(tz1, tz2));
  82.     tmax = std::min(tmax, std::max(tz1, tz2));
  83.    
  84.     // No intersection
  85.     if (tmax < tmin)
  86.         return -1.0f;
  87.  
  88.     // Ray origin is inside the AABB
  89.     if (tmin < Utils::Constants::ALMOST_ZERO)
  90.         return tmax;
  91.  
  92.     return tmin;
  93.  
  94. }
  95.  
  96. float AABB::IntersectsAABB(const AABB& aabb) const
  97. {
  98.     assert(false); // Not implemented yet.
  99.     return false;
  100. }
  101.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement