Basic voxel map generation in unity 3D

Basic voxel map generation in unity 3D

In the past I haven’t done that much procedural generation in unity so I thought I’d give it a go having done similar things in OpenGL prior to this.

 

Code snippet – Incomplete

I don’t currently have the full source code publicly available!

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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum RenderFlags
{
OPAQUE_GEOMETRY,
TRANSPARENT_GEOMETRY
}

// Flags for per voxel culling and other options
[System.Flags]
public enum VoxelFlags : uint
{
// Culling options
CULL_FRONT = 0x1,
CULL_BACK = 0x2,
CULL_LEFT = 0x4,
CULL_RIGHT = 0x8,
CULL_BOTTOM = 0x10,
CULL_TOP = 0x20,
AIR = 0x40, // Not rendered at all
TRANSPARENT = 0x80 // Rendered in 'second/subsequent' pass sorted, expensive.
}

// The voxel itself.
public class VoxelTexture
{
// the material this voxel uses.
public Material material;

// texture coords, first bottom left. clockwise winding
public Vector2[] textureCoords = new Vector2[4];
}

// provides interface for looking up voxel material by ID
public class VoxelTextureMap
{
///

/// Used for textel correction, avoid bleeding.
///

public uint textureSize = 32;

Dictionary<uint, VoxelTexture> voxelDataMap = new Dictionary<uint, VoxelTexture>();

private uint _textureIDCount = 0;

public uint TextureIDCount {
get { return _textureIDCount; }
}

// returns the texture for the given ID in the map.
public VoxelTexture getTextureForID(uint ID)
{
return voxelDataMap[ID];
}

// Add texture to the mapping
public void addTexture(AtlasTexture texture)
{

float xDiv = (texture.uvSubDivisions.x > 0) ? texture.uvSubDivisions.x : 1;
float yDiv = (texture.uvSubDivisions.y > 0) ? texture.uvSubDivisions.y : 1;

float subSizeX = 1.0f / xDiv;
float subSizeY = 1.0f / yDiv;

float textelOffset = subSizeX / 64.0f;

// create a map entry for every atlas image, increment count
for (uint i = 0; i < xDiv; ++i)
{
for (uint p = 0; p < yDiv; ++p)
{
VoxelTexture vTexture = new VoxelTexture();
vTexture.material = texture.material;

// Bottom Left
vTexture.textureCoords[0].x = (i * subSizeX) + textelOffset;
vTexture.textureCoords[0].y = (p * subSizeY) + textelOffset;

// Top Left
vTexture.textureCoords[1].x = (i * subSizeX) + textelOffset;
vTexture.textureCoords[1].y = ((p * subSizeY) + subSizeY) - textelOffset;

// Top Right
vTexture.textureCoords[2].x = ((i * subSizeX) + subSizeX) - textelOffset;
vTexture.textureCoords[2].y = ((p * subSizeY) + subSizeY) - textelOffset;

// Bottom Right
vTexture.textureCoords[3].x = ((i * subSizeX) + subSizeX) - textelOffset;
vTexture.textureCoords[3].y = (p * subSizeY) + textelOffset;

this.voxelDataMap.Add(_textureIDCount, vTexture);

_textureIDCount++;
}
}

}

}

// Voxel that makes up voxel chunk, size needs to be minimilisitic
public class VoxelDat // possibly turn this into a scriptable object.
{
// voxel prefab
protected internal Voxel voxel;
protected internal uint flags; // flags used for face culling and other things.

// for faster sorting store the distance to the origin, used to quickly establish distance from camera for sorting.
//public float sortDistance;
protected internal Vector3 position;

public Vector3 Position {
get { return position; }
}

// Meta data for block update min size per block 4 bytes
public VoxelMeta metaData;
}

