The problem is not with the calculations. Rather the fact that the program crashes.
I get the following dialog after running
"Windows has triggered a breakpoint in RenderEngine.exe.
This may be due to a corruption of the heap, which indicates a bug in RenderEngine.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while RenderEngine.exe has focus.
The output window may have more diagnostic information.
t".
[/quote]
Here is the method:
D3DXVECTOR3* Terrain::CalculateSurfaceNormals(TerrainVertex* verts)
{
D3DXVECTOR3* triangleNormals = new D3DXVECTOR3[((width-1) * (length-1))];
for (int x = 0; x < width-1; x++)
{
for (int z = 0; z < length-1; z++)
{
int i0,i1,i2,i3;
//calculate the 4 indices of this quad
i0 = x+(z*width);
i1 = (x+1)+z*width;
i2 = (x)+(z+1)*width;
i3 = (x+1)+(z+1)*width;
// ###############
//triangle 1
D3DXVECTOR3 v1 = *new D3DXVECTOR3(verts[i0].x,verts[i0].y,verts[i0].z);
D3DXVECTOR3 v2 = *new D3DXVECTOR3(verts[i1].x,verts[i1].y,verts[i1].z);
D3DXVECTOR3 v3 = *new D3DXVECTOR3(verts[i2].x,verts[i2].y,verts[i2].z);
D3DXVECTOR3 e1 = v2-v1;
D3DXVECTOR3 e2 = v3-v1;
//CROSS PRODUCT
D3DXVECTOR3 cross;
cross.x = e1.y*e2.z - e1.z*e2.y;
cross.y = e1.z*e2.x - e1.x*e2.z;
cross.z = e1.x*e2.y - e1.y*e2.x;
//NORMALIZE THE VECTOR
float magnitude = sqrt((cross.x * cross.x) +(cross.y * cross.y) + (cross.z * cross.z));
cross.x /= magnitude;
cross.z /= magnitude;
cross.y /= magnitude;
triangleNormals[(2*x) + ((z) * (2*(width-1)))] = cross;
//############
////triangle 2
D3DXVECTOR3 v1_2 = v3;
D3DXVECTOR3 v2_2 = v2;
D3DXVECTOR3 v3_2 = *new D3DXVECTOR3(verts[i3].x, verts[i3].y, verts[i3].z);
D3DXVECTOR3 e1_2 = v2_2-v1_2;
D3DXVECTOR3 e2_2 = v3_2-v1_2;
//CROSS PRODUCT
D3DXVECTOR3 cross_2;
cross_2.x = e1_2.y*e2_2.z - e1_2.z*e2_2.y;
cross_2.y = e1_2.z*e2_2.x - e1_2.x*e2_2.z;
cross_2.z = e1_2.x*e2_2.y - e1_2.y*e2_2.x;
//NORMALIZE THE VECTOR
float magnitude_2 = sqrt((cross_2.x * cross_2.x) +(cross_2.y * cross_2.y) + (cross_2.z * cross_2.z));
cross_2.x /= magnitude_2;
cross_2.z /= magnitude_2;
cross_2.y /= magnitude_2;
triangleNormals[(2*x) + ((z) * (2*(width-1))) + 1] = cross_2;
}
}
return triangleNormals;
}
additional info:
- currently the terrain grid is 64*64, ideally id want to go bigger when i program optimization.
- when it crashes it is about halfway through the nested loop x =34, y = 0
- the code is executed at the start of the program. during initialization and not in the game loop
Im not the most advanced when it comes to c++, i can only imagine its a memory problem.
I think the logic is correct (its late) but if you see any please make me aware because I would hate to get it running and see the wrong results.
thank you for your time.