summaryrefslogtreecommitdiff
path: root/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Graphs/Navmesh/Voxels/VoxelContour.cs
blob: 39b49dba132b02d133ff3f65af0edbcad3b95587 (plain)
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
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
using Unity.Burst;
using Pathfinding.Util;

namespace Pathfinding.Graphs.Navmesh.Voxelization.Burst {
	/// <summary>VoxelContour used for recast graphs.</summary>
	public struct VoxelContour {
		public int nverts;

		/// <summary>Vertex coordinates, each vertex contains 4 components.</summary>
		public int vertexStartIndex;

		/// <summary>Region ID of the contour</summary>
		public int reg;

		/// <summary>Area ID of the contour.</summary>
		public int area;
	}

	[BurstCompile(CompileSynchronously = true)]
	public struct JobBuildContours : IJob {
		public CompactVoxelField field;
		public float maxError;
		public float maxEdgeLength;
		public int buildFlags;
		public float cellSize;
		public NativeList<VoxelContour> outputContours;
		public NativeList<int> outputVerts;

		public void Execute () {
			outputContours.Clear();
			outputVerts.Clear();

			int w = field.width;
			int d = field.depth;
			int wd = w*d;

			const ushort BorderReg = VoxelUtilityBurst.BorderReg;

			// NOTE: This array may contain uninitialized data, but since we explicitly set all data in it before we use it, it's OK.
			var flags = new NativeArray<ushort>(field.spans.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory);

			// Mark boundaries. (@?)
			for (int z = 0; z < wd; z += field.width) {
				for (int x = 0; x < field.width; x++) {
					CompactVoxelCell c = field.cells[x+z];

					for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) {
						ushort res = 0;
						CompactVoxelSpan s = field.spans[i];

						if (s.reg == 0 || (s.reg & BorderReg) == BorderReg) {
							flags[i] = 0;
							continue;
						}

						for (int dir = 0; dir < 4; dir++) {
							int r = 0;

							if (s.GetConnection(dir) != CompactVoxelField.NotConnected) {
								int ni = field.cells[field.GetNeighbourIndex(x+z, dir)].index + s.GetConnection(dir);
								r = field.spans[ni].reg;
							}

							//@TODO - Why isn't this inside the previous IF
							if (r == s.reg) {
								res |= (ushort)(1 << dir);
							}
						}

						//Inverse, mark non connected edges.
						flags[i] = (ushort)(res ^ 0xf);
					}
				}
			}


			NativeList<int> verts = new NativeList<int>(256, Allocator.Temp);
			NativeList<int> simplified = new NativeList<int>(64, Allocator.Temp);

			for (int z = 0; z < wd; z += field.width) {
				for (int x = 0; x < field.width; x++) {
					CompactVoxelCell c = field.cells[x+z];

					for (int i = c.index, ci = c.index+c.count; i < ci; i++) {
						if (flags[i] == 0 || flags[i] == 0xf) {
							flags[i] = 0;
							continue;
						}

						int reg = field.spans[i].reg;

						if (reg == 0 || (reg & BorderReg) == BorderReg) {
							continue;
						}

						int area = field.areaTypes[i];

						verts.Clear();
						simplified.Clear();

						WalkContour(x, z, i, flags, verts);

						SimplifyContour(verts, simplified, maxError, buildFlags);
						RemoveDegenerateSegments(simplified);

						VoxelContour contour = new VoxelContour {
							vertexStartIndex = outputVerts.Length,
							nverts = simplified.Length/4,
							reg = reg,
							area = area,
						};

						outputVerts.AddRange(simplified.AsArray());

						outputContours.Add(contour);
					}
				}
			}

			verts.Dispose();
			simplified.Dispose();



