-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChunk.cs
652 lines (534 loc) · 17 KB
/
Chunk.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
using UnityEngine;
using System.Collections.Generic;
namespace Uzu
{
/// <summary>
/// A single "chunk" within the block world.
/// Each chunk represents a single mesh.
/// Large chunks will require more time to rebuild due to the large number of vertices contained.
/// Small chunks take less time to rebuild, but this will increase the number of meshes (draw calls) for the scene.
/// Chunks with multiple materials are split into submeshes.
/// </summary>
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class Chunk : BaseBehaviour
{
/// <summary>
/// Does this chunk need to be rebuilt?
/// </summary>
public bool DoesNeedRebuild { get { return _doesNeedRebuild; } }
/// <summary>
/// Request that this chunk be rebuilt.
/// </summary>
public void RequestRebuild ()
{
_doesNeedRebuild = true;
}
/// <summary>
/// Gets the blocks associated with this chunk.
/// </summary>
public BlockContainer Blocks { get { return _blocks; } }
/// <summary>
/// Performs initialization.
/// Called when a chunk is first added to the world.
/// </summary>
public void Initialize (BlockWorldConfig worldConfig)
{
_config = worldConfig;
// First initialization?
if (_blocks == null) {
_blocks = new BlockContainer (_config.ChunkSizeInBlocks);
_meshDesc = new ChunkMeshDesc (GetChunkMeshCreationConfig ());
_subMeshLUT = new FixedList<int> (worldConfig.MaxBlockTypeCount);
}
}
/// <summary>
/// Performs chunk cleanup.
/// </summary>
public void TearDown ()
{
_mesh.Clear ();
_doesNeedRebuild = false;
}
/// <summary>
/// Rebuilds this chunk's mesh.
/// </summary>
public void Rebuild ()
{
//using (ScopedSystemTimer timer = new ScopedSystemTimer("Chunk Rebuild Time"))
{
// Rebuild batches in case materials have changed.
RebuildBatches ();
Vector3 blockSize = _config.BlockSize;
VectorI3 count = _blocks.CountXYZ;
int countX = count.x;
int countY = count.y;
int countZ = count.z;
int lastX = countX - 1;
int lastY = countY - 1;
int lastZ = countZ - 1;
int createdFaceCount = 0;
// For each block...
int currentIndex = 0;
for (int x = 0; x < countX; x++) {
for (int y = 0; y < countY; y++) {
for (int z = 0; z < countZ; z++) {
Block thisBlock = _blocks [currentIndex];
// Skip empty blocks.
if (thisBlock.IsEmpty) {
++currentIndex;
continue;
}
BlockDesc blockDesc = _config.BlockDescs [(int)thisBlock.Type];
#region Ignore hidden faces.
BlockFaceFlag activeFaces = FACEFLAG_FULL_MASK;
// Apply user-specified ignore faces.
activeFaces &= ~blockDesc.IgnoreFaces;
// Disabled shared faces.
if (x > 0 &&
!_blocks [x - 1, y, z].IsEmpty) {
activeFaces &= ~BlockFaceFlag.Left;
}
if (x < lastX &&
!_blocks [x + 1, y, z].IsEmpty) {
activeFaces &= ~BlockFaceFlag.Right;
}
if (y > 0 &&
!_blocks [x, y - 1, z].IsEmpty) {
activeFaces &= ~BlockFaceFlag.Bottom;
}
if (y < lastY &&
!_blocks [x, y + 1, z].IsEmpty) {
activeFaces &= ~BlockFaceFlag.Top;
}
if (z > 0 &&
!_blocks [x, y, z - 1].IsEmpty) {
activeFaces &= ~BlockFaceFlag.Front;
}
if (z < lastZ &&
!_blocks [x, y, z + 1].IsEmpty) {
activeFaces &= ~BlockFaceFlag.Back;
}
#endregion
if (createdFaceCount > _config.MaxVisibleBlockFaceCountPerChunk) {
Debug.Log ("Visibile face count exceeded maximum count of [" + _config.MaxVisibleBlockFaceCountPerChunk + "]. Ignoring faces.");
break;
}
// Create the block.
int subMeshIndex = _subMeshLUT [(int)thisBlock.Type];
ChunkSubMeshDesc subMeshDesc = _subMeshDescs [subMeshIndex];
Vector3 blockOffset = new Vector3 (x * blockSize.x, y * blockSize.y, z * blockSize.z);
createdFaceCount += CreateBlock (blockDesc, blockOffset, blockSize, activeFaces, _meshDesc, subMeshDesc, thisBlock.Color);
++currentIndex;
}
}
}
// Construct mesh.
{
// Fill the arrays out w/ default data so that no garbage remains.
{
for (int i = 0; i < _subMeshDescs.Count; i++) {
_subMeshDescs [i].FillToCapacity ();
}
}
_mesh.vertices = _meshDesc.VertexList.ToArray ();
_mesh.normals = _meshDesc.NormalList.ToArray ();
_mesh.colors32 = _meshDesc.ColorList.ToArray ();
_mesh.uv = _meshDesc.UVList.ToArray ();
for (int i = 0; i < _subMeshDescs.Count; i++) {
ChunkSubMeshDesc subMeshDesc = _subMeshDescs [i];
_mesh.SetTriangles (subMeshDesc.IndexList.ToArray (), i);
}
_mesh.Optimize ();
}
// Reset flag.
_doesNeedRebuild = false;
}
}
/// <summary>
/// Gets the block type of a given block index.
/// </summary>
public BlockType GetBlockType (VectorI3 blockChunkIndex)
{
Block block = _blocks [blockChunkIndex.x, blockChunkIndex.y, blockChunkIndex.z];
return block.Type;
}
/// <summary>
/// Gets the block color of a given block index.
/// </summary>
public Color32 GetBlockColor (VectorI3 blockChunkIndex)
{
Block block = _blocks [blockChunkIndex.x, blockChunkIndex.y, blockChunkIndex.z];
return block.Color;
}
/// <summary>
/// Changes the block type of a given block index.
/// </summary>
public void SetBlockType (VectorI3 blockChunkIndex, BlockType blockType)
{
Block block = _blocks [blockChunkIndex.x, blockChunkIndex.y, blockChunkIndex.z];
// Ignore if already the same.
if (block.Type == blockType) {
return;
}
block.Type = blockType;
// Mark as dirty.
RequestRebuild ();
}
/// <summary>
/// Changes the block color of a given block index.
/// </summary>
public void SetBlockColor (VectorI3 blockChunkIndex, Color32 blockColor)
{
Block block = _blocks [blockChunkIndex.x, blockChunkIndex.y, blockChunkIndex.z];
// Ignore if already the same.
{
Color32 oldColor = block.Color;
if (oldColor.r == blockColor.r &&
oldColor.g == blockColor.g &&
oldColor.b == blockColor.b &&
oldColor.a == blockColor.a) {
return;
}
}
block.Color = blockColor;
// Mark as dirty.
RequestRebuild ();
}
#region Implementation.
private BlockContainer _blocks;
private BlockWorldConfig _config;
private Mesh _mesh;
private MeshRenderer _meshRenderer;
private ChunkMeshDesc _meshDesc;
private SmartList<ChunkSubMeshDesc> _subMeshDescs = new SmartList<ChunkSubMeshDesc> ();
private SmartList<ChunkSubMeshDesc> _subMeshDescPool = new SmartList<ChunkSubMeshDesc> ();
private FixedList<int> _subMeshLUT;
private bool _doesNeedRebuild;
private BlockFaceFlag FACEFLAG_FULL_MASK = (BlockFaceFlag)0xFF;
/// <summary>
/// Work array to prevent garbage generation.
/// </summary>
private SmartList<Material> _materialBatchesWork = new SmartList<Material> ();
#if false
public void OnDrawGizmosSelected()
{
float blockSize = _config.BlockSize.x;
float halfBlockSize = blockSize * 0.5f;
VectorI3 count = _blocks.CountXYZ;
#region Draw block type ids.
for (int x = 0; x < count.x; x++) {
for (int y = 0; y < count.y; y++) {
for (int z = 0; z < count.z; z++) {
Block thisBlock = _blocks [x, y, z];
Vector3 blockOffset = new Vector3 (x * blockSize + halfBlockSize, y * blockSize + halfBlockSize, z * blockSize + halfBlockSize);
Dbg.DrawText(CachedXform.localPosition + blockOffset, ((int)thisBlock.BlockType).ToString());
break;
}
}
}
#endregion
}
#endif
/// <summary>
/// Creates a single block at the given base position.
/// Returns the number of generated faces.
/// </summary>
private static int CreateBlock (BlockDesc blockDesc, Vector3 basePos, Vector3 blockSize, BlockFaceFlag activeFacesFlag, ChunkMeshDesc meshDesc, ChunkSubMeshDesc subMeshDesc, Color32 blockColor)
{
int faceCount = 0;
// All faces are hidden, so we don't need to do anything.
if (activeFacesFlag == 0) {
return faceCount;
}
float x = basePos.x;
float y = basePos.y;
float z = basePos.z;
FixedList<Vector3> vList = meshDesc.VertexList;
FixedList<int> iList = subMeshDesc.IndexList;
FixedList<Vector3> nList = meshDesc.NormalList;
FixedList<Color32> cList = meshDesc.ColorList;
FixedList<Vector2> uvList = meshDesc.UVList;
// Vertices.
Vector3 v0 = new Vector3 (x, y, z);
Vector3 v1 = new Vector3 (x + blockSize.x, y, z);
Vector3 v2 = new Vector3 (x + blockSize.x, y + blockSize.y, z);
Vector3 v3 = new Vector3 (x, y + blockSize.y, z);
Vector3 v4 = new Vector3 (x + blockSize.x, y, z + blockSize.z);
Vector3 v5 = new Vector3 (x, y, z + blockSize.z);
Vector3 v6 = new Vector3 (x, y + blockSize.y, z + blockSize.z);
Vector3 v7 = new Vector3 (x + blockSize.x, y + blockSize.y, z + blockSize.z);
// Normals.
Vector3 up = Vector3.up;
Vector3 down = Vector3.down;
Vector3 front = Vector3.back;
Vector3 back = Vector3.forward;
Vector3 left = Vector3.left;
Vector3 right = Vector3.right;
// UVs.
Vector2 uv00 = Vector2.zero;
Vector2 uv10 = new Vector2 (1.0f, 0.0f);
Vector2 uv11 = Vector2.one;
Vector2 uv01 = new Vector2 (0.0f, 1.0f);
// Starting index offset (offset by # of vertices).
int baseIdx = vList.Count;
#region Polygon construction.
if ((activeFacesFlag & BlockFaceFlag.Front) != 0) {
vList.Add (v0);
vList.Add (v1);
vList.Add (v2);
vList.Add (v3);
nList.Add (front);
nList.Add (front);
nList.Add (front);
nList.Add (front);
uvList.Add (uv00);
uvList.Add (uv10);
uvList.Add (uv11);
uvList.Add (uv01);
iList.Add (baseIdx + 3);
iList.Add (baseIdx + 1);
iList.Add (baseIdx + 0);
iList.Add (baseIdx + 3);
iList.Add (baseIdx + 2);
iList.Add (baseIdx + 1);
faceCount++;
}
if ((activeFacesFlag & BlockFaceFlag.Right) != 0) {
vList.Add (v1);
vList.Add (v4);
vList.Add (v7);
vList.Add (v2);
nList.Add (right);
nList.Add (right);
nList.Add (right);
nList.Add (right);
uvList.Add (uv00);
uvList.Add (uv10);
uvList.Add (uv11);
uvList.Add (uv01);
int idxOffset = 4 * faceCount;
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
iList.Add (baseIdx + 0 + idxOffset);
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 2 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
faceCount++;
}
if ((activeFacesFlag & BlockFaceFlag.Back) != 0) {
vList.Add (v4);
vList.Add (v5);
vList.Add (v6);
vList.Add (v7);
nList.Add (back);
nList.Add (back);
nList.Add (back);
nList.Add (back);
uvList.Add (uv00);
uvList.Add (uv10);
uvList.Add (uv11);
uvList.Add (uv01);
int idxOffset = 4 * faceCount;
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
iList.Add (baseIdx + 0 + idxOffset);
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 2 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
faceCount++;
}
if ((activeFacesFlag & BlockFaceFlag.Left) != 0) {
vList.Add (v5);
vList.Add (v0);
vList.Add (v3);
vList.Add (v6);
nList.Add (left);
nList.Add (left);
nList.Add (left);
nList.Add (left);
uvList.Add (uv00);
uvList.Add (uv10);
uvList.Add (uv11);
uvList.Add (uv01);
int idxOffset = 4 * faceCount;
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
iList.Add (baseIdx + 0 + idxOffset);
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 2 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
faceCount++;
}
if ((activeFacesFlag & BlockFaceFlag.Top) != 0) {
vList.Add (v3);
vList.Add (v2);
vList.Add (v7);
vList.Add (v6);
nList.Add (up);
nList.Add (up);
nList.Add (up);
nList.Add (up);
uvList.Add (uv00);
uvList.Add (uv10);
uvList.Add (uv11);
uvList.Add (uv01);
int idxOffset = 4 * faceCount;
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
iList.Add (baseIdx + 0 + idxOffset);
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 2 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
faceCount++;
}
if ((activeFacesFlag & BlockFaceFlag.Bottom) != 0) {
vList.Add (v5);
vList.Add (v4);
vList.Add (v1);
vList.Add (v0);
nList.Add (down);
nList.Add (down);
nList.Add (down);
nList.Add (down);
uvList.Add (uv00);
uvList.Add (uv10);
uvList.Add (uv11);
uvList.Add (uv01);
int idxOffset = 4 * faceCount;
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
iList.Add (baseIdx + 0 + idxOffset);
iList.Add (baseIdx + 3 + idxOffset);
iList.Add (baseIdx + 2 + idxOffset);
iList.Add (baseIdx + 1 + idxOffset);
faceCount++;
}
// Set colors per vertex.
int vertCount = faceCount * 4;
for (int i = 0; i < vertCount; ++i) {
cList.Add (blockColor);
}
#endregion
return faceCount;
}
/// <summary>
/// Rebuilds the batches associated w/ this chunk.
/// Used for material batching and subMesh division.
/// </summary>
private void RebuildBatches ()
{
// Clean up existing batch info.
{
// Return to pool for re-use.
// Push in reverse order so that we don't flip back and forth each time.
for (int i = _subMeshDescs.Count - 1; i >= 0; i--) {
ChunkSubMeshDesc subMeshDesc = _subMeshDescs [i];
subMeshDesc.Clear ();
_subMeshDescPool.Add (subMeshDesc);
}
_mesh.Clear ();
_meshDesc.Clear ();
_subMeshDescs.Clear ();
_subMeshLUT.Clear ();
}
// Calculate the # of batches.
{
// Reset LUT to default state.
{
const int INVALID_BATCH_INDEX = -1;
for (int i = 0; i < _subMeshLUT.Capacity; i++) {
_subMeshLUT.Add (INVALID_BATCH_INDEX);
}
}
// For each block...
int count = _blocks.Count;
for (int i = 0; i < count; i++) {
Block block = _blocks [i];
// Empty blocks don't use materials.
if (block.IsEmpty) {
continue;
}
int blockTypeInt = (int)block.Type;
BlockDesc blockDesc = _config.BlockDescs [blockTypeInt];
// Does a batch for this block desc already exist?
bool doesBatchExist = false;
for (int j = 0; j < _materialBatchesWork.Count; j++) {
if (_materialBatchesWork [j] == blockDesc.Material) {
// Add to main LUT.
int batchIndex = j;
_subMeshLUT [blockTypeInt] = batchIndex;
doesBatchExist = true;
break;
}
}
// New batch discovered.
if (!doesBatchExist) {
int batchIndex = _materialBatchesWork.Count;
_subMeshLUT [blockTypeInt] = batchIndex;
_materialBatchesWork.Add (blockDesc.Material);
}
}
}
int batchCount = _materialBatchesWork.Count;
// No materials used (empty chunk).
if (batchCount == 0) {
return;
}
// One subMesh per batch.
_mesh.subMeshCount = batchCount;
_meshRenderer.materials = _materialBatchesWork.ToArray ();
// Create mesh descs.
{
ChunkMeshCreationConfig config = GetChunkMeshCreationConfig ();
for (int i = 0; i < batchCount; i++) {
ChunkSubMeshDesc subMeshDesc;
// Take from pool if available.
if (_subMeshDescPool.Count > 0) {
int lastIndex = _subMeshDescPool.Count - 1;
subMeshDesc = _subMeshDescPool [lastIndex];
_subMeshDescPool.RemoveAt (lastIndex);
} else {
subMeshDesc = new ChunkSubMeshDesc (config);
}
Dbg.Assert (subMeshDesc != null);
_subMeshDescs.Add (subMeshDesc);
}
}
#if UNITY_EDITOR
{
int expectedBatchCount = _materialBatchesWork.Count;
int actualBatchCount = _subMeshDescs.Count;
if (actualBatchCount != expectedBatchCount) {
Debug.LogError("Invalid batch count: " + actualBatchCount + "/" + expectedBatchCount);
}
}
#endif
// Clear for re-use next frame.
_materialBatchesWork.Clear ();
}
private ChunkMeshCreationConfig GetChunkMeshCreationConfig ()
{
const int FACE_COUNT_PER_BLOCK = 6;
ChunkMeshCreationConfig config = new ChunkMeshCreationConfig ();
// Add 1 block as buffer.
config.MaxVisibileFaceCount = _config.MaxVisibleBlockFaceCountPerChunk + FACE_COUNT_PER_BLOCK;
return config;
}
protected override void Awake ()
{
base.Awake ();
// Setup mesh to be used for rendering this chunk.
{
_mesh = new Mesh ();
MeshFilter meshFilter = GetComponent<MeshFilter> ();
meshFilter.mesh = _mesh;
_meshRenderer = GetComponent<MeshRenderer> ();
_meshRenderer.castShadows = false;
_meshRenderer.receiveShadows = false;
_mesh.MarkDynamic ();
}
}
#endregion
}
}