public class VoxelChunk
{

Camera mainCamera;

public Vector3 position;

private uint chunkSize = 16;

private Mesh mesh;
private MeshFilter meshFilter;
private MeshRenderer meshRenderer;

// for transparent pass.
private Mesh meshTrans;
private MeshFilter meshFilterTrans;
private MeshRenderer meshRendererTrans;

// ref to parent map.
private VoxelMap parent;

// ref parent gameobject where mesh resides
private GameObject gameObject;
private GameObject transparenPass;
private GameObject opaquePass;

// Dirty flag triggers resort of transparent geometry.
bool sortDirty = true;

// Buffer is dirty, trigger buffer update
bool isDirty = false;

// Recalculate faces this update
bool recalculateFaces = false;

List voxelsToBeSorted = new List();

// holds a reference to each Voxel instance, this list should equal the max num voxels in a chunk.
private List voxels = new List();

public VoxelChunk(uint ChunkSize, uint subMeshSize)
{
this.chunkSize = ChunkSize;
}

// Set the chunk dirty, recalculate faces is expensive and should not be called regually, instead when a block is changed it should update its individual faces
public void setDirty(bool isDirty, bool recalculateFaces = false) {
this.isDirty = isDirty;
this.recalculateFaces = recalculateFaces;
}

public void init()
{
this.mainCamera = Camera.main;

this.mesh = new Mesh();

// Create parent game object
this.gameObject = new GameObject("VoxelChunk");
this.transparenPass = new GameObject("Transparent Pass");
this.opaquePass = new GameObject("Opaque Pass");

// Parent the children to the parent object.
this.transparenPass.transform.parent = this.gameObject.transform;
this.opaquePass.transform.parent = this.gameObject.transform;

this.gameObject.transform.position = this.position +( Vector3.one * this.chunkSize * 0.5f);
this.gameObject.transform.parent = this.parent.transform;

this.meshRenderer = this.opaquePass.AddComponent();
this.meshFilter = this.opaquePass.AddComponent();

this.meshRendererTrans = this.transparenPass.AddComponent();
this.meshFilterTrans = this.transparenPass.AddComponent();

this.meshRenderer.material = this.parent.textureMap.getTextureForID(0).material;
this.meshRendererTrans.material = this.parent.textureMap.getTextureForID(257).material;

int chunkOffset = -(int)this.chunkSize / 2;

for (int x = 0; x < this.chunkSize; ++x) {
for (int y = 0; y < this.chunkSize; ++y) {
for (int z = 0; z < this.chunkSize; ++z) {
// Create a new voxel
VoxelDat voxelToAdd = new VoxelDat();
voxelToAdd.voxel = this.parent.getVoxel(0);
//voxelToAdd.voxel.hasTransparency = true;
//voxelToAdd.sortDistance = Mathf.Abs(Vector3.Distance(Vector3.one, new Vector3(x,y,z) + this.gameObject.transform.position));
// voxels are offset by chunk offset, so the gameobjects center is in the center of the chunk, takes advantage of unitys sorting for transparent objects, origin has to be centered.
voxelToAdd.position = new Vector3(z + chunkOffset, y + chunkOffset, x + chunkOffset) + this.gameObject.transform.position;
voxels.Add(voxelToAdd);
}
}
}

this.calculateFaceCulling();

}

// Super expensive, called once on load to perform initial cull, iterates over entire mesh and performs culling.
public void calculateFaceCulling(){
for (int x = 0; x < this.chunkSize; ++x){
for (int y = 0; y < this.chunkSize; ++y){
for (int z = 0; z < this.chunkSize; ++z){
this.calculateFaceCulling(new Vector3(x,y,z));
}
}
}
}

// Calculate face culling for voxel at specific position.
public void calculateFaceCulling(Vector3 Position){

/*VoxelDat up = this.getVoxelAtPosition(Position + Vector3.up);
VoxelDat down = this.getVoxelAtPosition(Position - Vector3.up);
VoxelDat front = this.getVoxelAtPosition(Position + Vector3.forward);
VoxelDat back = this.getVoxelAtPosition(Position - Vector3.forward);
VoxelDat right = this.getVoxelAtPosition(Position + Vector3.right);
VoxelDat left = this.getVoxelAtPosition(Position - Vector3.right);*/


VoxelDat up = this.parent.getVoxelAtPosition(this.position +Position + Vector3.up, true);
VoxelDat down = this.parent.getVoxelAtPosition(this.position + Position - Vector3.up, true);
VoxelDat front = this.parent.getVoxelAtPosition(this.position + Position + Vector3.forward, true);
VoxelDat back = this.parent.getVoxelAtPosition(this.position + Position - Vector3.forward, true);
VoxelDat right = this.parent.getVoxelAtPosition(this.position + Position + Vector3.right, true);
VoxelDat left = this.parent.getVoxelAtPosition(this.position + Position - Vector3.right, true);

VoxelDat thisVoxel = this.getVoxelAtPosition(Position);

// This voxel is air cull all faces.
if (thisVoxel.voxel.airBlock) {
// write flag
thisVoxel.flags |= (uint)VoxelFlags.AIR;
}

// This voxel is TOTALLY transparent cull all faces.
if (thisVoxel.voxel.airBlock && (this.parent.RenderFlags & (uint)VoxelMapRenderFlags.RENDER_AIR) == 0)
{
thisVoxel.flags |= (uint)VoxelFlags.CULL_TOP;
thisVoxel.flags |= (uint)VoxelFlags.CULL_BOTTOM;
thisVoxel.flags |= (uint)VoxelFlags.CULL_LEFT;
thisVoxel.flags |= (uint)VoxelFlags.CULL_RIGHT;
thisVoxel.flags |= (uint)VoxelFlags.CULL_FRONT;
thisVoxel.flags |= (uint)VoxelFlags.CULL_BACK;
return;
}

if (up.voxel.hasTransparency || up.voxel.airBlock)
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_TOP;
else {
thisVoxel.flags |= (uint)VoxelFlags.CULL_TOP;
up.flags |= (uint)VoxelFlags.CULL_BOTTOM;
}

if (down.voxel.hasTransparency || down.voxel.airBlock)
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_BOTTOM;
else {
thisVoxel.flags |= (uint)VoxelFlags.CULL_BOTTOM;
down.flags |= (uint)VoxelFlags.CULL_TOP;
}

if (left.voxel.hasTransparency || left.voxel.airBlock)
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_LEFT;
else {
thisVoxel.flags |= (uint)VoxelFlags.CULL_LEFT;
left.flags |= (uint)VoxelFlags.CULL_RIGHT;
}

if (right.voxel.hasTransparency || right.voxel.airBlock)
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_RIGHT;
else {
thisVoxel.flags |= (uint)VoxelFlags.CULL_RIGHT;
right.flags |= (uint)VoxelFlags.CULL_LEFT;
}

if (front.voxel.hasTransparency || front.voxel.airBlock)
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_BACK;
else {
thisVoxel.flags |= (uint)VoxelFlags.CULL_BACK;
front.flags |= (uint)VoxelFlags.CULL_FRONT;
}

if (back.voxel.hasTransparency || back.voxel.airBlock)
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_FRONT;
else {
thisVoxel.flags |= (uint)VoxelFlags.CULL_FRONT;
back.flags |= (uint)VoxelFlags.CULL_BACK;
}

bool occuludeTransparentFaces = false;

// If has transparency and any one of the faces isn't culled then don't cull any of the faces
if (thisVoxel.voxel.hasTransparency) {

if (((thisVoxel.flags & (uint)VoxelFlags.CULL_TOP) != 1) ||
((thisVoxel.flags & (uint)VoxelFlags.CULL_BOTTOM) != 1) ||
((thisVoxel.flags & (uint)VoxelFlags.CULL_LEFT) != 1) ||
((thisVoxel.flags & (uint)VoxelFlags.CULL_RIGHT) != 1) ||
((thisVoxel.flags & (uint)VoxelFlags.CULL_FRONT) != 1) ||
((thisVoxel.flags & (uint)VoxelFlags.CULL_BACK) != 1) )
{
if (!occuludeTransparentFaces) {
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_TOP;
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_BOTTOM;
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_LEFT;
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_RIGHT;
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_FRONT;
thisVoxel.flags &= ~(uint)VoxelFlags.CULL_BACK;
}

// same goes for aajacent faces, if there opaque
if (!down.voxel.hasTransparency)
down.flags &= ~(uint)VoxelFlags.CULL_TOP;

if (!up.voxel.hasTransparency)
up.flags &= ~(uint)VoxelFlags.CULL_BOTTOM;

if (!left.voxel.hasTransparency)
left.flags &= ~(uint)VoxelFlags.CULL_RIGHT;

if (!right.voxel.hasTransparency)
right.flags &= ~(uint)VoxelFlags.CULL_LEFT;

if (front.voxel.hasTransparency)
front.flags &= ~(uint)VoxelFlags.CULL_FRONT;

if (back.voxel.hasTransparency)
back.flags &= ~(uint)VoxelFlags.CULL_BACK;

}
}

}

// ensure consistency when getting the array position for the voxel.
public int vectorToArrayPosition(Vector3 Position) {
return (int)(Position.x + ((float)this.chunkSize * Position.y) + (((float)this.chunkSize * this.chunkSize) * Position.z));
}

public void setVoxel(Vector3 Position, Voxel Voxel) {
int pos = this.vectorToArrayPosition(Position);

bool outsideRange = false;

// end of the chunk
if (Position.x < 0 || Position.y < 0 || Position.z < 0 || Position.x >= this.chunkSize || Position.y >= this.chunkSize || Position.z >= this.chunkSize) {
outsideRange = true;
}

if (pos >= this.voxels.Capacity || pos < 0 || outsideRange) {
Debug.LogError("Unable to set voxel at position specified");
return;
}

// Get the voxel data object.
VoxelDat voxelData = this.voxels[pos];
voxelData.flags = 0;
voxelData.voxel = Voxel;

// calculate face culling
this.calculateFaceCulling(Position);

// set the buffer dirty.
this.isDirty = true;
}

public VoxelDat getVoxelAtPosition(Vector3 Position)
{
// Get the position in the array of voxels.
int pos = this.vectorToArrayPosition(Position);

bool outsideRange = false;

// end of the chunk
if (Position.x < 0 || Position.y < 0 || Position.z < 0 || Position.x >= this.chunkSize || Position.y >= this.chunkSize || Position.z >= this.chunkSize)
{
outsideRange = true;
}

if (pos >= this.voxels.Capacity || pos < 0 || outsideRange) { // return transparent block, this can be optimised VoxelDat transparent = new VoxelDat(); transparent.voxel = new Voxel(); transparent.voxel.hasTransparency = true; transparent.flags |= (uint)VoxelFlags.AIR; return transparent; } return this.voxels[pos]; } public void update() { if (this.isDirty) { // Must be done prior to updating the buffer. if (this.recalculateFaces) { // calculates face culling for entire mesh - VERY EXPENSIVE - SHOULD ONLY BE CALLED WHEN RENDER SETTINGS CHANGE REALLY this.calculateFaceCulling(); this.recalculateFaces = false; } this.updateBuffer(); this.isDirty = false; } } //Block update variables, number of blocks that update per update. static int blockUpdatesPerCycle = 100; int currentBlock = 0; // returns true if this chunk has finished updating. >> called by voxel map.
public bool performBlockUpdates() {

for (int i = currentBlock; i < this.voxels.Count && i < currentBlock + blockUpdatesPerCycle; ++i) { foreach(VoxelBehaviour behaviour in this.voxels[i].voxel.behaviours) { behaviour.blockUpdate(this.voxels[i]); } currentBlock++; } if (currentBlock >= this.voxels.Count) {
currentBlock = 0;
return true;
}
else {
return false;
}

}

// Updates the vertex data of the mesh. TODODODODODOD This needs considerable work.
public void updateBuffer()
{
this.mesh = this.opaquePass.GetComponent().mesh;
this.meshTrans = this.transparenPass.GetComponent().mesh;
this.mesh.Clear();
this.meshTrans.Clear();

// Nuke list gets populated during the transparent pass
this.voxelsToBeSorted.Clear();

renderPass(RenderFlags.OPAQUE_GEOMETRY);
renderPass(RenderFlags.TRANSPARENT_GEOMETRY);
}

void renderPass(RenderFlags RenderPass)
{

// Calculate vertex buffer size. 6 per face 6 faces per voxel = 36 vertices per voxel
// TO DO temp hard code on size, makes buffer maximum size
uint vertexBufferSize = 36 * (this.chunkSize * this.chunkSize * this.chunkSize);

List vertices = new List();
List uvs = new List();
List normals = new List();

int vertexOffset = 0;
int chunkOffset = -(int)this.chunkSize /2;

// This could be more optimal.

for (int x = 0; x < this.chunkSize; ++x)
{
for (int y = 0; y < this.chunkSize; ++y)
{
for (int z = 0; z < this.chunkSize; ++z) { // get voxel VoxelDat voxel = this.getVoxelAtPosition(new Vector3(x, y, z)); if (RenderFlags.OPAQUE_GEOMETRY == RenderPass) { if (voxel.voxel.hasTransparency) continue; } else { if (!voxel.voxel.hasTransparency) continue; } // Used to determine the vertex offset & whether we need to add to the sort list byte _offset = 0; // Front if ((voxel.flags & (uint)VoxelFlags.CULL_FRONT) == 0) { vertices.Add(new Vector3(x+ chunkOffset, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + chunkOffset)); uvs.Add(voxel.voxel.material[0].textureCoords[0]); uvs.Add(voxel.voxel.material[0].textureCoords[1]); uvs.Add(voxel.voxel.material[0].textureCoords[2]); uvs.Add(voxel.voxel.material[0].textureCoords[0]); uvs.Add(voxel.voxel.material[0].textureCoords[2]); uvs.Add(voxel.voxel.material[0].textureCoords[3]); normals.Add(Vector3.forward); normals.Add(Vector3.forward); normals.Add(Vector3.forward); normals.Add(Vector3.forward); normals.Add(Vector3.forward); normals.Add(Vector3.forward); _offset += 6; } // Top if ((voxel.flags & (uint)VoxelFlags.CULL_TOP) == 0) { vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + chunkOffset)); uvs.Add(voxel.voxel.material[4].textureCoords[0]); uvs.Add(voxel.voxel.material[4].textureCoords[1]); uvs.Add(voxel.voxel.material[4].textureCoords[2]); uvs.Add(voxel.voxel.material[4].textureCoords[0]); uvs.Add(voxel.voxel.material[4].textureCoords[2]); uvs.Add(voxel.voxel.material[4].textureCoords[3]); normals.Add(Vector3.up); normals.Add(Vector3.up); normals.Add(Vector3.up); normals.Add(Vector3.up); normals.Add(Vector3.up); normals.Add(Vector3.up); _offset += 6; } // Right if ((voxel.flags & (uint)VoxelFlags.CULL_RIGHT) == 0) { vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + 1 + chunkOffset)); uvs.Add(voxel.voxel.material[3].textureCoords[0]); uvs.Add(voxel.voxel.material[3].textureCoords[1]); uvs.Add(voxel.voxel.material[3].textureCoords[2]); uvs.Add(voxel.voxel.material[3].textureCoords[0]); uvs.Add(voxel.voxel.material[3].textureCoords[2]); uvs.Add(voxel.voxel.material[3].textureCoords[3]); normals.Add(Vector3.right); normals.Add(Vector3.right); normals.Add(Vector3.right); normals.Add(Vector3.right); normals.Add(Vector3.right); normals.Add(Vector3.right); _offset += 6; } // Back if ((voxel.flags & (uint)VoxelFlags.CULL_BACK) == 0) { vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + 1 + chunkOffset)); uvs.Add(voxel.voxel.material[1].textureCoords[0]); uvs.Add(voxel.voxel.material[1].textureCoords[1]); uvs.Add(voxel.voxel.material[1].textureCoords[2]); uvs.Add(voxel.voxel.material[1].textureCoords[0]); uvs.Add(voxel.voxel.material[1].textureCoords[2]); uvs.Add(voxel.voxel.material[1].textureCoords[3]); normals.Add(Vector3.back); normals.Add(Vector3.back); normals.Add(Vector3.back); normals.Add(Vector3.back); normals.Add(Vector3.back); normals.Add(Vector3.back); _offset += 6; } // Left if ((voxel.flags & (uint)VoxelFlags.CULL_LEFT) == 0) { vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset + 1, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + chunkOffset)); uvs.Add(voxel.voxel.material[2].textureCoords[0]); uvs.Add(voxel.voxel.material[2].textureCoords[1]); uvs.Add(voxel.voxel.material[2].textureCoords[2]); uvs.Add(voxel.voxel.material[2].textureCoords[0]); uvs.Add(voxel.voxel.material[2].textureCoords[2]); uvs.Add(voxel.voxel.material[2].textureCoords[3]); normals.Add(Vector3.left); normals.Add(Vector3.left); normals.Add(Vector3.left); normals.Add(Vector3.left); normals.Add(Vector3.left); normals.Add(Vector3.left); _offset += 6; } // Bottom if ((voxel.flags & (uint)VoxelFlags.CULL_BOTTOM) == 0) { vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset, y + chunkOffset, z + 1 + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + chunkOffset)); vertices.Add(new Vector3(x + chunkOffset + 1, y + chunkOffset, z + 1 + chunkOffset)); uvs.Add(voxel.voxel.material[5].textureCoords[0]); uvs.Add(voxel.voxel.material[5].textureCoords[1]); uvs.Add(voxel.voxel.material[5].textureCoords[2]); uvs.Add(voxel.voxel.material[5].textureCoords[0]); uvs.Add(voxel.voxel.material[5].textureCoords[2]); uvs.Add(voxel.voxel.material[5].textureCoords[3]); normals.Add(Vector3.down); normals.Add(Vector3.down); normals.Add(Vector3.down); normals.Add(Vector3.down); normals.Add(Vector3.down); normals.Add(Vector3.down); _offset += 6; } if (RenderPass == RenderFlags.TRANSPARENT_GEOMETRY) { if (_offset > 0) {
// push back voxel to be sorted.
this.voxelsToBeSorted.Add(voxel);
}
}

vertexOffset += _offset;

}
}
}

int[] triangles = new int[vertexOffset];
for (int i = 0; i < vertexOffset; ++i)
{
triangles[i] = i;
}
if (RenderPass == RenderFlags.OPAQUE_GEOMETRY)
{
this.mesh.vertices = vertices.ToArray();
this.mesh.uv = uvs.ToArray();
this.mesh.triangles = triangles;
this.mesh.normals = normals.ToArray();
//this._meshFilter.mesh = _mesh;
}
else
{
this.meshTrans.vertices = vertices.ToArray();
this.meshTrans.uv = uvs.ToArray();
this.meshTrans.normals = normals.ToArray();
this.meshTrans.triangles = triangles;
}
}

private Transform cameraTransform;

void OnRenderObject()
{
//this.cameraTransform = Camera.current.transform;
//sortTransparentGeometry();
//this.sortDirty = true;
}

int sortsPerCycle = 1;

// Re-sort indices for transparent geometry.
public void sortTransparentGeometry()
{

// TODO: per face sorting.
//

//testing, remove this
this.sortDirty = true;

this.meshTrans = this.transparenPass.GetComponent().mesh;
int[] triangles = this.meshTrans.triangles;

if (this.sortDirty) {

//bubble sort

for (int iteration = 0; iteration < sortsPerCycle; ++ iteration) {

// Get camera distance from origin.
float cameraDist = Vector3.Distance(Vector3.zero, this.mainCamera.transform.position);

Vector3 cameraPos = this.mainCamera.transform.position;

// Assume there in correct order
bool orderedCorrectly = true;

for (int i = 0; i < this.voxelsToBeSorted.Count-1; ++i) { // elements with the greates distance are moved to the beginning of the list //if (Mathf.Abs(this.voxelsToBeSorted[i].sortDistance - cameraDist) > Mathf.Abs(this.voxelsToBeSorted[i+1].sortDistance - cameraDist)) {
if (Vector3.Distance(this.voxelsToBeSorted[i].position,cameraPos) < Vector3.Distance(this.voxelsToBeSorted[i+1].position, cameraPos)) {
// Swap
VoxelDat temp = this.voxelsToBeSorted[i + 1];
this.voxelsToBeSorted[i + 1] = this.voxelsToBeSorted[i];
this.voxelsToBeSorted[i] = temp;
orderedCorrectly = false;

// flip indices, reorder indices.
//int[] tempTris = new int[36];

for (int p = 0; p < 36; ++p) {

int tempTri = triangles[(36 * i) + p];
triangles[(36 * i) + p] = triangles[(36 * (i + 1)) + p];
triangles[(36 * (i + 1)) + p] = tempTri;
}

}
}

if (orderedCorrectly) {
this.sortDirty = false;
}
else {
this.meshTrans.triangles = triangles;
}
}

}

}

public void setParent(VoxelMap Parent)
{
this.parent = Parent;
}
}

