// A fast ray-bounding box intersection routine // Requires: a ray structure that stores (a) the origin, (b) the inverse direction // (i.e., (1/dir_x, 1/dir_y, 1/dir_z) where dir_xyz is the ray's direction) // as well as (c) a quantity related to the sign of the inverse direction. // (i.e., invDirSign[0] is 1 if 1/dir_x < 0 and is 0 if 1/dir_x >= 0) // Also requires an array of points representing the bounding box. In this case, // bounds[0] is the minimum point of the bounding box and bounds[1] is the maximum. bool IntersectBBox( Ray &ray, Point *bounds ) { float tmin = (bounds[ray.invDirSign[0]].X() - ray.origin.X()) * ray.invDir.X(); float tymax = (bounds[1-ray.invDirSign[1]].Y() - ray.origin.Y()) * ray.invDir.Y(); if ( tmin > tymax ) return false; float tmax = (bounds[1-ray.invDirSign[0]].X() - ray.origin.X()) * ray.invDir.X(); float tymin = (bounds[ray.invDirSign[1]].Y() - ray.origin.Y()) * ray.invDir.Y(); if ( tymin > tmax ) return false; if ( tymax < tmax ) tmax = tymax; float tzmin = (bounds[ray.invDirSign[2]].Z() - ray.origin.Z()) * ray.invDir.Z(); if ( tzmin > tmax ) return false; if ( tymin > tmin ) tmin = tymin; float tzmax = (bounds[1-ray.invDirSign[2]].Z() - ray.origin.Z()) * ray.invDir.Z(); if ( tmin > tzmax ) return false; if ( tzmin > tmin ) tmin = tzmin; if ( tzmax < tmax ) tmax = tzmax; return ( (tmin < ray.hitDist) && (tmax > EPSILON) ); // EPSILON is a small value > 0 }