我们可以解上面的方程:
根据克拉默法则(Cramer's Rule),每个未知数等于用常数项替换对应系数行列式某一列的行列式比上系数行列式。注意这里我们记,,
。根据标量三重积(scalar triple product),我们知道(下面ABC是三个3维向量):$$|A B C| = -(A \times C) \cdot B = -(C \times B) \cdot A.$$所以最终结果为:
boolrayTriangleIntersect( const Vec3f &orig, const Vec3f &dir, const Vec3f &v0, const Vec3f &v1, const Vec3f &v2, float &t, float &u, float &v) { #ifdef MOLLER_TRUMBORE Vec3f v0v1 = v1 - v0; Vec3f v0v2 = v2 - v0; Vec3f pvec = dir.crossProduct(v0v2); float det = v0v1.dotProduct(pvec); #ifdef CULLING // if the determinant is negative the triangle is backfacing // if the determinant is close to 0, the ray misses the triangle if (det < kEpsilon) returnfalse; #else // ray and triangle are parallel if det is close to 0 if (fabs(det) < kEpsilon) returnfalse; #endif float invDet = 1 / det; Vec3f tvec = orig - v0; u = tvec.dotProduct(pvec) * invDet; if (u < 0 || u > 1) returnfalse; Vec3f qvec = tvec.crossProduct(v0v1); v = dir.dotProduct(qvec) * invDet; if (v < 0 || u + v > 1) returnfalse; t = v0v2.dotProduct(qvec) * invDet; returntrue; #else ... #endif }