[System.Flags]
enum VoxelMapRenderFlags : uint {
RENDER_AIR = 0x1 << 0
}

// The voxel maps position can be deduced from the transform.
public class VoxelMap : MonoBehaviour {

public uint voxelMapDimensions = 512;
public uint voxelMapHeight = 64;

public uint chunkSize = 32;

public bool renderAir = false;

public List materials;

public Voxel defaultAirBlock;
public Voxel mantleLevel;
public Voxel soilLevel;
public Voxel grassLevel;
public List voxels;

// exposed in editor toggling toggles the whole map to be re-rendered.
public bool isDirty = false;
private bool recalculateFaces = false; // expensive

// Bitwise render flags, changing these marks the whole map as dirty and causes a re-render
private uint renderFlags = 0;
private uint previouseRenderFlags = 0;

// Get the render flags, return read only.
public uint RenderFlags {
get { return renderFlags; }
}

// Chunks, mesh for each chunk.
private List chunks = new List();
private uint totalChunks = 0;

// Create game objects for each mesh
private List chunkObjects = new List();

// Voxel 'prefabs'
private Dictionary<uint, Voxel> voxelMap = new Dictionary<uint, Voxel>();
private uint _voxelCount = 0;

// For handling textures
private VoxelTextureMap voxelTextureMap;

public VoxelTextureMap textureMap {
get { return this.voxelTextureMap; }
}

// Use this for initialization
void Start() {

// Init variables/ objects
this.voxelTextureMap = new VoxelTextureMap();

foreach(AtlasTexture tex in materials)
{
this.voxelTextureMap.addTexture(tex);
}

this.loadVoxel(this.defaultAirBlock);
this.loadVoxel(this.mantleLevel);
this.loadVoxel(this.soilLevel);
this.loadVoxel(this.grassLevel);

foreach (Voxel voxy in this.voxels)
{
this.loadVoxel(voxy);
}

// Todo, requires some guards here to mitigate silly values being entered above.

if (this.voxelMapDimensions > 0 && this.voxelMapHeight > 0){
this.totalChunks = (this.voxelMapHeight / this.chunkSize) * (this.voxelMapDimensions / this.chunkSize);
}

for (uint q = 0; q < (this.voxelMapHeight / this.chunkSize); ++q) {
for (uint i = 0; i < (this.voxelMapDimensions / this.chunkSize); ++i)
{
for (uint p = 0; p < (this.voxelMapDimensions / this.chunkSize); ++p)
{

VoxelChunk chunk = this.addChunk(new VoxelChunk(this.chunkSize, (uint)this.materials.Count));
chunk.position = new Vector3((i* this.chunkSize) ,
(q * this.chunkSize) ,
(p * this.chunkSize) );
chunk.init();
chunk.updateBuffer();
}
}
}

this.generateEnviroment();

}

public void generateEnviroment() {

uint mantleNoiseHeight = 2;

for (uint x = 0; x < this.voxelMapDimensions; ++x) {

for (uint z = 0; z < this.voxelMapDimensions; ++z) {
int yHeight = (int)(Random.value * mantleNoiseHeight);
//Mantle
for (uint y = 0; y <yHeight+1 && y < this.voxelMapHeight; ++y) {
this.setVoxel(new Vector3(x, y, z), this.mantleLevel);
}

// dirt
for (int y = yHeight + 1; y < yHeight +2 && y < this.voxelMapHeight; ++y) {
this.setVoxel(new Vector3(x, y, z), this.soilLevel);
}

// grass
/*for (int y = yHeight + 2; y < yHeight + 7 && y < this.voxelMapHeight; ++y) { this.setVoxel(new Vector3(x, y, z), this.grassLevel); }*/ } } } // Sets up the voxel and adds it to the map void loadVoxel(Voxel voxel) { //voxel.setTexture(this.voxelTextureMap.getTextureForID((uint)voxel.textureID)); voxel.setTexture(0,this.voxelTextureMap.getTextureForID((uint)voxel.textureIDFront)); voxel.setTexture(1, this.voxelTextureMap.getTextureForID((uint)voxel.textureIDBack)); voxel.setTexture(2, this.voxelTextureMap.getTextureForID((uint)voxel.textureIDLeft)); voxel.setTexture(3, this.voxelTextureMap.getTextureForID((uint)voxel.textureIDRight)); voxel.setTexture(4, this.voxelTextureMap.getTextureForID((uint)voxel.textureIDUp)); voxel.setTexture(5, this.voxelTextureMap.getTextureForID((uint)voxel.textureIDDown)); this.voxelMap.Add(this._voxelCount++,voxel); } // return the voxel instance assiociated with a given ID public Voxel getVoxel(uint ID) { return this.voxelMap[ID]; } // Get the top most(y) voxel at a given position along x,z axis's (that isn't an air block-> unless there all air O.O)
public VoxelDat getTopPosition(Vector2 Position) {

Vector3 _position = new Vector3(Position.x, 0, Position.y);
VoxelDat _voxel = this.getVoxelAtPosition(_position);

// Keep previous avoid additional get.
VoxelDat _previous = _voxel;

while ((_voxel.flags & (uint)VoxelFlags.AIR) == 0 && _position.y <= this.voxelMapHeight) { _position.y++; _previous = _voxel; _voxel = this.getVoxelAtPosition(_position); } return _previous; } // Set the voxel at a given position using an index into the map of voxels public void setVoxel(Vector3 Position, uint ID) { if (ID > this.voxelMap.Count) {
Debug.LogError("Set Voxel ID out of range");
return;
}

