Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool BoundingBox::intersects(const raytracer::Ray& ray, float& distance) const
- {
- //Lamda to calculate the intersection distance
- const auto calculateT = [&](float invDir, float origin, float min, float max, float& tMin, float& tMax)
- {
- if (invDir >= 0)
- {
- tMin = invDir * (min - origin);
- tMax = invDir * (max - origin);
- }
- else
- {
- tMin = invDir * (max - origin);
- tMax = invDir * (min - origin);
- }
- };
- if(!b_hasVolume)
- {
- return false;
- }
- vec3 tMin, tMax;
- const vec3& inverseDirection = ray.getInverseDirection();
- const vec3 origin = ray.getOrigin();
- //Calculate all the min and max intersections.
- calculateT(inverseDirection.m_X, origin.m_X, min.m_X, max.m_X, tMin.m_X, tMax.m_X);
- calculateT(inverseDirection.m_Y, origin.m_Y, min.m_Y, max.m_Y, tMin.m_Y, tMax.m_Y);
- calculateT(inverseDirection.m_Z, origin.m_Z, min.m_Z, max.m_Z, tMin.m_Z, tMax.m_Z);
- /*
- * Get the maximum min distance, and the minimum max distane.
- * These are the bounds at which all three axes are within the shape along the ray.
- * If max <= min, no intersection occurs.
- */
- const float minIntersectDistance = std::max(tMin.m_X, std::max(tMin.m_Y, tMin.m_Z));
- const float maxIntersectDistance = std::min(tMax.m_X, std::min(tMax.m_Y, tMax.m_Z));
- //There is segment along the line that is within the box
- if(minIntersectDistance < maxIntersectDistance)
- {
- //Min intersect is negative.
- if(minIntersectDistance < 0.f)
- {
- //Max intersect is also negative, so there is no intersection (all happens behind the ray origin).
- if(maxIntersectDistance < 0.f)
- {
- return false;
- }
- //There is an intersection, but the ray originates within this box.
- //That means that it should ALWAYS be checked before other boxes that may be inside it.
- //Therefore, distance is 0.
- distance = 0.f; //maxIntersectDistance (normally you'd want to return this).
- return true;
- }
- distance = minIntersectDistance;
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement