ChunkTerrainGenerator.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using NavMeshSurface = UnityEngine.AI.NavMeshSurface;
  5. using KairoEngine.Core;
  6. using KairoEngine.Chunks;
  7. using KairoEngine.NoiseUtilities;
  8. using Utilities = KairoEngine.Utility.Utilities;
  9. using Sirenix.OdinInspector;
  10. using UniRx;
  11. namespace KairoEngine.TerrainEngine
  12. {
  13. [HideMonoScript]
  14. public class ChunkTerrainGenerator : MonoBehaviour
  15. {
  16. [BoxGroup("Configurations")] public Vector3 voxelSize = new Vector3(1f, 1f, 1f);
  17. [BoxGroup("Configurations")] public Vector3Int chunkSize = new Vector3Int(16, 16, 16);
  18. [BoxGroup("Configurations")] public Vector3Int chunkLimit = new Vector3Int(2, 1, 2);
  19. [BoxGroup("Configurations")] public StartConfig startConfiguration = StartConfig.DoNothing;
  20. [BoxGroup("Configurations"), ShowIf("@startConfiguration == StartConfig.WaitForEvent")] public string generateWorldEvent = "GenerateWorld";
  21. [BoxGroup("Configurations")] public int dataProcessLimit = 4;
  22. [BoxGroup("Configurations")] public int parallelMeshJobs = 4;
  23. [HorizontalGroup("Configurations/NavMesh")] public bool processNavMesh = false;
  24. [HorizontalGroup("Configurations/NavMesh"), ShowIf("@processNavMesh"), HideLabel] public NavMeshSurface navMeshSurface;
  25. [BoxGroup("Configurations")] public bool showChunkData = false;
  26. [InlineProperty, HideLabel, BoxGroup("Marching Cubes")] public MarchingCubes4 marchingCubes = new();
  27. [BoxGroup("Map Data Generator"), InlineProperty, HideLabel, SerializeReference] public IMapDataGenerator mapDataGenerator;
  28. [ShowIf("@showChunkData"), BoxGroup("Chunk System"), InlineProperty, HideLabel] public ChunkSystem<BlockBase> chunkSystem;
  29. public Dictionary<Vector3, GameObject> terrainMeshes = new Dictionary<Vector3, GameObject>();
  30. private List<Vector3> chunkDataBuffer = new List<Vector3>(); // Store list of chunks for populating with data
  31. private List<Vector3> chunkMeshBuffer = new List<Vector3>(); // Store list of chunks for generating the mesh
  32. private bool initialized = false;
  33. public class VoxelUpdateData
  34. {
  35. public Vector3 position;
  36. public BlockBase block;
  37. public VoxelUpdateData(Vector3 position, BlockBase block)
  38. {
  39. this.position = position;
  40. this.block = block;
  41. }
  42. }
  43. private Dictionary<Vector3,List<VoxelUpdateData>> chunkUpdates = new Dictionary<Vector3, List<VoxelUpdateData>>();
  44. private void Start()
  45. {
  46. if(startConfiguration == StartConfig.GenerateOnStart) GenerateWorld();
  47. else if(startConfiguration == StartConfig.WaitForEvent) GenericEvents.StartListening(generateWorldEvent, GenerateWorld);
  48. }
  49. private void Update()
  50. {
  51. marchingCubes.UpdateFinishedJobs();
  52. }
  53. private void OnDisable()
  54. {
  55. if(startConfiguration == StartConfig.WaitForEvent) GenericEvents.StopListening(generateWorldEvent, GenerateWorld);
  56. }
  57. private void OnDestroy()
  58. {
  59. marchingCubes.OnDestroy();
  60. }
  61. public void Initialize ()
  62. {
  63. chunkSystem = new ChunkSystem<BlockBase>(chunkSize,voxelSize, true);
  64. initialized = true;
  65. }
  66. public bool IsInitialized() => initialized;
  67. [Button("Generate World"), ButtonGroup("Buttons")]
  68. void GenerateWorld()
  69. {
  70. if(mapDataGenerator == null)
  71. {
  72. Debug.LogError("Missing planet template", this.gameObject);
  73. return;
  74. }
  75. DestroyTerrain();
  76. Debug.Log("Starting chunk generation");
  77. Initialize();
  78. for (int x = 0; x < chunkLimit.x; x++) {
  79. for (int z = 0; z < chunkLimit.z; z++) {
  80. for (int y = 0; y < chunkLimit.y; y++) {
  81. Vector3 chunkGlobalPos = new Vector3(x * chunkSize.x * voxelSize.x, y * chunkSize.y * voxelSize.y, z * chunkSize.z * voxelSize.z);
  82. Vector3Int chunkPos = new Vector3Int(x * chunkSize.x, y * chunkSize.y, z * chunkSize.z);
  83. chunkSystem.CreateChunk(chunkGlobalPos, chunkPos, (Chunk<BlockBase> c, Vector3Int pos) => new BlockBase(0, 0));
  84. PopulateChunkData(chunkGlobalPos);
  85. }
  86. }
  87. }
  88. for (int x = 0; x < chunkLimit.x; x++) {
  89. for (int z = 0; z < chunkLimit.z; z++) {
  90. for (int y = 0; y < chunkLimit.y; y++) {
  91. //Vector3Int chunkPos = new Vector3Int(x * chunkSize.x, y * chunkSize.y, z * chunkSize.z);
  92. Vector3 chunkPos = new Vector3(x * chunkSize.x * voxelSize.x, y * chunkSize.y * voxelSize.y, z * chunkSize.z * voxelSize.z);
  93. GenerateTerrainMesh(chunkPos);
  94. //else if(marchingCubes2 != null) marchingCubes2.Generate(chunkSystem, chunkPos);
  95. }
  96. }
  97. }
  98. #if UNITY_EDITOR
  99. UpdateEditor ();
  100. #endif
  101. }
  102. public void GenerateChunk(Vector3 position)
  103. {
  104. position = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(position);
  105. bool buffered = false;
  106. for (int i = 0; i < chunkDataBuffer.Count; i++)
  107. {
  108. if(chunkDataBuffer[i] == position) buffered = true;
  109. }
  110. for (int i = 0; i < chunkMeshBuffer.Count; i++)
  111. {
  112. if(chunkMeshBuffer[i] == position) buffered = true;
  113. }
  114. //if(chunkSystem.ChunkExists(position)) buffered = true;
  115. //bool meshGenerated = terrainMeshes.TryGetValue(position, out GameObject obj);
  116. //if(meshGenerated) buffered = true;
  117. if(buffered) return;
  118. chunkDataBuffer.Add(position);
  119. }
  120. void PopulateChunkData(Vector3 initialPos)
  121. {
  122. float width = (float)(chunkLimit.x * chunkSize.x * voxelSize.x);
  123. float height = (float)(chunkLimit.y * chunkSize.y * voxelSize.y);
  124. float length = (float)(chunkLimit.z * chunkSize.z * voxelSize.z);
  125. for (int x = 0; x < chunkSize.x; x++) {
  126. for (int z = 0; z < chunkSize.z; z++) {
  127. for (int y = 0; y < chunkSize.y; y++) {
  128. // Get a terrain height using regular old Perlin noise.
  129. Vector3 pos = initialPos + new Vector3(x * voxelSize.x, y * voxelSize.y, z * voxelSize.z);
  130. // Old example noise:
  131. //float thisHeight = height * Mathf.PerlinNoise((float)pos.x / width * noiseMultiplier + 0.001f, (float)pos.z / length * noiseMultiplier + 0.001f);
  132. float elevation = mapDataGenerator.SamplePoint((float)pos.x / width, (float)pos.z / length);
  133. float thisHeight = height * elevation;
  134. uint code = mapDataGenerator.SamplePointColor((float)pos.x / width, (float)pos.z / length, elevation);
  135. BlockBase block = new BlockBase(code, (uint)Mathf.FloorToInt(thisHeight * 1000));
  136. chunkSystem.SetBlock(pos, block);
  137. }
  138. }
  139. }
  140. chunkUpdates.TryGetValue(initialPos, out List<VoxelUpdateData> updates);
  141. if(updates == null) return;
  142. for (int i = 0; i < updates.Count; i++)
  143. {
  144. chunkSystem.SetBlock(updates[i].position, updates[i].block);
  145. }
  146. }
  147. public void GenerateChunkData(Vector3 position)
  148. {
  149. position = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(position);
  150. Vector3Int chunkPos = chunkSystem.GetChunkPositionFromGlobalPosition(position);
  151. if(!chunkSystem.ChunkExists(position))
  152. {
  153. //Debug.Log($"Generating Terrain Data ({position} | {chunkPos})");
  154. chunkSystem.CreateChunk(position, chunkPos, (Chunk<BlockBase> c, Vector3Int pos) => new BlockBase(0, 0));
  155. PopulateChunkData(position);
  156. }
  157. }
  158. public void GenerateTerrainMesh(Vector3 position, bool overwrite = false)
  159. {
  160. bool meshExists = terrainMeshes.TryGetValue(position, out GameObject obj);
  161. if(meshExists && !overwrite) return;
  162. if(!overwrite) terrainMeshes.Add(position, null);
  163. if(marchingCubes != null) marchingCubes.Generate(chunkSystem, this, position);
  164. }
  165. public void UpdateGenerator()
  166. {
  167. if(marchingCubes.GetJobCount() == 0) ProcessChunkDataBuffer();
  168. ProcessChunkMeshBuffer();
  169. }
  170. public void UpdateEditor ()
  171. {
  172. Timer.ExecuteRealTime(50, () => {
  173. if(marchingCubes != null)
  174. {
  175. UpdateGenerator();
  176. if(!marchingCubes.IsGeneratorDone()) UpdateEditor();
  177. }
  178. });
  179. }
  180. private void ProcessChunkDataBuffer()
  181. {
  182. int limit = chunkDataBuffer.Count < dataProcessLimit ? chunkDataBuffer.Count : dataProcessLimit;
  183. for (int i = 0; i < limit; i++)
  184. {
  185. Vector3 position = chunkDataBuffer[i];
  186. List<Vector3> positions = new List<Vector3>{
  187. new Vector3( 0, 0, 0),
  188. new Vector3( 1, 0, 0),
  189. new Vector3( 1, 0, -1),
  190. new Vector3( 0, 0, -1),
  191. new Vector3(-1, 0, -1),
  192. new Vector3(-1, 0, 0),
  193. new Vector3(-1, 0, 1),
  194. new Vector3( 0, 0, 1),
  195. new Vector3( 1, 0, 1),
  196. new Vector3( 0, 1, 0),
  197. new Vector3( 1, 1, 0),
  198. new Vector3( 1, 1, -1),
  199. new Vector3( 0, 1, -1),
  200. new Vector3(-1, 1, -1),
  201. new Vector3(-1, 1, 0),
  202. new Vector3(-1, 1, 1),
  203. new Vector3( 0, 1, 1),
  204. new Vector3( 1, 1, 1),
  205. new Vector3( 0, -1, 0),
  206. new Vector3( 1, -1, 0),
  207. new Vector3( 1, -1, -1),
  208. new Vector3( 0, -1, -1),
  209. new Vector3(-1, -1, -1),
  210. new Vector3(-1, -1, 0),
  211. new Vector3(-1, -1, 1),
  212. new Vector3( 0, -1, 1),
  213. new Vector3( 1, -1, 1),
  214. };
  215. for (int a = 0; a < positions.Count; a++)
  216. {
  217. //position = new Vector3(position.x + chunkSize.x * voxelSize.x, position.y, position.z);
  218. Vector3 chunkPos = new Vector3(
  219. position.x + (positions[a].x * chunkSize.x * voxelSize.x),
  220. position.y + (positions[a].y * chunkSize.y * voxelSize.y),
  221. position.z + (positions[a].z * chunkSize.z * voxelSize.z)
  222. );
  223. GenerateChunkData(chunkPos);
  224. }
  225. chunkMeshBuffer.Add(chunkDataBuffer[i]);
  226. }
  227. chunkDataBuffer.RemoveRange(0, limit);
  228. }
  229. private void ProcessChunkMeshBuffer()
  230. {
  231. bool terrainChanged = false;
  232. marchingCubes.UpdateFinishedJobs();
  233. int limit = marchingCubes.GetJobCount() < parallelMeshJobs ? parallelMeshJobs - marchingCubes.GetJobCount() : 0;
  234. limit = limit < chunkMeshBuffer.Count ? limit : chunkMeshBuffer.Count;
  235. for (int i = 0; i < limit; i++)
  236. {
  237. GenerateTerrainMesh(chunkMeshBuffer[i]);
  238. }
  239. if(chunkMeshBuffer.Count > 0) terrainChanged = true;
  240. chunkMeshBuffer.RemoveRange(0, limit);
  241. if(!processNavMesh) return;
  242. if(terrainChanged && chunkMeshBuffer.Count == 0 && chunkDataBuffer.Count == 0 && navMeshSurface != null)
  243. Timer.ExecuteRealTime(50, () => navMeshSurface.BuildNavMesh());
  244. }
  245. public void DestroyChunk(Vector3 position)
  246. {
  247. DestroyChunkData(position);
  248. DestroyChunkMesh(position);
  249. }
  250. public void DestroyChunkData(Vector3 position)
  251. {
  252. chunkSystem.DestroyChunk(position);
  253. }
  254. public void DestroyChunkMesh(Vector3 position)
  255. {
  256. terrainMeshes.TryGetValue(position, out GameObject obj);
  257. if(obj != null)
  258. {
  259. Destroy(obj);
  260. #if UNITY_EDITOR
  261. DestroyImmediate(obj);
  262. #endif
  263. }
  264. terrainMeshes.Remove(position);
  265. }
  266. public void ClearChunkDataBuffer() => chunkDataBuffer.Clear();
  267. [Button("Destroy"), ButtonGroup("Buttons")]
  268. public void DestroyTerrain()
  269. {
  270. var childTransforms = this.gameObject.transform.GetComponentsInChildren<Transform>();
  271. if(childTransforms.Length > 0) Debug.Log($"Destroying {childTransforms.Length - 1} terrain objects");
  272. for (int i = 0; i < childTransforms.Length; i++)
  273. {
  274. if(childTransforms[i] == this.transform) continue;
  275. #if UNITY_EDITOR
  276. DestroyImmediate(childTransforms[i].gameObject);
  277. #else
  278. Destroy(childTransforms[i].gameObject);
  279. #endif
  280. }
  281. terrainMeshes = new Dictionary<Vector3, GameObject>();
  282. chunkDataBuffer = new List<Vector3>();
  283. chunkMeshBuffer = new List<Vector3>();
  284. chunkSystem.chunks = new Dictionary<Vector3Int, Chunk<BlockBase>>();
  285. chunkSystem.chunkList = new List<Vector3>();
  286. }
  287. public enum VoxelOperation
  288. {
  289. Add,
  290. Remove,
  291. Level
  292. }
  293. public void ChangeVoxels(Vector3 pos, uint code, VoxelOperation operation, int radius = 3)
  294. {
  295. int startHeigth = 0, endHeigth = 0, targetHeigth = 0, updatedVoxels = 0;
  296. switch (operation)
  297. {
  298. case VoxelOperation.Add:
  299. startHeigth = -1;
  300. endHeigth = radius;
  301. targetHeigth = (int)(((chunkSystem.GetBlock(pos).value/1000) + (radius * voxelSize.y)) * 1000);
  302. break;
  303. case VoxelOperation.Remove:
  304. startHeigth = -1 * (radius + 1);
  305. endHeigth = radius + 1;
  306. targetHeigth = (int)(Mathf.Clamp((chunkSystem.GetBlock(pos).value/1000) - (radius * voxelSize.y), 0, 10000) * 1000);
  307. break;
  308. case VoxelOperation.Level:
  309. startHeigth = -1 * radius;
  310. endHeigth = radius;
  311. targetHeigth = (int)chunkSystem.GetBlock(pos).value;
  312. break;
  313. default:
  314. return;
  315. }
  316. Vector3 chunkPosition = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(pos);
  317. List<Vector2Int> points = Utilities.GetPointsInRadius(radius, true);
  318. List<Vector3> chunkPositions = new List<Vector3>();
  319. for (int j = 0; j < points.Count; j++)
  320. {
  321. for (int y = startHeigth; y < endHeigth + 1; y++)
  322. {
  323. updatedVoxels += 1;
  324. Vector3 voxelPos = new Vector3(pos.x + points[j].x * voxelSize.x, pos.y + y * voxelSize.y, pos.z + points[j].y * voxelSize.z);
  325. BlockBase block = chunkSystem.GetBlock(voxelPos);
  326. block.code = code;
  327. block.value = (uint)targetHeigth;
  328. chunkSystem.SetBlock(voxelPos, block);
  329. // Get positions
  330. Vector3Int localVoxelPos = chunkSystem.GetVoxelFromGlobalPosition(voxelPos);
  331. Vector3 chunkPos = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(voxelPos);
  332. // Save data update
  333. VoxelUpdateData updateData = new VoxelUpdateData(voxelPos, block);
  334. chunkUpdates.TryGetValue(chunkPos, out List<VoxelUpdateData> chunkUpdate);
  335. if(chunkUpdate != null)
  336. {
  337. bool exists = false;
  338. for (int h = 0; h < chunkUpdate.Count; h++)
  339. {
  340. if(chunkUpdate[h].position.Equals(updateData.position))
  341. {
  342. exists = true;
  343. chunkUpdate[h].block = updateData.block;
  344. }
  345. }
  346. if(!exists) chunkUpdate.Add(updateData);
  347. }
  348. else chunkUpdates.Add(chunkPos, new List<VoxelUpdateData>{updateData});
  349. // Check if changed voxels are in the edge of the chunk and if true add the neightboring chunk to the update list
  350. List<Vector3> chunks = new List<Vector3>();
  351. chunks.Add(chunkPos);
  352. if(localVoxelPos.x == 0) chunks.Add(new Vector3(chunkPos.x - chunkSize.x * voxelSize.x, chunkPos.y, chunkPos.z));
  353. if(localVoxelPos.x == 16) chunks.Add(new Vector3(chunkPos.x + chunkSize.x * voxelSize.x, chunkPos.y, chunkPos.z));
  354. if(localVoxelPos.y == 0) chunks.Add(new Vector3(chunkPos.x, chunkPos.y - chunkSize.y * voxelSize.y, chunkPos.z));
  355. if(localVoxelPos.y == 16) chunks.Add(new Vector3(chunkPos.x, chunkPos.y + chunkSize.y * voxelSize.y, chunkPos.z));
  356. if(localVoxelPos.z == 0) chunks.Add(new Vector3(chunkPos.x, chunkPos.y, chunkPos.z - chunkSize.z * voxelSize.z));
  357. if(localVoxelPos.z == 16) chunks.Add(new Vector3(chunkPos.x , chunkPos.y, chunkPos.z + chunkSize.z * voxelSize.z));
  358. for (int i = 0; i < chunks.Count; i++)
  359. {
  360. bool duplicate = false;
  361. for (int k = 0; k < chunkPositions.Count; k++)
  362. {
  363. if(chunkPositions[k].Equals(chunks[i]))
  364. {
  365. duplicate = true;
  366. break;
  367. }
  368. }
  369. if(!duplicate) chunkPositions.Add(chunks[i]);
  370. }
  371. }
  372. }
  373. for (int c = 0; c < chunkPositions.Count; c++) GenerateTerrainMesh(chunkPositions[c], true);
  374. Debug.Log($"Changing voxel at {pos}, updated {updatedVoxels} voxels and {chunkPositions.Count} chunks");
  375. }
  376. public void AddGeneratedTerrainMesh(Vector3 chunkPosition, GameObject meshObj)
  377. {
  378. bool meshExists = terrainMeshes.TryGetValue(chunkPosition, out GameObject currentMesh);
  379. if(currentMesh != null)
  380. {
  381. //Debug.Log($"Updating chunk mesh at {chunkPosition}");
  382. DestroyChunkMesh(chunkPosition);
  383. terrainMeshes[chunkPosition] = meshObj;
  384. }
  385. else
  386. {
  387. //Debug.Log($"Adding chunk mesh at {chunkPosition}");
  388. //terrainMeshes.Add(chunkPosition, meshObj);
  389. terrainMeshes[chunkPosition] = meshObj;
  390. }
  391. }
  392. [Button("Save"), ButtonGroup("Buttons")]
  393. public void SaveChunkUpdateData()
  394. {
  395. }
  396. public enum StartConfig
  397. {
  398. DoNothing,
  399. GenerateOnStart,
  400. WaitForEvent
  401. }
  402. }
  403. }