			// Check and merge droppings.
			// Sometimes the previous algorithms can fail and create several outputContours
			// per area. This pass will try to merge the holes into the main region.
			for (int i = 0; i < outputContours.Length; i++) {
				VoxelContour cont = outputContours[i];
				// Check if the contour is would backwards.
				var outputVertsArr = outputVerts.AsArray();
				if (CalcAreaOfPolygon2D(outputVertsArr, cont.vertexStartIndex, cont.nverts) < 0) {
					// Find another contour which has the same region ID.
					int mergeIdx = -1;
					for (int j = 0; j < outputContours.Length; j++) {
						if (i == j) continue;
						if (outputContours[j].nverts > 0 && outputContours[j].reg == cont.reg) {
							// Make sure the polygon is correctly oriented.
							if (CalcAreaOfPolygon2D(outputVertsArr, outputContours[j].vertexStartIndex, outputContours[j].nverts) > 0) {
								mergeIdx = j;
								break;
							}
						}
					}
					if (mergeIdx == -1) {
						// Debug.LogError("rcBuildContours: Could not find merge target for bad contour "+i+".");
					} else {
						// Debugging
						// Debug.LogWarning ("Fixing contour");

						VoxelContour mcont = outputContours[mergeIdx];
						// Merge by closest points.
						GetClosestIndices(outputVertsArr, mcont.vertexStartIndex, mcont.nverts, cont.vertexStartIndex, cont.nverts, out var ia, out var ib);

						if (ia == -1 || ib == -1) {
							// Debug.LogWarning("rcBuildContours: Failed to find merge points for "+i+" and "+mergeIdx+".");
							continue;
						}


						if (!MergeContours(outputVerts, ref mcont, ref cont, ia, ib)) {
							//Debug.LogWarning("rcBuildContours: Failed to merge contours "+i+" and "+mergeIdx+".");
							continue;
						}

						outputContours[mergeIdx] = mcont;
						outputContours[i] = cont;
					}
				}
			}
		}

		void GetClosestIndices (NativeArray<int> verts, int vertexStartIndexA, int nvertsa,
								int vertexStartIndexB, int nvertsb,
								out int ia, out int ib) {
			int closestDist = 0xfffffff;

			ia = -1;
			ib = -1;
			for (int i = 0; i < nvertsa; i++) {
				//in is a keyword in C#, so I can't use that as a variable name
				int in2 = (i+1) % nvertsa;
				int ip = (i+nvertsa-1) % nvertsa;
				int va = vertexStartIndexA + i*4;
				int van = vertexStartIndexA + in2*4;
				int vap = vertexStartIndexA + ip*4;

				for (int j = 0; j < nvertsb; ++j) {
					int vb = vertexStartIndexB + j*4;
					// vb must be "infront" of va.
					if (Ileft(verts, vap, va, vb) && Ileft(verts, va, van, vb)) {
						int dx = verts[vb+0] - verts[va+0];
						int dz = (verts[vb+2]/field.width) - (verts[va+2]/field.width);
						int d = dx*dx + dz*dz;
						if (d < closestDist) {
							ia = i;
							ib = j;
							closestDist = d;
						}
					}
				}
			}
		}

		public static bool MergeContours (NativeList<int> verts, ref VoxelContour ca, ref VoxelContour cb, int ia, int ib) {
			// Note: this will essentially leave junk data in the verts array where the contours were previously.
			// This shouldn't be a big problem because MergeContours is normally not called for that many contours (usually none).
			int nv = 0;
			var startIndex = verts.Length;

			// Copy contour A.
			for (int i = 0; i <= ca.nverts; i++) {
				int src = ca.vertexStartIndex + ((ia+i) % ca.nverts)*4;
				verts.Add(verts[src+0]);
				verts.Add(verts[src+1]);
				verts.Add(verts[src+2]);
				verts.Add(verts[src+3]);
				nv++;
			}

			// Copy contour B
			for (int i = 0; i <= cb.nverts; i++) {
				int src = cb.vertexStartIndex + ((ib+i) % cb.nverts)*4;
				verts.Add(verts[src+0]);
				verts.Add(verts[src+1]);
				verts.Add(verts[src+2]);
				verts.Add(verts[src+3]);
				nv++;
			}

			ca.vertexStartIndex = startIndex;
			ca.nverts = nv;

			cb.vertexStartIndex = 0;
			cb.nverts = 0;

			return true;
		}

