I am currently following Frank D. Luna's DirectX 10 book. I have just come across a method he uses for rendering mountains and I am not quite sure I understand why he uses it. For the vertex buffer he uses: (n and m are rows and columns and dx is 1.0f)(getHeight puts x and z into a function resembling a mountain)
float dx = 1.0f;
float halfWidth = (n - 1)*dx*0.5f;
float halfDepth = (m - 1)*dx*0.5f;
for (DWORD i = 0; i < m; ++i)
{
float z = halfDepth - i*dx;
for (DWORD j = 0; j < n; ++j)
{
float x = -halfWidth + j*dx;
// Graph of this function looks like a mountain range.
float y = getHeight(x, z);
vertices[i*n + j].pos = D3DXVECTOR3(x, y, z);
// Color the vertex based on its height.
if (y < -10.0f)
vertices[i*n + j].color = BEACH_SAND;
else if (y < 5.0f)
vertices[i*n + j].color = LIGHT_YELLOW_GREEN;
else if (y < 12.0f)
vertices[i*n + j].color = DARK_YELLOW_GREEN;
else if (y < 20.0f)
vertices[i*n + j].color = DARKBROWN;
else
vertices[i*n + j].color = WHITE;
}
}
Then for the indices buffer he uses:
int k = 0;
for (DWORD i = 0; i < m - 1; ++i)
{
for (DWORD j = 0; j < n - 1; ++j)
{
indexlist[k] = i*n + j;
indexlist[k + 1] = i*n + j + 1;
indexlist[k + 2] = (i + 1)*n + j;
indexlist[k + 3] = (i + 1)*n + j;
indexlist[k + 4] = i*n + j + 1;
indexlist[k + 5] = (i + 1)*n + j + 1;
k += 6; // next quad
}
}
If someone could explain these two buffer uses to me that would be great. I am just not quite sure why he uses these equations and what these equations do.
When creating the vertexbuffer, the term i * n + j
is used to calculate the index of the current vertex. j
is used for the position on the x-axis. So if you increment j
and keep i
, you'll get to the vertex to the right on the same row. The index is also increased by 1. If you increment i
and keep j
, you'll get to the vertex below the current one. The index is increased by n
(the width of the field). This is natural, because the vertices in between have to be there.
Using a width of n = 4
, you get the following numbering
\ j| 0 | 1 | 2 | 3 |
i \| | | | |
---+----+----+----+----+
0 | 0 | 1 | 2 | 3 |
1 | 4 | 5 | 6 | 7 |
2 | 8 | 9 | 10 | 11 |
...
You see that moving from row i
to row i+1
results in the index being increased by the fields width, while going from column j
to j+1
results in the index increased by 1. This results in the formula j + i * n
.
The same formula is used for the calculation of the index buffer.
The first triangle is:
col j , row i -> j + i * n
col j + 1, row i -> j + 1 + i * n
col j , row i + 1 -> j + (i + 1) * n