/////////////////////////////////////////////////////////////////////////////////////////////////// // Calculate the tangent basis for a triangle on the surface of a model // This vector is needed for most normal mapping shaders void m3dCalculateTangentBasis(const M3DVector3f vTriangle[3], const M3DVector2f vTexCoords[3], const M3DVector3f N, M3DVector3f vTangent) { M3DVector3f dv2v1, dv3v1; float dc2c1t, dc2c1b, dc3c1t, dc3c1b; float M; m3dSubtractVectors3(dv2v1, vTriangle[1], vTriangle[0]); m3dSubtractVectors3(dv3v1, vTriangle[2], vTriangle[0]); dc2c1t = vTexCoords[1][0] - vTexCoords[0][0]; dc2c1b = vTexCoords[1][1] - vTexCoords[0][1]; dc3c1t = vTexCoords[2][0] - vTexCoords[0][0]; dc3c1b = vTexCoords[2][1] - vTexCoords[0][1]; M = (dc2c1t * dc3c1b) - (dc3c1t * dc2c1b); M = 1.0f / M; m3dScaleVector3(dv2v1, dc3c1b); m3dScaleVector3(dv3v1, dc2c1b); m3dSubtractVectors3(vTangent, dv2v1, dv3v1); m3dScaleVector3(vTangent, M); // This potentially changes the direction of the vector m3dNormalizeVector(vTangent); M3DVector3f B; m3dCrossProduct(B, N, vTangent); m3dCrossProduct(vTangent, B, N); m3dNormalizeVector(vTangent); }
/** Calculate normal vector of the plane of v1, v2 vector. */ tM3dVector m3dCalcNormal(tM3dVector v1, tM3dVector v2) { tM3dVector normal; normal = m3dCrossProduct(v1, v2); m3dNormalise(normal); return(normal); }
/** Calculates the transformation matrix which rotates Z axis to base vector */ tM3dMatrix m3dTransformMatrixV(tM3dVector base) { tM3dMatrix result; tM3dVector normals[3]; normals[0] = m3dNormalise(base); normals[1] = m3dNormalise(m3dVector(base.c[1]/base.c[0], 1, 0)); normals[2] = m3dCrossProduct(normals[0], normals[1]); result = m3dMatrixV3(normals); return(result); }
void m3dFindNormal(M3DVector3f result, const M3DVector3f point1, const M3DVector3f point2, const M3DVector3f point3) { M3DVector3f v1,v2; // Temporary vectors // Calculate two vectors from the three points. Assumes counter clockwise // winding! v1[0] = point1[0] - point2[0]; v1[1] = point1[1] - point2[1]; v1[2] = point1[2] - point2[2]; v2[0] = point2[0] - point3[0]; v2[1] = point2[1] - point3[1]; v2[2] = point2[2] - point3[2]; // Take the cross product of the two vectors to get // the normal vector. m3dCrossProduct(result, v1, v2); }
// Ditto above, but for doubles void m3dGetPlaneEquation(M3DVector4d planeEq, const M3DVector3d p1, const M3DVector3d p2, const M3DVector3d p3) { // Get two vectors... do the cross product M3DVector3d v1, v2; // V1 = p3 - p1 v1[0] = p3[0] - p1[0]; v1[1] = p3[1] - p1[1]; v1[2] = p3[2] - p1[2]; // V2 = P2 - p1 v2[0] = p2[0] - p1[0]; v2[1] = p2[1] - p1[1]; v2[2] = p2[2] - p1[2]; // Unit normal to plane - Not sure which is the best way here m3dCrossProduct(planeEq, v1, v2); m3dNormalizeVector(planeEq); // Back substitute to get D planeEq[3] = -(planeEq[0] * p3[0] + planeEq[1] * p3[1] + planeEq[2] * p3[2]); }