Hello, I’m currently having trouble getting chunking to work for marching cubes. I’ve based my project off of Scrawks (GitHub - Scrawk/Marching-Cubes: Marching cubes in Unity) Project.
This is my problem
The important part:
using UnityEngine;
using System.Collections.Generic;
public class Chunk : MonoBehaviour
{
public int width;
public int height;
public int length;
public Vector3Int coord;
public GameObject chunkObj;
public Material chunkMat;
public ChunkVoxelProvider chunkVoxelProvider;
private List<GameObject> meshes = new List<GameObject>();
public float[] voxels;
public void Generate(List<Chunk> chunks)
{
List<Vector3> verts = new List<Vector3>();
List<int> indices = new List<int>();
//The voxel array.
voxels = new float[width * height * length];
//Cubes is faster and creates less verts, tetrahedrons is slower and creates more verts but better represents the mesh surface.
Marching marching = new MarchingCubes();
//Surface is the value that represents the surface of mesh
//For example the perlin noise has a range of -1 to 1 so the mid point is where we want the surface to cut through.
//The target value does not have to be the mid point it can be any value with in the range.
marching.Surface = chunkVoxelProvider.surface;
//Get generated values from chunk provider.
voxels = chunkVoxelProvider.Provide(width, height, length, coord.x, coord.y, coord.z);
//The mesh produced is not optimal. There is one vert for each index.
//Would need to weld vertices for better quality mesh.
marching.Generate(voxels, width, height, length, verts, indices);
//A mesh in unity can only be made up of 65000 verts.
//Need to split the verts between multiple meshes.
int maxVertsPerMesh = 30000; //must be divisible by 3, ie 3 verts == 1 triangle
int numMeshes = verts.Count / maxVertsPerMesh + 1;
for (int i = 0; i < numMeshes; i++)
{
List<Vector3> splitVerts = new List<Vector3>();
List<int> splitIndices = new List<int>();
for (int j = 0; j < maxVertsPerMesh; j++)
{
int idx = i * maxVertsPerMesh + j;
if (idx < verts.Count)
{
splitVerts.Add(verts[idx]);
splitIndices.Add(j);
}
}
if (splitVerts.Count == 0) continue;
Mesh mesh = new Mesh();
mesh.SetVertices(splitVerts);
mesh.SetTriangles(splitIndices, 0);
mesh.RecalculateBounds();
mesh.RecalculateNormals();
GameObject go = new GameObject("Mesh-" + i);
go.transform.parent = transform;
go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
go.GetComponent<Renderer>().material = chunkMat;
go.GetComponent<MeshFilter>().mesh = mesh;
go.transform.localPosition = new Vector3(-width / 2, -height / 2, -length / 2);
meshes.Add(go);
}
}
}
I have no idea how I’d pass the neighboring voxel data in.
Any help is appreciated.