		public void SimplifyContour (NativeList<int> verts, NativeList<int> simplified, float maxError, int buildFlags) {
			// Add initial points.
			bool hasConnections = false;

			for (int i = 0; i < verts.Length; i += 4) {
				if ((verts[i+3] & VoxelUtilityBurst.ContourRegMask) != 0) {
					hasConnections = true;
					break;
				}
			}

			if (hasConnections) {
				// The contour has some portals to other regions.
				// Add a new point to every location where the region changes.
				for (int i = 0, ni = verts.Length/4; i < ni; i++) {
					int ii = (i+1) % ni;
					bool differentRegs = (verts[i*4+3] & VoxelUtilityBurst.ContourRegMask) != (verts[ii*4+3] & VoxelUtilityBurst.ContourRegMask);
					bool areaBorders = (verts[i*4+3] & VoxelUtilityBurst.RC_AREA_BORDER) != (verts[ii*4+3] & VoxelUtilityBurst.RC_AREA_BORDER);

					if (differentRegs || areaBorders) {
						simplified.Add(verts[i*4+0]);
						simplified.Add(verts[i*4+1]);
						simplified.Add(verts[i*4+2]);
						simplified.Add(i);
					}
				}
			}


			if (simplified.Length == 0) {
				// If there is no connections at all,
				// create some initial points for the simplification process.
				// Find lower-left and upper-right vertices of the contour.
				int llx = verts[0];
				int lly = verts[1];
				int llz = verts[2];
				int lli = 0;
				int urx = verts[0];
				int ury = verts[1];
				int urz = verts[2];
				int uri = 0;

				for (int i = 0; i < verts.Length; i += 4) {
					int x = verts[i+0];
					int y = verts[i+1];
					int z = verts[i+2];
					if (x < llx || (x == llx && z < llz)) {
						llx = x;
						lly = y;
						llz = z;
						lli = i/4;
					}
					if (x > urx || (x == urx && z > urz)) {
						urx = x;
						ury = y;
						urz = z;
						uri = i/4;
					}
				}

				simplified.Add(llx);
				simplified.Add(lly);
				simplified.Add(llz);
				simplified.Add(lli);

				simplified.Add(urx);
				simplified.Add(ury);
				simplified.Add(urz);
				simplified.Add(uri);
			}

			// Add points until all raw points are within
			// error tolerance to the simplified shape.
			// This uses the Douglas-Peucker algorithm.
			int pn = verts.Length/4;

			//Use the max squared error instead
			maxError *= maxError;

			for (int i = 0; i < simplified.Length/4;) {
				int ii = (i+1) % (simplified.Length/4);

				int ax = simplified[i*4+0];
				int ay = simplified[i*4+1];
				int az = simplified[i*4+2];
				int ai = simplified[i*4+3];

				int bx = simplified[ii*4+0];
				int by = simplified[ii*4+1];
				int bz = simplified[ii*4+2];
				int bi = simplified[ii*4+3];

				// Find maximum deviation from the segment.
				float maxd = 0;
				int maxi = -1;
				int ci, cinc, endi;

				// Traverse the segment in lexilogical order so that the
				// max deviation is calculated similarly when traversing
				// opposite segments.
				if (bx > ax || (bx == ax && bz > az)) {
					cinc = 1;
					ci = (ai+cinc) % pn;
					endi = bi;
				} else {
					cinc = pn-1;
					ci = (bi+cinc) % pn;
					endi = ai;
					Memory.Swap(ref ax, ref bx);
					Memory.Swap(ref az, ref bz);
				}

				// Tessellate only outer edges or edges between areas.
				if ((verts[ci*4+3] & VoxelUtilityBurst.ContourRegMask) == 0 ||
					(verts[ci*4+3] & VoxelUtilityBurst.RC_AREA_BORDER) == VoxelUtilityBurst.RC_AREA_BORDER) {
					while (ci != endi) {
						float d2 = VectorMath.SqrDistancePointSegmentApproximate(verts[ci*4+0], verts[ci*4+2]/field.width, ax, az/field.width, bx, bz/field.width);

						if (d2 > maxd) {
							maxd = d2;
							maxi = ci;
						}
						ci = (ci+cinc) % pn;
					}
				}

				// If the max deviation is larger than accepted error,
				// add new point, else continue to next segment.
				if (maxi != -1 && maxd > maxError) {
					// Add space for the new point.
					simplified.ResizeUninitialized(simplified.Length + 4);

					// Move all points after this one, to leave space to insert the new point
					simplified.AsUnsafeSpan().Move((i+1)*4, (i+2)*4, simplified.Length-(i+2)*4);

					// Add the point.
					simplified[(i+1)*4+0] = verts[maxi*4+0];
					simplified[(i+1)*4+1] = verts[maxi*4+1];
					simplified[(i+1)*4+2] = verts[maxi*4+2];
					simplified[(i+1)*4+3] = maxi;
				} else {
					i++;
				}
			}

			// Split too long edges

			float maxEdgeLen = maxEdgeLength / cellSize;

			if (maxEdgeLen > 0 && (buildFlags & (VoxelUtilityBurst.RC_CONTOUR_TESS_WALL_EDGES|VoxelUtilityBurst.RC_CONTOUR_TESS_AREA_EDGES|VoxelUtilityBurst.RC_CONTOUR_TESS_TILE_EDGES)) != 0) {
				for (int i = 0; i < simplified.Length/4;) {
					if (simplified.Length/4 > 200) {
						break;
					}

					int ii = (i+1) % (simplified.Length/4);

					int ax = simplified[i*4+0];
					int az = simplified[i*4+2];
					int ai = simplified[i*4+3];

					int bx = simplified[ii*4+0];
					int bz = simplified[ii*4+2];
					int bi = simplified[ii*4+3];

					// Find maximum deviation from the segment.
					int maxi = -1;
					int ci = (ai+1) % pn;

					// Tessellate only outer edges or edges between areas.
					bool tess = false;

					// Wall edges.
					if ((buildFlags & VoxelUtilityBurst.RC_CONTOUR_TESS_WALL_EDGES) != 0 && (verts[ci*4+3] & VoxelUtilityBurst.ContourRegMask) == 0)
						tess = true;

					// Edges between areas.
					if ((buildFlags & VoxelUtilityBurst.RC_CONTOUR_TESS_AREA_EDGES) != 0 && (verts[ci*4+3] & VoxelUtilityBurst.RC_AREA_BORDER) == VoxelUtilityBurst.RC_AREA_BORDER)
						tess = true;

					// Border of tile
					if ((buildFlags & VoxelUtilityBurst.RC_CONTOUR_TESS_TILE_EDGES) != 0 && (verts[ci*4+3] & VoxelUtilityBurst.BorderReg) == VoxelUtilityBurst.BorderReg)
						tess = true;

					if (tess) {
						int dx = bx - ax;
						int dz = (bz/field.width) - (az/field.width);
						if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen) {
							// Round based on the segments in lexilogical order so that the
							// max tesselation is consistent regardles in which direction
							// segments are traversed.
							int n = bi < ai ? (bi+pn - ai) : (bi - ai);
							if (n > 1) {
								if (bx > ax || (bx == ax && bz > az)) {
									maxi = (ai + n/2) % pn;
								} else {
									maxi = (ai + (n+1)/2) % pn;
								}
							}
						}
					}

					// If the max deviation is larger than accepted error,
					// add new point, else continue to next segment.
					if (maxi != -1) {
						// Add space for the new point.
						//simplified.resize(simplified.size()+4);
						simplified.Resize(simplified.Length + 4, NativeArrayOptions.UninitializedMemory);

						simplified.AsUnsafeSpan().Move((i+1)*4, (i+2)*4, simplified.Length-(i+2)*4);

						// Add the point.
						simplified[(i+1)*4+0] = verts[maxi*4+0];
						simplified[(i+1)*4+1] = verts[maxi*4+1];
						simplified[(i+1)*4+2] = verts[maxi*4+2];
						simplified[(i+1)*4+3] = maxi;
					} else {
						++i;
					}
				}
			}

