Math problem

Im trying to implement ray/line to triangle collision. Strange things are happenning, as depending on the rotation of the object it works 80% of the time but not the other 20. I figure it must be a math problem. Anyone willing take a look at my code. thanks

bool CTriangle::Intersect(CVector start, CVector end)
{
double d;
double a1,a2,a3;
double total,denom,mu;
CVector n,pa1,pa2,pa3, p;

// Calculate the parameters for the plane
n.setX( (Vertices[1].m_Y - Vertices[0].m_Y)(Vertices[2].m_Z - Vertices[0].m_Z) - (Vertices[1].m_Z - Vertices[0].m_Z)(Vertices[2].m_Y - Vertices[0].m_Y) );

n.setY( (Vertices[1].m_Z - Vertices[0].m_Z)(Vertices[2].m_X - Vertices[0].m_X) - (Vertices[1].m_X - Vertices[0].m_X)(Vertices[2].m_Z - Vertices[0].m_Z) );

n.setZ( (Vertices[1].m_X - Vertices[0].m_X)(Vertices[2].m_Y - Vertices[0].m_Y) - (Vertices[1].m_Y - Vertices[0].m_Y)(Vertices[2].m_X - Vertices[0].m_X) );

n.Normalize();

d = - (n.GetX() * Vertices[0].m_X- n.GetY() * Vertices[0].m_Y - n.GetZ() * Vertices[0].m_Z);

// Calculate the position on the line that intersects the plane
denom = n.GetX() * (end.GetX() - start.GetX()) + n.GetY() * (end.GetY() - start.GetY()) + n.GetZ() * (end.GetZ() - start.GetZ());
if (abs(denom) < EPS)
// Line and plane don’t intersect
return false;

mu = - (d + n.GetX() * start.GetX() + n.GetY() * start.GetY() + n.GetZ() * start.GetZ()) / denom;

p.setX( (start.GetX() + mu * (end.GetX() - start.GetX())) );

p.setY( (start.GetY() + mu * (end.GetY() - start.GetY())) );

p.setZ( (start.GetZ() + mu * (end.GetZ() - start.GetZ())) );

if (mu < 0 | | mu > 1) // Intersection not along line segment
return false;

// Determine whether or not the intersection point is bounded by pa,pb,pc

pa1.setX( Vertices[0].m_X - p.GetX() );
pa1.setY( Vertices[0].m_Y - p.GetY() );
pa1.setZ( Vertices[0].m_Z - p.GetZ() );
pa1.Normalize();

pa2.setX( Vertices[1].m_X - p.GetX() );
pa2.setY( Vertices[1].m_Y - p.GetY() );
pa2.setZ( Vertices[1].m_Z - p.GetZ() );
pa2.Normalize();

pa3.setX( Vertices[2].m_X - p.GetX() );
pa3.setY( Vertices[2].m_Y - p.GetY() );
pa3.setZ( Vertices[2].m_Z - p.GetZ() );
pa3.Normalize();

a1 = pa1.GetX() * pa2.GetX() + pa1.GetY() * pa2.GetY() + pa1.GetZ() * pa2.GetZ();

a2 = pa2.GetX() * pa3.GetX() + pa2.GetY() * pa3.GetY() + pa2.GetZ() * pa3.GetZ();

a3 = pa3.GetX() * pa1.GetX() + pa3.GetY() * pa1.GetY() + pa3.GetZ() * pa1.GetZ();

double rad = (acos(a1) + acos(a2) + acos(a3));

total = (rad/3.141592) * 180;
double a = abs(total - 360);

if (a >= EPS)
return false;
return true;
}

>>double a = abs(total - 360);<<
i persume u want fabs

theres heaps of ray->triangle example source code maybe worth looking at eg http://www.realtimerendering.com/int/