I'm generating a relatively low-poly terrain for my game using the code below:
for (int z = 0; z < VERTEX_COUNT; z++) {
for (int x = 0; x < VERTEX_COUNT; x++) {
final float posX = x / ((float) VERTEX_COUNT - 1) * SIZE;
final float height = generateHeight(x, z);
final float posY = height;
final float posZ = z / ((float) VERTEX_COUNT - 1) * SIZE;
final Vector3 nor = getNormals(x, z);
final float norX = nor.x;
final float norY = nor.y;
final float norZ = nor.z;
final float texU = x / ((float) VERTEX_COUNT - 1);
final float texV = z / ((float) VERTEX_COUNT - 1);
// Create vertex
}
}
for (int z = 0; z < VERTEX_COUNT - 1; z++) {
for (int x = 0; x < VERTEX_COUNT - 1; x++) {
final int topLeft = (z * VERTEX_COUNT) + x;
final int topRight = topLeft + 1;
final int bottomLeft = ((z + 1) * VERTEX_COUNT) + x;
final int bottomRight = bottomLeft + 1;
//Triangle 1: topLeft - bottomLeft - topRight
//Triangle 2: topRight - bottomLeft - mottomRight
}
}
private Vector3 getNormals(final int x, final int z) {
final float heightL = generateHeight(x - 1, z);
final float heightR = generateHeight(x + 1, z);
final float heightD = generateHeight(x, z - 1);
final float heightU = generateHeight(x, z + 1);
return new Vector3(heightL - heightR, 2f, heightD - heightU).nor();
}
This works perfectly fine and generates a smooth terrain mesh. The problem is I want this mesh to use flat shading; i.e. I don't want vertices to be shared between triangles. But I don't know how I would duplicate the vertices and find the appropriate indices to properly index the mesh. Any help?
Here's in image from google in case it wasn't clear (left shading is what I want, right is what I have):
P.S. I found this code for the Unity scripting language:
Vector3[] oldVerts = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3[] vertices = new Vector3[triangles.Length];
for (int i = 0; i < triangles.Length; i++) {
vertices[i] = oldVerts[triangles[i]];
triangles[i] = i;
}
mesh.vertices = vertices;
mesh.triangles = triangles;
Perhaps this is the solution I'm looking for? If so, how can I translate this code to using float[]
instead of Vector3[]
array for my vertices? And what is the triangles
array, the indices?