3D Terrain mesh generation error C#
Asked Answered
C

2

0

I am following this tutorial to generate a terrain mesh, and converting it to C#.

I am getting an error:
scene/resources/mesh.cpp:354 - Condition "index >= vc" is true. Returning: Ref<TriangleMesh>()
This happens twice upon generation.

The geometry is also completely wrong:

And here:

And finally, here is my code:

` private void generateChunk()
{
var aMesh = new ArrayMesh();
var surfTool = new SurfaceTool();

	surfTool.Begin(Mesh.PrimitiveType.Triangles);

	var vertexCount = 0;

	for (int x = 0; x <= chunkSize; x++)
	{
		int y = 0;

        for (int z = 0; z <= chunkSize; z++)
        {
			var pos = new Vector3(x, y, z);

            surfTool.AddVertex(pos);
			vertexCount++;

            drawDebugSphere(pos);
        }
    }

	int index = 0;
	for (int x = 0; x <= chunkSize; x++)
	{
		int y = 0;

		for (int z = 0; z <= chunkSize; z++)
		{
			surfTool.AddIndex(index + 0);
            surfTool.AddIndex(index + 1);
            surfTool.AddIndex(index + chunkSize + 1);
            surfTool.AddIndex(index + chunkSize + 1);
            surfTool.AddIndex(index + 1);
            surfTool.AddIndex(index + chunkSize + 2);
			index++;
        }
            //index++;
    }

    GD.PushWarning($"Vertex count: {vertexCount}, Index count: {index * 6}");

	//surfTool.GenerateNormals();
    aMesh = surfTool.Commit();
	Mesh = aMesh;
}

`

Any help would be greatly appreciated!

  • DrBellubins
Concoff answered 23/9, 2023 at 23:20 Comment(0)
B
0

Concoff Please format your code properly by using ``` at first and last line.

Bondswoman answered 24/9, 2023 at 16:4 Comment(0)
L
0

The creator of that series made a mistake in his code. Let's say you have a grid size of 5 x 5 faces. That is 36 vertices (zSize + 1 * xSize + 1). These vertices are stored in a 1 dimensional array starting at index 0. So you start adding triangles from the very first vertex (index 0) and you draw your triangles down to the next row (0, 1, xSize +1). Seems simple enough but now what happens when we get to the last row (zSize +1 * xSize) or in the case of our 5 x 5 grid, index number 31? If we try to do xSize + 2 as in the tutorial to draw down we can't because we only have 36 vertices (index 35) and xSize +2 would be be index 36 or the 37th vertex which does not exist. A simple fix is to just use a single loop as we're working with a 1 dimensional array anyway and to stop our count one row before the very last row and one vertex before the end of that row as that is where our last triangle will be.

for (int i = 0; i < (zSize * (xSize + 1) - 1); i++)
  {
        surfaceTool.AddIndex(i + 0);
	surfaceTool.AddIndex(i + 1);
	surfaceTool.AddIndex(i + xSize + 1);

	surfaceTool.AddIndex(i + xSize + 1);
	surfaceTool.AddIndex(i + 1);
	surfaceTool.AddIndex(i + xSize + 2);
  }
Leg answered 23/2 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.