我正在尝试为从点多边形文件创建的多边形添加光照。我的问题是当从点创建向量时我只得到多边形的某个部分点亮,然后如果我反转法线的计算,(从A.x - C.x到C.x - A.x)它点亮之前没有点亮的部分。代码和图片如下。
h_vector V1;//= (p2 - p1);
// A = 0 B = 1 C = 2 D =3
V1.x = vertices[1].x - vertices[0].x;
V1.y = vertices[1].y - vertices[0].y;
V1.z = vertices[1].z - vertices[0].z;
h_vector V2;// = (p3 - p1);
V2.x = vertices[3].x - vertices[0].x;
V2.y = vertices[3].y - vertices[0].y;
V2.z = vertices[3].z - vertices[0].z;
/*
h_vector V1;//= (p2 - p1);
V1.x = vertices[0].x - vertices[1].x;
V1.y = vertices[0].y - vertices[1].y;
V1.z = vertices[0].z - vertices[1].z;
h_vector V2;// = (p3 - p1);
V2.x = vertices[0].x - vertices[3].x;
V2.y = vertices[0].y - vertices[3].y;
V2.z = vertices[0].z - vertices[3].z;
*/
surfaceNormal.x = (V1.y*V2.z) - (V1.z-V2.y);
surfaceNormal.y = - ( (V2.z * V1.x) - (V2.x * V1.z) );
surfaceNormal.z = (V1.x-V2.y) - (V1.y-V2.x);
float normalize = sqrtf((pow(surfaceNormal.x,2) + pow(surfaceNormal.y,2) + pow(surfaceNormal.z,2)));
surfaceNormal.x = surfaceNormal.x/normalize;
surfaceNormal.y = surfaceNormal.y/normalize;
surfaceNormal.z = surfaceNormal.z/normalize;
答案 0 :(得分:2)
这个交叉产品代码严重受损:
surfaceNormal.x = (V1.y*V2.z) - (V1.z-V2.y);
surfaceNormal.y = - ( (V2.z * V1.x) - (V2.x * V1.z) );
surfaceNormal.z = (V1.x-V2.y) - (V1.y-V2.x);
括号内的表达式都应该有一个乘法运算符,但在上面的代码中,其中一半是减法运算。
叉积计算应为:
surfaceNormal.x = V1.y * V2.z - V1.z * V2.y;
surfaceNormal.y = V1.z * V2.x - V1.x * V2.z;
surfaceNormal.z = V1.x * V2.y - V1.y * V2.x;
您可能希望研究使用矩阵/矢量库。如果你进行一些搜索,有许多免费提供。