Velocity Reviews > C++ > ray/triangle intersection

# ray/triangle intersection

jmeson79
Junior Member
Join Date: Nov 2008
Posts: 1

 11-05-2008
i have a function that should return true if a ray intersects a
triangle and false if not, but i can't get it to work. any ideas as to what's wrong with the following function?

bool TrimeshFace::intersectLocal( const ray& r, isect& i ) const
{

// retrieve the vertices
const Vec3d& v0 = parent->vertices[ids[0]];
const Vec3d& v1 = parent->vertices[ids[1]];
const Vec3d& v2 = parent->vertices[ids[2]];

Vec3d e1 = Vec3d(v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]);
Vec3d e2 = Vec3d(v2[0] - v0[0], v2[1] - v0[1], v2[2] - v0[2]);

Vec3d h = Vec3d(r.getDirection()[2] * e2[3] - r.getDirection()[3] * e2[2],
r.getDirection()[3] * e2[1] - r.getDirection()[1] * e2[3],
r.getDirection()[1] * e2[2] - r.getDirection()[2] * e2[1]);

double a = (e1[0] * h[0]) + (e1[1] * h[1]) + (e1[2] * h[2]);

if (a > -0.00001 && a < 0.00001)
return false;

double f = 1/a;

Vec3d s = Vec3d(r.getPosition()[2] * v0[3] - r.getPosition()[3] * v0[2],
r.getPosition()[3] * v0[1] - r.getPosition()[1] * v0[3],
r.getPosition()[1] * v0[2] - r.getPosition()[2] * v0[1]);

double u = f * ((s[0] * h[0]) + (s[1] * h[1]) + (s[2] * h[2]));

if (u < 0.0 || u > 1.0) {
return false;
}

Vec3d q = Vec3d(s[2] * e1[3] - s[3] * e1[2],
s[3] * e1[1] - s[1] * e1[3],
s[1] * e1[2] - s[2]* e1[1]);

double v = f * ((r.getDirection()[0] * q[0]) +
(r.getDirection()[1] * q[1]) +
(r.getDirection()[2] * q[2]));

if (v < 0.0 || u + v > 1.0)
return false;

// at this stage we can compute t to find out where
// the intersection point is on the line
double t = f * ((e2[0] * q[0]) + (e2[1] * q[1]) + (e2[2] * q[2]));

if (t > 0.00001) // ray intersection
{
i.obj = this;
i.t = t;
i.N = Vec3d(e1[2] * e2[3] - e1[3] * e2[2],
e1[3] * e2[1] - e1[1] * e2[3],
e1[1] * e2[2] - e1[2]* e2[1]);;
return true;
}

else // this means that there is a line intersection
// but not a ray intersection
return false;

}