OpenGL @ Lighthouse 3D - Maths Tutorial
full algorithm to compute the intersection between a ray and a sphere. It is assumed that the ray is defined by an origin p, and a direction d, and that the sphere has a center c, and a radius r.
vpc = c - p // this is the vector from p to c
if ((vpc . d) < 0) // when the sphere is behind the origin p
// note that this case may be dismissed if it is considered
// that p is outside the sphere
if (|vpc| > r)
// there is no intersection
else if (|vpc| == r)
intersection = p
else // occurs when p is inside the sphere
pc = projection of c on the line
dist = sqrt(radius^2 - |pc - c|^2)// distance from pc to i1
di1 = dist - |pc - p|
intersection = p + d * di1
else // center of sphere projects on the ray
pc = projection of c on the line
if (| c - pc | > r)
// there is no intersection
else
dist = sqrt(radius^2 - |pc - c|^2)// distance from pc to i1
if (|vpc| > r) // origin is outside sphere
di1 = |pc - p| - dist
else // origin is inside sphere
di1 = |pc - p| + dist
intersection = p + d * di1
Ray Tracing: Graphics for the Masses
Color trace_ray( Ray
original_ray )
{
Color point_color, reflect_color,
refract_color
Object obj
obj = get_first_intersection(
original_ray )
point_color = get_point_color( obj
)
if ( object is reflective )
reflect_color = trace_ray(
get_reflected_ray( original_ray,
obj ) )
if ( object is refractive )
refract_color = trace_ray(
get_refracted_ray( original_ray,
obj ) )
return ( combine_colors(
point_color, reflect_color, refract_color ))
}- where a Color is the
triple (R, G,
B) for the red, green, and blue
components of the color, which can each vary between zero
and one. This function, along with some intersection
routines, is really all that is needed to write a ray
tracer.
Posted from Diigo. The rest of my favorite links are here.