Graphics Reference
In-Depth Information
(a)
(b)
(c)
(d)
(e)
Figure 5.21 Different cases of ray-sphere intersection: (a) ray intersects sphere (twice) with
t > 0, (b) false intersection with t < 0, (c) ray intersects sphere tangentially, (d) ray starts inside
sphere, and (e) no intersection.
intersection value of t
0. This case is illustrated in Figure 5.21, along with all other
ray-sphere intersection relationships.
The following code implements the ray-sphere intersection test.
<
// Intersects rayr=p+td,|d|=1,with sphere s and, if intersecting,
// returns t value of intersection and intersection point q
int IntersectRaySphere(Point p, Vector d, Sphere s, float &t, Point &q)
{
Vectorm=p-s.c;
float b = Dot(m, d);
float c = Dot(m, m) - s.r * s.r;
// Exit if r's origin outside s (c > 0) and r pointing away from s (b > 0)
if (c > 0.0f && b > 0.0f) return 0;
float discr = b*b - c;
// A negative discriminant corresponds to ray missing sphere
if (discr < 0.0f) return 0;
// Ray now found to intersect sphere, compute smallest t value of intersection
t = -b - Sqrt(discr);
// If t is negative, ray started inside sphere so clamp t to zero
if (t < 0.0f) t = 0.0f;
q=p+t*d;
return 1;
}
For intersecting a directed segment AB against a sphere, the same code can be
used by setting P
A )
=
A and d
=
( B
B
A
. On intersection, it is important to
verify that t
B
A
so that the detected intersection does not lie beyond the end
of the segment.
To just test if the ray intersects the sphere (but not when or where), the code can
be optimized to not have to perform a potentially expensive square root operation.
 
Search WWH ::




Custom Search