Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Rendering;
- using System.Threading.Tasks;
- using Unity.Mathematics;
- using Unity.Jobs;
- using Unity.Collections;
- using Unity.Burst;
- using UnityEngine.Profiling;
- using System.Diagnostics;
- using System.Xml.Serialization;
- public class MeshGenerator : MonoBehaviour
- {
- public static Vector2Int chunkDimensions = new Vector2Int(32, 192);
- public Material material;
- public ComputeShader voxelGridShader;
- public int brushSize;
- public float brushStrength;
- public int lod;
- public int maxLod;
- public int maxChunksProcessing;
- public float surfaceLevel;
- public bool weldedVertices;
- public bool hideMeshOnPlay;
- public bool interpolate;
- public bool stopWatch;
- [Header("Noise Settings")]
- public float heightMultiplier;
- public int curveResolution;
- public AnimationCurve heightCurve;
- public float frequency;
- public float lacunarity;
- public float persistance;
- public int octaves;
- public float density;
- public float warpingStrength;
- public float warpingFrequency;
- public Vector2 offset;
- [Header("")]
- public bool autoUpdate;
- public string executionTime;
- NativeArray<int> nativeTriTable;
- NativeArray<int> nativeCaseToNumPolys;
- Camera cam;
- VoxelGrid voxelGrid;
- List<ChunkData> chunksToProcess;
- int chunksProcessing;
- private void Start()
- {
- Init();
- if (GameObject.Find("Mesh") != null)
- {
- GameObject.Find("Mesh").SetActive(!hideMeshOnPlay);
- }
- }
- private void Update()
- {
- if (Input.GetKeyDown(KeyCode.Space))
- {
- EditorMesh();
- }
- //Limit the number of chunks that can be processed at once, preventing lag spikes
- for (int i = 0; i < chunksToProcess.Count; i++)
- {
- if(chunksProcessing < maxChunksProcessing)
- {
- ProcessChunk(chunksToProcess[i]);
- chunksProcessing++;
- chunksToProcess.RemoveAt(i);
- }
- }
- }
- public GameObject ChunkObject(Vector2 position)
- {
- GameObject chunk = new GameObject("Chunk");
- chunk.AddComponent<MeshFilter>().mesh = ChunkMesh(position, 0);
- chunk.AddComponent<MeshRenderer>().material = material;
- chunk.GetComponent<MeshRenderer>().receiveShadows = false;
- chunk.GetComponent<MeshRenderer>().shadowCastingMode = ShadowCastingMode.Off;
- return chunk;
- }
- public Mesh ChunkMesh(Vector2 position, int lod)
- {
- Mesh mesh = new Mesh();
- mesh.indexFormat = IndexFormat.UInt32;
- lod = lod == 0 ? 1 : lod * 2;
- chunksToProcess.Add(new ChunkData
- {
- mesh = mesh,
- position = position,
- lod = lod
- });
- return mesh;
- }
- public void EditorMesh()
- {
- Init();
- Mesh mesh = ChunkMesh(offset / 10, lod);
- ProcessChunk(chunksToProcess[0]);
- chunksToProcess.Clear();
- if (GameObject.Find("Mesh") == null)
- {
- GameObject obj = new GameObject("Mesh");
- obj.transform.parent = transform;
- obj.AddComponent<MeshFilter>().mesh = mesh;
- obj.AddComponent<MeshRenderer>().material = material;
- obj.AddComponent<MeshCollider>();
- }
- else
- {
- var mf = GameObject.Find("Mesh").GetComponent<MeshFilter>();
- var collider = GameObject.Find("Mesh").GetComponent<MeshCollider>();
- mf.mesh = mesh;
- collider.sharedMesh = null;
- collider.sharedMesh = mesh;
- }
- }
- void Init()
- {
- chunksToProcess = new();
- cam = Camera.main;
- nativeTriTable = new NativeArray<int>(256 * 15, Allocator.Persistent);
- nativeCaseToNumPolys = new NativeArray<int>(256, Allocator.Persistent);
- for (int i = 0; i < Tables.triTable.Length; i++)
- {
- nativeCaseToNumPolys[i] = Tables.caseToNumPolys[i];
- for (int j = 0; j < 15; j++)
- {
- nativeTriTable[(i * 15) + j] = Tables.triTable[i][j];
- }
- }
- voxelGrid = new VoxelGrid(frequency, lacunarity, persistance, octaves, surfaceLevel, density, heightMultiplier, warpingFrequency, warpingStrength, curveResolution, heightCurve, voxelGridShader);
- }
- void ProcessChunk(ChunkData cd)
- {
- //Getting back data from the GPU is slow, so first the voxel grid is requested then
- //whenever the data has reached the CPU the mesh is constructed
- Profiler.BeginSample("Requesting Voxel grid");
- voxelGrid.RequestVoxelGrid(cd.position, cd.lod, out ShaderData shaderData);
- Profiler.EndSample();
- Stopwatch watch = new Stopwatch();
- watch.Start();
- AsyncGPUReadback.Request(shaderData.voxelGridBuffer);
- CompleteReadBack(shaderData, cd.mesh, cd.lod, watch);
- // AsyncGPUReadback.Request(shaderData.voxelGridBuffer, request =>
- // {
- // if (request.hasError)
- // {
- // UnityEngine.Debug.LogWarning("GPU readback error detected.");
- // }
- // else
- // {
- // watch.Stop();
- // if (stopWatch)
- // UnityEngine.Debug.Log("Getting voxelGrid took " + watch.ElapsedMilliseconds + " ms");
- // Profiler.BeginSample("Readback after completion");
- // NativeArray<float> voxelGrid = request.GetData<float>();
- // ConstructMesh(voxelGrid, cd.mesh, cd.lod);
- // Profiler.EndSample();
- // }
- // });
- // //CompleteReadBack(shaderData, cd.mesh, cd.lod, watch);
- //}
- }
- async void CompleteReadBack(ShaderData sd, Mesh mesh, int lod, Stopwatch watch)
- {
- var request = AsyncGPUReadback.Request(sd.voxelGridBuffer);
- // Wait for the request to complete
- while (!request.done)
- {
- await Task.Yield();
- }
- if (request.hasError)
- {
- UnityEngine.Debug.LogWarning("GPU readback error detected.");
- }
- else
- {
- watch.Stop();
- if (stopWatch)
- {
- UnityEngine.Debug.Log("Getting voxelGrid took " + watch.ElapsedMilliseconds + " ms");
- }
- Profiler.BeginSample("Readback after completion");
- //Get voxelGrid after readback is complete
- sd.voxelGridBuffer.Release();
- sd.noiseMap2DBuffer.Release();
- sd.noiseMap2D.Dispose();
- float[] voxelGrid = request.GetData<float>().ToArray();
- ConstructMesh(voxelGrid, mesh, lod);
- Profiler.EndSample();
- }
- }
- async void ConstructMesh(float[] voxelGrid, Mesh mesh, int lod)
- {
- List<Vector3> vertices = new();
- List<int> indices = new();
- Dictionary<Vector3, int> vertDictionary = new();
- MeshData meshData = new MeshData
- {
- vertices = vertices,
- indices = indices,
- vertDictionary = vertDictionary,
- voxelGrid = voxelGrid,
- lod = lod
- };
- //Offloads mesh creation to another thread so the main thread is not halted
- await Task.Run(() =>
- {
- for (int z = 0, i = 0; z < chunkDimensions.x; z += lod)
- {
- for (int y = 0; y < chunkDimensions.y; y += lod)
- {
- for (int x = 0; x < chunkDimensions.x; x += lod, i++)
- {
- AddVertices(i, new Vector3Int(x, y, z), meshData);
- }
- }
- }
- });
- mesh.vertices = vertices.ToArray();
- mesh.triangles = indices.ToArray();
- mesh.RecalculateNormals();
- chunksProcessing--;
- }
- void AddVertices(int index, Vector3Int pos, MeshData md)
- {
- float[] voxelCornerValues = new float[8];
- for (int i = 0; i < 8; i++)
- {
- voxelCornerValues[i] = md.voxelGrid[(index * 8) + i];
- }
- int triCase = CalculateCase(voxelCornerValues);
- int[] edges = Tables.triTable[triCase];
- for (int j = 0, i = 0; j < Tables.caseToNumPolys[triCase]; j++, i += 3)
- {
- for (int h = 0; h < 3; h++)
- {
- Vector3 vertex = GetEdgePosition(edges[i + (2 - h)], voxelCornerValues, md.lod, pos);
- //Checks for duplicate vertices
- if (md.vertDictionary.TryGetValue(vertex, out int triIndex))
- {
- md.indices.Add(triIndex);
- }
- else
- {
- md.vertDictionary.Add(vertex, md.vertices.Count);
- md.vertices.Add(vertex);
- md.indices.Add(md.vertices.Count - 1);
- }
- }
- }
- }
- Vector3 GetEdgePosition(int edge, float[] voxelData, int lod, Vector3Int pos)
- {
- int x = pos.x;
- int y = pos.y;
- int z = pos.z;
- switch (edge)
- {
- case 0: return GetInterpolatedEdgePosition(x, y, z, voxelData[0], voxelData[1], 0, 1, 0);
- case 1: return GetInterpolatedEdgePosition(x, y + lod, z, voxelData[1], voxelData[2], 1, 0, 0);
- case 2: return GetInterpolatedEdgePosition(x + lod, y, z, voxelData[3], voxelData[2], 0, 1, 0);
- case 3: return GetInterpolatedEdgePosition(x, y, z, voxelData[0], voxelData[3], 1, 0, 0);
- case 4: return GetInterpolatedEdgePosition(x, y, z + lod, voxelData[4], voxelData[5], 0, 1, 0);
- case 5: return GetInterpolatedEdgePosition(x, y + lod, z + lod, voxelData[5], voxelData[6], 1, 0, 0);
- case 6: return GetInterpolatedEdgePosition(x + lod, y, z + lod, voxelData[7], voxelData[6], 0, 1, 0);
- case 7: return GetInterpolatedEdgePosition(x, y, z + lod, voxelData[4], voxelData[7], 1, 0, 0);
- case 8: return GetInterpolatedEdgePosition(x, y, z, voxelData[0], voxelData[4], 0, 0, 1);
- case 9: return GetInterpolatedEdgePosition(x, y + lod, z, voxelData[1], voxelData[5], 0, 0, 1);
- case 10: return GetInterpolatedEdgePosition(x + lod, y + lod, z, voxelData[2], voxelData[6], 0, 0, 1);
- case 11: return GetInterpolatedEdgePosition(x + lod, y, z, voxelData[3], voxelData[7], 0, 0, 1);
- default: throw new ArgumentOutOfRangeException(nameof(edge), "Invalid edge index: " + edge);
- }
- }
- Vector3 GetInterpolatedEdgePosition(int x, int y, int z, float voxelA, float voxelB, int offsetX, int offsetY, int offsetZ)
- {
- float interpolation = (0 - voxelA) / (voxelB - voxelA);
- return new Vector3(x + offsetX * interpolation, y + offsetY * interpolation, z + offsetZ * interpolation);
- }
- int CalculateCase(float[] voxelData)
- {
- int triCase = 0;
- for (int i = 0; i < 8; i++)
- {
- int bit = voxelData[i] < 0 ? 1 : 0;
- triCase |= bit << i;
- }
- return triCase;
- }
- struct MeshData
- {
- public List<Vector3> vertices;
- public List<int> indices;
- public Dictionary<Vector3, int> vertDictionary;
- public float[] voxelGrid;
- public int lod;
- }
- struct ChunkData
- {
- public Mesh mesh;
- public Vector2 position;
- public int lod;
- }
- }
- [BurstCompile]
- struct MeshJob : IJobParallelFor
- {
- [WriteOnly]
- public NativeQueue<Triangle>.ParallelWriter triangles;
- [ReadOnly]
- public NativeArray<float> voxelGrid;
- [ReadOnly]
- public int lod;
- [ReadOnly]
- public int2 chunkDimensions;
- [ReadOnly]
- public bool interpolate;
- [ReadOnly]
- public NativeArray<int> triTable;
- [ReadOnly]
- public NativeArray<int> caseToNumTris;
- public void Execute(int i)
- {
- int z = i / (chunkDimensions.x / lod * chunkDimensions.y / lod) * lod;
- int y = (i / (chunkDimensions.x / lod) * lod) - z / lod * chunkDimensions.y;
- int x = i % (chunkDimensions.x / lod) * lod;
- AddTriangles(i, x, y, z);
- }
- void AddTriangles(int index, int x, int y, int z)
- {
- int triCase = CalculateCase(index);
- int triIndex = 0;
- for (int i = 0; i < caseToNumTris[triCase]; i++)
- {
- int edge0 = triTable[(triCase * 15) + triIndex + 2];
- float3 vertex0 = CalculateVertexPosition(edge0, index, lod, x, y, z);
- int edge1 = triTable[(triCase * 15) + triIndex + 1];
- float3 vertex1 = CalculateVertexPosition(edge1, index, lod, x, y, z);
- int edge2 = triTable[(triCase * 15) + triIndex];
- float3 vertex2 = CalculateVertexPosition(edge2, index, lod, x, y, z);
- triIndex += 3;
- triangles.Enqueue(new Triangle
- {
- vertex0 = vertex0,
- vertex1 = vertex1,
- vertex2 = vertex2
- });
- }
- }
- //Returns vertex position at on of the 12 edges of a cube
- float3 CalculateVertexPosition(int edge, int index, int lod, int x, int y, int z)
- {
- int i = index * 8;
- switch (edge)
- {
- case 0:
- return interpolate ? InterpolatePosition(x, y, z, voxelGrid[i], voxelGrid[i + 1], 0, 1, 0) : new float3(x, y + 1, z);
- case 1:
- return interpolate ? InterpolatePosition(x, y + lod, z, voxelGrid[i + 1], voxelGrid[i + 2], 1, 0, 0) : new float3(x + 1, y + lod, z);
- case 2:
- return interpolate ? InterpolatePosition(x + lod, y, z, voxelGrid[i + 3], voxelGrid[i + 2], 0, 1, 0) : new float3(x + lod, y + 1, z);
- case 3:
- return interpolate ? InterpolatePosition(x, y, z, voxelGrid[i], voxelGrid[i + 3], 1, 0, 0) : new float3(x + 1, y, z);
- case 4:
- return interpolate ? InterpolatePosition(x, y, z + lod, voxelGrid[i + 4], voxelGrid[i + 5], 0, 1, 0) : new float3(x, y + 1, z + lod);
- case 5:
- return interpolate ? InterpolatePosition(x, y + lod, z + lod, voxelGrid[i + 5], voxelGrid[i + 6], 1, 0, 0) : new float3(x + 1, y + lod, z + lod);
- case 6:
- return interpolate ? InterpolatePosition(x + lod, y, z + lod, voxelGrid[i + 7], voxelGrid[i + 6], 0, 1, 0) : new float3(x + lod, y + 1, z + lod);
- case 7:
- return interpolate ? InterpolatePosition(x, y, z + lod, voxelGrid[i + 4], voxelGrid[i + 7], 1, 0, 0) : new float3(x + 1, y, z + lod);
- case 8:
- return interpolate ? InterpolatePosition(x, y, z, voxelGrid[i], voxelGrid[i + 4], 0, 0, 1) : new float3(x, y, z + 1);
- case 9:
- return interpolate ? InterpolatePosition(x, y + lod, z, voxelGrid[i + 1], voxelGrid[i + 5], 0, 0, 1) : new float3(x, y + lod, z + 1);
- case 10:
- return interpolate ? InterpolatePosition(x + lod, y + lod, z, voxelGrid[i + 2], voxelGrid[i + 6], 0, 0, 1) : new float3(x + lod, y + lod, z + 1);
- case 11:
- return interpolate ? InterpolatePosition(x + lod, y, z, voxelGrid[i + 3], voxelGrid[i + 7], 0, 0, 1) : new float3(x + lod, y, z + 1);
- default:
- throw new ArgumentOutOfRangeException(nameof(edge), "Invalid edge index: " + edge);
- }
- }
- public float3 InterpolatePosition(int x, int y, int z, float cornerValue0, float cornerValue1, int offsetX, int offsetY, int offsetZ)
- {
- float interpolation = (0 - cornerValue0) / (cornerValue1 - cornerValue0);
- return new float3(x + offsetX * interpolation, y + offsetY * interpolation, z + offsetZ * interpolation);
- }
- public int CalculateCase(int index)
- {
- int triCase = 0;
- for (int i = 0; i < 8; i++)
- {
- int bit = voxelGrid[(index * 8) + i] < 0 ? 1 : 0;
- triCase |= bit << i;
- }
- return triCase;
- }
- }
- public struct Triangle
- {
- public float3 vertex0;
- public float3 vertex1;
- public float3 vertex2;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement