示例#1
0
int IntersectRaySphereX(	const SphereX& sphere,
							const Vector3X& p,
							const Vector3X& dir,
							Fixed* t )
{
	Vector3X raySphere = sphere.origin - p;
	Fixed raySphereLen2 = DotProduct( raySphere, raySphere );
	Fixed sphereR2 = sphere.radius*sphere.radius;

	if (raySphereLen2 < sphereR2) 
	{	
		// Origin is inside the sphere.
		return grinliz::INSIDE;
	} 
	else 
	{
		// Clever idea: what is the rays closest approach to the sphere?
		// see: http://www.devmaster.net/wiki/Ray-sphere_intersection

		Fixed closest = DotProduct(raySphere, dir);
		if (closest < 0) {
			// Then we are pointing away from the sphere (and we know we aren't inside.)
			return grinliz::REJECT;
		}
		Fixed halfCordLen = (sphereR2 - raySphereLen2) / DotProduct(dir, dir) + (closest*closest);
		if ( halfCordLen > 0 ) {
			*t = closest - halfCordLen.Sqrt();
			return grinliz::INTERSECT;
		}
	}
	return grinliz::REJECT;
}