从已知三角形顶点和顶点U,V推断三角形中的点的U,V
参考从LuxRays(http://src.luxrender.net/luxrays)获取的代码。获取重心坐标:
其中p0,p1,p2 为三角形的三个点,uv为点对应的uv坐标,hitpoint 为射线到三角面的交点,newuv 为返回的uv坐标
public static bool GetBaryCoords(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 hitPoint, List<Vector2> uv,ref Vector2 newuv)
{
Vector3 u = p1 - p0;
Vector3 v = p2 - p0;
Vector3 w = hitPoint - p0;
Vector3 vCrossW = Vector3.Cross(v, w);
Vector3 vCrossU = Vector3.Cross(v, u);
if (Vector3.Dot(vCrossW, vCrossU) < 0.0f)
return false;
Vector3 uCrossW = Vector3.Cross(u, w);
Vector3 uCrossV = Vector3.Cross(u, v);
if (Vector3.Dot(uCrossW, uCrossV) < 0.0f)
return false;
float denom = uCrossV.magnitude;
float r = vCrossW.magnitude / denom;
float t = uCrossW.magnitude / denom;
float b0 = 1.0f - r - t;
float x = b0 * uv[0].x + r * uv[1].x + t * uv[2].x;
float y = b0 * uv[0].y + r * uv[1].y + t * uv[2].y;
newuv.x = x;
newuv.y = y;
return ((r <= 1.0f) && (t <= 1.0f) && (r + t <= 1.0f));
}
要决定的主要事情是要如何精确地在三角形内部插值UV。
在这种情况下,您需要该三角形内部的点的重心坐标:http://en.wikipedia.org/wiki/Barycentric_coordinate_system
简而言之,三角形内部的每个点都可以表示为其顶点的加权和,其中每个权重在0和1之间。可以通过求解2x2线性方程组来找到权重。
当拥有这些权重时,可以使用它们来获得UV坐标的加权总和。