<分区>
我正尝试在 C++ 中为光线追踪器做一些半复杂的对象初始化。
以下代码用于通过数组向对象添加三角形面:
// "newTriangles" is a class; the object itself
// "faces" is an array of "triangle", a struct with three ints in it
// "nfaces" is an int of the number of faces which I use to initialize the array:
newTriangles->faces = new triangle[newTriangles->nFaces];
for (int i = 0; i < newTriangles->nFaces; ++i)
{
// grab values
newTriangles->faces[i].v1 = a;
newTriangles->faces[i].v2 = b;
newTriangles->faces[i].v3 = c;
cout << i << ": " << newTriangles->faces[0].v1 << ", " << newTriangles->faces[0].v2 << ", " << newTriangles->faces[0].v3 << "\n";
// Other code in this loop
// Compute normal for this face
coordinate v1 = {
newTriangles->vertices[a].x,
newTriangles->vertices[a].y,
newTriangles->vertices[a].z };
coordinate v2 = {
newTriangles->vertices[b].x,
newTriangles->vertices[b].y,
newTriangles->vertices[b].z };
coordinate v3 = {
newTriangles->vertices[c].x,
newTriangles->vertices[c].y,
newTriangles->vertices[c].z };
ray v1v2 = {
v1.x - v2.x,
v1.y - v2.y,
v1.z - v2.z };
ray v3v2 = {
v3.x - v2.x,
v3.y - v2.y,
v3.z - v2.z };
ray n = normalize(cross(v1v2, v3v2));
newTriangles->fNormals[i].x = n.x;
newTriangles->fNormals[i].y = n.y;
newTriangles->fNormals[i].z = n.z;
// This block here seems to be where the problem surfaces
newTriangles->vNormals[i].x += n.x;
newTriangles->vNormals[i].y += n.y;
newTriangles->vNormals[i].z += n.z;
double d = dot(newTriangles->fNormals[i], newTriangles->vertices[a]);
newTriangles->d[i] = d;
}
我使用此 cout
命令来确保正确输入我的值。在这段代码中,我只打印出索引 0 处的第一个元素,看看它会发生什么。
这是我尝试用 48 个元素初始化数组时的一些示例输出:
0: 6, 7, 15 (this is correct)
1: 6, 7, 15
2: 6, 7, 15
... (repeats)
28: 6, 7, 15
29: -422365367, -1077858410, 15
30: -422365367, -1077858410, -58508617
31: -422365367, -1077858410, -58508617
... (repeats)
47: -422365367, -1077858410, -58508617
很明显,在我初始化数组的那个循环中,我的数据被破坏了。对我来说毫无意义。