# Terrain Math

This topic is 4934 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Here's the problem: I really suck at logical math and stuff like that. Here's the other problem: my geo-mipmapping math isn't working. I'm dividing the terrain (which used to be just a vertex buffer and a index buffer) into 100 meshes (or cells, whatever). First I initialize all the meshes, then I start filling the buffers:
TerrainVertex* v = 0;
int i = 0;
for(int z = startZ; z >= endZ; z -= _cellSpacing)
{
int j = 0;
for(int x = startX; x <= endX; x += _cellSpacing)
{
// compute the correct index into the vertex buffer and
// heightmap based on where we are in the nested loop.
int index = i * _numVertsPerRow + j;

// convert from the range [0 - numVertices] to [0 - numMeshes]
int meshIndexI = i * NUM_MESHES_COL / _numVertsPerCol;
int meshIndexJ = j * NUM_MESHES_ROW / _numVertsPerRow;
int meshIndex = meshIndexI * NUM_MESHES_COL + meshIndexJ;

// it crashes here after several iterations of meshIndexJ
littleMeshes[meshIndex]->LockVertexBuffer(0, (void**)&v);

// find the normal by taking the cross product of two
D3DXVECTOR3 nn = calcNormal(j, i);

v[index - meshIndex] = TerrainVertex(
(float)x, // init the position
(float)_heightmap[index],
(float)z,
nn.x, // the normal
nn.y,
nn.z,
(float)j * uCoordIncrementSize, // texture coordinates
(float)i * vCoordIncrementSize);
littleMeshes[meshIndex]->UnlockVertexBuffer();
v = 0;
j++; // next column
}
i++; // next row
}

I know it's not a programming error with pointers or something because the loop iterates for a while through several meshes before crashing when it indexes in the "littleMeshes" array. Any help would be greatly appreciated!

##### Share on other sites
Well just so you know. Memory problems sometimes do not occur until you iterate several elements past the end.

example:

int *pIntArray = new int[50]
for (int i = 0; i < 100; i++) {
int = i;
}

I bet you it will crash around the 55th or 60th iterations.
In some case's, if you are unlucky, this won't crash at all but instead totally corrupt the future parts of your program.

##### Share on other sites
Actually, it crashes no where near the end of the array.

It works like this: meshIndexI never changes. It's always 0. meshIndexJ changes like it should. It goes up to 16, which is numVertsPerRow (160) / NUM_MESHES_ROW (10), then it resets itself to 0 for the next row. The third time meshIndexJ resets itself to 0, it gets to 12 and then crashes. That's why I think my math is wrong.

1. 1
2. 2
Rutin
18
3. 3
khawk
15
4. 4
A4L
14
5. 5

• 9
• 13
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633744
• Total Posts
3013665
×