intersectTriangle method
Performs a ray/triangle intersection test and stores the intersection point to the given 3D vector. If no intersection is detected, null is returned.
Implementation
Vector3? intersectTriangle(Map<String,Vector3> triangle, bool backfaceCulling, Vector3 result ) {
// reference: https://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
final a = triangle['a']!;
final b = triangle['b']!;
final c = triangle['c']!;
edge1.subVectors( b, a );
edge2.subVectors( c, a );
normal.crossVectors( edge1, edge2 );
double ddN = direction.dot( normal );
int sign;
if ( ddN > 0 ) {
if ( backfaceCulling ) return null;
sign = 1;
}
else if ( ddN < 0 ) {
sign = - 1;
ddN = - ddN;
}
else {
return null;
}
v1.subVectors( origin, a );
final ddQxE2 = sign * direction.dot( edge2.crossVectors( v1, edge2 ) );
// b1 < 0, no intersection
if ( ddQxE2 < 0 ) {
return null;
}
final ddE1xQ = sign * direction.dot( edge1.cross( v1 ) );
// b2 < 0, no intersection
if ( ddE1xQ < 0 ) {
return null;
}
// b1 + b2 > 1, no intersection
if ( ddQxE2 + ddE1xQ > ddN ) {
return null;
}
// line intersects triangle, check if ray does
final qdN = - sign * v1.dot( normal );
// t < 0, no intersection
if ( qdN < 0 ) {
return null;
}
// ray intersects triangle
return at( qdN / ddN, result );
}