将单行向量(数组)赋值转换为经典数组,C++ 转换为 C

Convert a one line vector (array) assignation to classical array, C++ translation to C

我正在尝试转换 Moller Trumbore 算法,如 here 所示。

这段代码的目标是搜索向量与三角形的交点,它也是 return U 和 V 纹理点。

但是,我坚持这一行:

Vector uvHit = uvVectors[0] * u + uvVectors[1] * v + uvVectors[2] * (1 - u - v);

谁也可以看成:

*uvHit = u * uvVectors[0] + v * uvVectors[1] + (1 - u - v) * uvVectors[2];

这是我的代码:

typedef float vec_t;
typedef vec_t vec3_t[3];

qboolean GetIntersection(vec3_t rayOrigin, vec3_t rayDirection, float hitDistance, vec3_t *uv)
{
vec3_t pvec;
float det = 0.0f;
vec3_t tvec;
vec3_t qvec;
vec3_t uvHit;

// begin calculating determinant - also used to calculate U parameter
CrossProduct(rayDirection, edge2, pvec);

// if determinant is near zero, ray lies in plane of triangle
det = DotProduct(edge1, pvec);

const float EPSILON = 0.000001f;

if ((det > -EPSILON) && (det < EPSILON))
    return qfalse;

float inv_det = 1.0f / det;

// calculate distance from vertex 0 to ray origin
tvec = rayOrigin - verts[0];

// calculate U parameter and test bounds
u = DotProduct(tvec, pvec) * inv_det;


if ((u < 0.0f) || (u > 1.0f))
    return false;

// prepare to test V parameter
CrossProduct(tvec, edge1, qvec);

// calculate V parameter and test bounds
float v = DotProduct(rayDirection, qvec) * inv_det;

if ((v < 0.0f) || (u + v > 1.0f))
    return false;

Vector uvHit = uvVectors[0] * u + uvVectors[1] * v + uvVectors[2] * (1 - u - v);// This is the line I don't understand 

uv[0] = uvHit[0];
uv[1] = uvHit[1];
uv[2] = 0;

// calculate t, ray intersects triangle
hitDistance = DotProduct(edge2, qvec) * inv_det;

// only allow intersections in the forward ray direction
return hitDistance >= 0.0f;
}

您正在根据表示为 Vector uvVectors[3] 的顶点及其重心坐标 uvw == 1 - u - v.

计算三角形中的一个点

在您显示的 C++ 代码中,Vector 可能是一个 class 或一个结构。乘法运算符 * 已被重载,在本例中为向量与标量的乘法:

Vector uvHit = uvVectors[0] * u + uvVectors[1] * v + uvVectors[2] * (1 - u - v);

在 C 中,您不能重载运算符,因此您必须显式地编写此计算。假设您的矢量是 3D 中的矢量 space:

typedef struct Vector Vector;

struct Vector {
    double x, y, z;
};

那么当你初始化一个向量时你的乘法看起来像这样:

Vector uvHit = {
    uvVectors[0].x * u + uvVectors[1].x * v + uvVectors[2].x * (1 - u - v),
    uvVectors[0].y * u + uvVectors[1].y * v + uvVectors[2].y * (1 - u - v),
    uvVectors[0].z * u + uvVectors[1].z * v + uvVectors[2].z * (1 - u - v)
};

或者以后赋值时像这样:

uvHit.x = uvVectors[0].x * u + uvVectors[1].x * v + uvVectors[2].x * (1 - u - v);
uvHit.y = uvVectors[0].y * u + uvVectors[1].y * v + uvVectors[2].y * (1 - u - v);
uvHit.z = uvVectors[0].z * u + uvVectors[1].z * v + uvVectors[2].z * (1 - u - v);