Monday, November 23, 2009

Ray-Triangle intersection test code

I noticed that most of the blog visitors come here for Ray-Triangle intersection test so I decide to put the code here.

I hope it is useful for you.

//! Checks if the ray and triangle intersects and store the intersection point in the Out parameter.
CollisionType IntersectRay(Ray* pRay, kge::math::Vector& Out)
{
Edge1 = Point2 - Point1;
Edge2 = Point3 - Point1;
Normal.Cross(Edge1, Edge2);
float fGama = -(pRay->Direction * Normal);

if (fGama < fEpsilon)
return ECT_NotIntersect;

Vector b = pRay->Position - Point1;
float fLanda = (b * Normal) / fGama;

if (fLanda >= 0.0f && fLanda <= 1.0f)
{
Vector u;
u.Cross(b, pRay->Direction);
float u1, u2;
u1 = (Edge2 * u) / fGama;
u2 = (-(Edge1 * u)) / fGama;
if (u1 + u2 <= 1.0f && u1 >= 0.0f && u2 >= 0.0f)
{
Out = pRay->Position + (pRay->Direction * fLanda);
return ECT_Intersect;
}
}

return ECT_NotIntersect;

} // IntersectRay

No comments: