Dub*_*Dot 3 c++ graphics vertices indices
我目前正在制作一种方法来加载嘈杂的高度图,但缺少三角形来这样做。我想制作一个算法来获取图像,它的宽度和高度并从中构建一个地形节点。
这是我到目前为止所拥有的,有点伪
Vertex* vertices = new Vertices[image.width * image.height];
Index* indices; // How do I judge how many indices I will have?
float scaleX = 1 / image.width;
float scaleY = 1 / image.height;
float currentYScale = 0;
for(int y = 0; y < image.height; ++y) {
float currentXScale = 0;
for (int x = 0; x < image.width; ++x) {
Vertex* v = vertices[x * y];
v.x = currentXScale;
v.y = currentYScale;
v.z = image[x,y];
currentXScale += scaleX;
}
currentYScale += scaleY;
}
Run Code Online (Sandbox Code Playgroud)
这足以满足我的需要,我唯一的问题是:如何计算索引的数量及其绘制三角形的位置?我对索引有些熟悉,但不知道如何以编程方式计算它们,我只能静态地这样做。
就你上面的代码而言,使用vertices[x * y]是不对的 - 如果你使用它,那么例如vert(2,3) == vert(3,2). 你想要的是类似的东西vertices[y * image.width + x],但你可以通过增加一个计数器来更有效地做到这一点(见下文)。
这是我使用的等效代码。不幸的是它在 C# 中,但希望它应该说明这一点:
/// <summary>
/// Constructs the vertex and index buffers for the terrain (for use when rendering the terrain).
/// </summary>
private void ConstructBuffers()
{
int heightmapHeight = Heightmap.GetLength(0);
int heightmapWidth = Heightmap.GetLength(1);
int gridHeight = heightmapHeight - 1;
int gridWidth = heightmapWidth - 1;
// Construct the individual vertices for the terrain.
var vertices = new VertexPositionTexture[heightmapHeight * heightmapWidth];
int vertIndex = 0;
for(int y = 0; y < heightmapHeight; ++y)
{
for(int x = 0; x < heightmapWidth; ++x)
{
var position = new Vector3(x, y, Heightmap[y,x]);
var texCoords = new Vector2(x * 2f / heightmapWidth, y * 2f / heightmapHeight);
vertices[vertIndex++] = new VertexPositionTexture(position, texCoords);
}
}
// Create the vertex buffer and fill it with the constructed vertices.
this.VertexBuffer = new VertexBuffer(Renderer.GraphicsDevice, typeof(VertexPositionTexture), vertices.Length, BufferUsage.WriteOnly);
this.VertexBuffer.SetData(vertices);
// Construct the index array.
var indices = new short[gridHeight * gridWidth * 6]; // 2 triangles per grid square x 3 vertices per triangle
int indicesIndex = 0;
for(int y = 0; y < gridHeight; ++y)
{
for(int x = 0; x < gridWidth; ++x)
{
int start = y * heightmapWidth + x;
indices[indicesIndex++] = (short)start;
indices[indicesIndex++] = (short)(start + 1);
indices[indicesIndex++] = (short)(start + heightmapWidth);
indices[indicesIndex++] = (short)(start + 1);
indices[indicesIndex++] = (short)(start + 1 + heightmapWidth);
indices[indicesIndex++] = (short)(start + heightmapWidth);
}
}
// Create the index buffer.
this.IndexBuffer = new IndexBuffer(Renderer.GraphicsDevice, typeof(short), indices.Length, BufferUsage.WriteOnly);
this.IndexBuffer.SetData(indices);
}
Run Code Online (Sandbox Code Playgroud)
我想关键是,给定一个 size 的高度图heightmapHeight * heightmapWidth,您需要(heightmapHeight - 1) * (heightmapWidth - 1) * 6索引,因为您正在绘制:
2 每个网格正方形的三角形3 每个三角形的顶点(heightmapHeight - 1) * (heightmapWidth - 1) 地形中的网格方块。