setVoxel(Position, this.voxelMap[ID]);
}

// Sets the voxel at the given position with the voxel passed in
public void setVoxel(Vector3 Position, Voxel voxel) {

// Work out which chunk the voxel resides in.
uint chunkX = (uint)(Position.x / (float)this.chunkSize);
uint chunkZ = (uint)(Position.z / (float)this.chunkSize);
uint chunkY = (uint)(Position.y / (float)this.chunkSize);

// Optimise precalculate this
uint _chunkDimensionXZ = this.voxelMapDimensions / this.chunkSize;
uint _chunkDimensionY = this.voxelMapHeight / this.chunkSize;

//int pos = (chunkZ * (int)this.chunkSize) + (chunkY * (int)this.chunkSize) + (chunkX);
uint pos = (chunkZ) + ( (chunkX* _chunkDimensionXZ)+((_chunkDimensionXZ * _chunkDimensionXZ) * chunkY));

// Normalise the position to make relative to parent chunk.
Vector3 normalisedPosition = Position - new Vector3(chunkX * this.chunkSize, chunkY * this.chunkSize, chunkZ * this.chunkSize);

this.chunks[(int)pos].setVoxel(normalisedPosition, voxel);

}

// returns a reference, get triggers the buffer to be marked as dirty?
public VoxelDat getVoxelAtPosition(Vector3 Position, bool dirtyBuffer = false)
{
// Work out which chunk the voxel resides in, loses float precision however should be caught by out of range guard, regardless.
uint chunkX = (uint)( Position.x / (float)this.chunkSize);
uint chunkZ = (uint)(Position.z / (float)this.chunkSize);
uint chunkY = (uint)(Position.y / (float)this.chunkSize);

// Optimise precalculate this
uint _chunkDimensionXZ = this.voxelMapDimensions / this.chunkSize;
uint _chunkDimensionY = this.voxelMapHeight / this.chunkSize;

//int pos = (chunkZ * (int)this.chunkSize) + (chunkY * (int)this.chunkSize) + (chunkX);
uint pos = (chunkZ) + ((chunkX * _chunkDimensionXZ) + ((_chunkDimensionXZ * _chunkDimensionXZ) * chunkY));

// Normalise the position to make relative to parent chunk.
Vector3 normalisedPosition = Position - new Vector3(chunkX * this.chunkSize, chunkY * this.chunkSize, chunkZ * this.chunkSize);

bool outOfRange = false;

if (Position.x < 0 || Position.y < 0 || Position.z < 0 || Position.x >= this.voxelMapDimensions || Position.y >= this.voxelMapHeight || Position.z >= this.voxelMapDimensions) {
outOfRange = true;
}

if (pos > this.chunks.Count-1 || outOfRange || pos < 0) { VoxelDat transparent = new VoxelDat(); transparent.voxel = new Voxel(); transparent.voxel.hasTransparency = true; transparent.flags |= (uint)VoxelFlags.AIR; return transparent; } // Set the buffer dirty if (dirtyBuffer) this.chunks[(int)pos].setDirty(dirtyBuffer); return this.chunks[(int)pos].getVoxelAtPosition(normalisedPosition); } // Adds a chunk to the voxel map VoxelChunk addChunk(VoxelChunk Chunk) { Chunk.setParent(this); this.chunks.Add(Chunk); return Chunk; } // Update is called once per frame void Update() { this.updateRenderFlags(); foreach (VoxelChunk chunk in this.chunks) { // if dirty, make chunks dirty if (this.isDirty) { chunk.setDirty(true, this.recalculateFaces); } chunk.update(); chunk.sortTransparentGeometry(); } // Perform block update this.performBlockUpdates(); // Always make render clean at end of update. this.isDirty = false; this.recalculateFaces = false; } // Block update variables int currentUpdateChunk = 0; static int chunkUpdatesPerCycle = 1; // should NOT be zero or updates will not happen. float lastUpdateElapsed = 0; void performBlockUpdates () { lastUpdateElapsed += Time.deltaTime; if (lastUpdateElapsed > 1) {
lastUpdateElapsed = 0;
for (int i = this.currentUpdateChunk; i < this.chunks.Count && i < this.currentUpdateChunk + chunkUpdatesPerCycle; ++i) { this.chunks[i].performBlockUpdates(); this.currentUpdateChunk++; } if (currentUpdateChunk >= this.chunks.Count) {
currentUpdateChunk = 0;
}
}
}

// Updates the render flags
void updateRenderFlags() {
// possibly replace for custom editor
if (this.renderAir) {
this.renderFlags |= (uint)VoxelMapRenderFlags.RENDER_AIR;
}
else {
this.renderFlags &= ~(uint)VoxelMapRenderFlags.RENDER_AIR;
}

if (this.renderFlags != this.previouseRenderFlags) {
this.isDirty = true;
this.recalculateFaces = true;
this.previouseRenderFlags = this.renderFlags;
}

}

}

Leave a Reply