I am currently making a method to load in a noisy heightmap, but lack the triangles to do so. I want to make an algorithm that will take an image, its width and height and construct a terrain node out of it.
Here’s what I have so far, in somewhat pseudo
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;
}
This works well enough to my needs, my only problem is this: How would I calculate the # of indices and their positions for drawing the triangles? I have somewhat familiarity with indices, but not how to programmatically calculate them, I can only do that statically.
As far as your code above goes, using
vertices[x * y]isn’t right – if you use that, then e.g.vert(2,3) == vert(3,2). What you want is something likevertices[y * image.width + x], but you can do it more efficiently by incrementing a counter (see below).Here’s the equivalent code I use. It’s in C# unfortunately, but hopefully it should illustrate the point:
I guess the key point is that given a heightmap of size
heightmapHeight * heightmapWidth, you need(heightmapHeight - 1) * (heightmapWidth - 1) * 6indices, since you’re drawing:2triangles per grid square3vertices per triangle(heightmapHeight - 1) * (heightmapWidth - 1)grid squares in your terrain.