			for (int i = 0; i < simplified.Length/4; i++) {
				// The edge vertex flag is take from the current raw point,
				// and the neighbour region is take from the next raw point.
				int ai = (simplified[i*4+3]+1) % pn;
				int bi = simplified[i*4+3];
				simplified[i*4+3] = (verts[ai*4+3] & VoxelUtilityBurst.ContourRegMask) | (verts[bi*4+3] & VoxelUtilityBurst.RC_BORDER_VERTEX);
			}
		}

		public void WalkContour (int x, int z, int i, NativeArray<ushort> flags, NativeList<int> verts) {
			// Choose the first non-connected edge
			int dir = 0;

			while ((flags[i] & (ushort)(1 << dir)) == 0) {
				dir++;
			}

			int startDir = dir;
			int startI = i;

			int area = field.areaTypes[i];

			int iter = 0;

			while (iter++ < 40000) {
				// Are we facing a region edge
				if ((flags[i] & (ushort)(1 << dir)) != 0) {
					// Choose the edge corner
					bool isBorderVertex = false;
					bool isAreaBorder = false;

					int px = x;
					int py = GetCornerHeight(x, z, i, dir, ref isBorderVertex);
					int pz = z;

					// Offset the vertex to land on the corner of the span.
					// The resulting coordinates have an implicit 1/2 voxel offset because all corners
					// are in the middle between two adjacent integer voxel coordinates.
					switch (dir) {
					case 0: pz += field.width; break;
					case 1: px++; pz += field.width; break;
					case 2: px++; break;
					}

					int r = 0;
					CompactVoxelSpan s = field.spans[i];

					if (s.GetConnection(dir) != CompactVoxelField.NotConnected) {
						int ni = (int)field.cells[field.GetNeighbourIndex(x+z, dir)].index + s.GetConnection(dir);
						r = (int)field.spans[ni].reg;

						if (area != field.areaTypes[ni]) {
							isAreaBorder = true;
						}
					}

					if (isBorderVertex) {
						r |= VoxelUtilityBurst.RC_BORDER_VERTEX;
					}
					if (isAreaBorder) {
						r |= VoxelUtilityBurst.RC_AREA_BORDER;
					}

					verts.Add(px);
					verts.Add(py);
					verts.Add(pz);
					verts.Add(r);

					flags[i] = (ushort)(flags[i] & ~(1 << dir)); // Remove visited edges

					// & 0x3 is the same as % 4 (for positive numbers)
					dir = (dir+1) & 0x3;  // Rotate CW
				} else {
					int ni = -1;
					int nx = x + VoxelUtilityBurst.DX[dir];
					int nz = z + VoxelUtilityBurst.DZ[dir]*field.width;

					CompactVoxelSpan s = field.spans[i];

					if (s.GetConnection(dir) != CompactVoxelField.NotConnected) {
						CompactVoxelCell nc = field.cells[nx+nz];
						ni = (int)nc.index + s.GetConnection(dir);
					}

					if (ni == -1) {
						Debug.LogWarning("Degenerate triangles might have been generated.\n" +
							"Usually this is not a problem, but if you have a static level, try to modify the graph settings slightly to avoid this edge case.");
						return;
					}
					x = nx;
					z = nz;
					i = ni;

					// & 0x3 is the same as % 4 (modulo 4)
					dir = (dir+3) & 0x3; // Rotate CCW
				}

				if (startI == i && startDir == dir) {
					break;
				}
			}
		}

		public int GetCornerHeight (int x, int z, int i, int dir, ref bool isBorderVertex) {
			CompactVoxelSpan s = field.spans[i];

			int cornerHeight = (int)s.y;

			// dir + 1 step in the clockwise direction
			int dirp = (dir+1) & 0x3;

			unsafe {
				// We need a small buffer to hold regions for each axis aligned neighbour.
				// This requires unsafe, though. In future C# versions we can use Span<T>.
				//
				//        dir
				//      X---->
				// dirp |
				//      v
				//
				//
				// The regs array will contain the regions for the following spans,
				// where the 0th span is the current span.
				// 'x' signifies the position of the corner we are interested in.
				// This is the shared vertex corner the four spans.
				// It is conceptually at the current span's position + 0.5*dir + 0.5*dirp
				//
				//
				//      0 --------- 1   -> dir
				//      |           |
				//      |     x     |
				//      |           |
				//      3 --------- 2
				//
				//      | dirp
				//      v
				//
				var regs = stackalloc uint[] { 0, 0, 0, 0 };

				regs[0] = (uint)field.spans[i].reg | ((uint)field.areaTypes[i] << 16);

				if (s.GetConnection(dir) != CompactVoxelField.NotConnected) {
					int neighbourCell = field.GetNeighbourIndex(x+z, dir);
					int ni = (int)field.cells[neighbourCell].index + s.GetConnection(dir);

					CompactVoxelSpan ns = field.spans[ni];

					cornerHeight = System.Math.Max(cornerHeight, (int)ns.y);
					regs[1] = (uint)ns.reg | ((uint)field.areaTypes[ni] << 16);

					if (ns.GetConnection(dirp) != CompactVoxelField.NotConnected) {
						int neighbourCell2 = field.GetNeighbourIndex(neighbourCell, dirp);
						int ni2 = (int)field.cells[neighbourCell2].index + ns.GetConnection(dirp);

						CompactVoxelSpan ns2 = field.spans[ni2];

						cornerHeight = System.Math.Max(cornerHeight, (int)ns2.y);
						regs[2] = (uint)ns2.reg | ((uint)field.areaTypes[ni2] << 16);
					}
				}

				if (s.GetConnection(dirp) != CompactVoxelField.NotConnected) {
					int neighbourCell = field.GetNeighbourIndex(x+z, dirp);
					int ni = (int)field.cells[neighbourCell].index + s.GetConnection(dirp);

					CompactVoxelSpan ns = field.spans[ni];

					cornerHeight = System.Math.Max(cornerHeight, (int)ns.y);
					regs[3] = (uint)ns.reg | ((uint)field.areaTypes[ni] << 16);

					if (ns.GetConnection(dir) != CompactVoxelField.NotConnected) {
						int neighbourCell2 = field.GetNeighbourIndex(neighbourCell, dir);
						int ni2 = (int)field.cells[neighbourCell2].index + ns.GetConnection(dir);

						CompactVoxelSpan ns2 = field.spans[ni2];

						cornerHeight = System.Math.Max(cornerHeight, (int)ns2.y);
						regs[2] = (uint)ns2.reg | ((uint)field.areaTypes[ni2] << 16);
					}
				}

				// Zeroes show up when there are no connections to some spans. E.g. if the current span is on a ledge.
				bool noZeros = regs[0] != 0 && regs[1] != 0 && regs[2] != 0 && regs[3] != 0;

				// Check if the vertex is special edge vertex, these vertices will be removed later.
				for (int j = 0; j < 4; ++j) {
					int a = j;
					int b = (j+1) & 0x3;
					int c = (j+2) & 0x3;
					int d = (j+3) & 0x3;

					// The vertex is a border vertex there are two same exterior cells in a row,
					// followed by two interior cells and none of the regions are out of bounds.
					bool twoSameExts = (regs[a] & regs[b] & VoxelUtilityBurst.BorderReg) != 0 && regs[a] == regs[b];
					bool twoInts = ((regs[c] | regs[d]) & VoxelUtilityBurst.BorderReg) == 0;
					bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
					if (twoSameExts && twoInts && intsSameArea && noZeros) {
						isBorderVertex = true;
						break;
					}
				}
			}

			return cornerHeight;
		}

		static void RemoveRange (NativeList<int> arr, int index, int count) {
			for (int i = index; i < arr.Length - count; i++) {
				arr[i] = arr[i+count];
			}
			arr.Resize(arr.Length - count, NativeArrayOptions.UninitializedMemory);
		}

		static void RemoveDegenerateSegments (NativeList<int> simplified) {
			// Remove adjacent vertices which are equal on xz-plane,
			// or else the triangulator will get confused
			for (int i = 0; i < simplified.Length/4; i++) {
				int ni = i+1;
				if (ni >= (simplified.Length/4))
					ni = 0;

				if (simplified[i*4+0] == simplified[ni*4+0] &&
					simplified[i*4+2] == simplified[ni*4+2]) {
					// Degenerate segment, remove.
					RemoveRange(simplified, i, 4);
				}
			}
		}

		int CalcAreaOfPolygon2D (NativeArray<int> verts, int vertexStartIndex, int nverts) {
			int area = 0;

			for (int i = 0, j = nverts-1; i < nverts; j = i++) {
				int vi = vertexStartIndex + i*4;
				int vj = vertexStartIndex + j*4;
				area += verts[vi+0] * (verts[vj+2]/field.width) - verts[vj+0] * (verts[vi+2]/field.width);
			}

			return (area+1) / 2;
		}

		static bool Ileft (NativeArray<int> verts, int a, int b, int c) {
			return (verts[b+0] - verts[a+0]) * (verts[c+2] - verts[a+2]) - (verts[c+0] - verts[a+0]) * (verts[b+2] - verts[a+2]) <= 0;
		}
	}
}