我想将此算法用于光线/三角交叉测试:
#define EPSILON 0.000001
int triangle_intersection( const Vec3 V1, // Triangle vertices
const Vec3 V2,
const Vec3 V3,
const Vec3 O, //Ray origin
const Vec3 D, //Ray direction
float* out )
{
Vec3 e1, e2; //Edge1, Edge2
Vec3 P, Q, T;
float det, inv_det, u, v;
float t;
//Find vectors for two edges sharing V1
SUB(e1, V2, V1);
SUB(e2, V3, V1);
//Begin calculating determinant - also used to calculate u parameter
CROSS(P, D, e2);
//if determinant is near zero, ray lies in plane of triangle
det = DOT(e1, P);
//NOT CULLING
if(det > -EPSILON && det < EPSILON) return 0;
inv_det = 1.f / det;
//calculate distance from V1 to ray origin
SUB(T, O, V1);
//Calculate u parameter and test bound
u = DOT(T, P) * inv_det;
//The intersection lies outside of the triangle
if(u < 0.f || u > 1.f) return 0;
//Prepare to test v parameter
CROSS(Q, T, e1);
//Calculate V parameter and test bound
v = DOT(D, Q) * inv_det;
//The intersection lies outside of the triangle
if(v < 0.f || u + v > 1.f) return 0;
t = DOT(e2, Q) * inv_det;
if(t > EPSILON) { //ray intersection
*out = t;
return 1;
}
// No hit, no win
return 0;
}
然而,我在理解它时遇到了一些麻烦。此算法是否仅测试交叉点是否存在?我希望能够检索光线与三角形相交的点。
感谢您的帮助。