-
Notifications
You must be signed in to change notification settings - Fork 32
/
Cell.cs
739 lines (604 loc) · 24.5 KB
/
Cell.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using Ray = UnityEngine.Ray;
using Transform = UnityEngine.Transform;
using Vector3 = UnityEngine.Vector3;
namespace Kethane.GeodesicGrid
{
public struct Cell : IEquatable<Cell>
{
private readonly uint index;
public Cell(uint index)
{
this.index = index;
}
private Cell(uint subindex, int level) : this(subindex + CountAtLevel(level)) { }
public uint Index
{
get { return index; }
}
public int Level
{
get { return (IntMath.LogBase2((Math.Max(2, index) - 2) / 5) + 1) / 2; }
}
public bool IsPentagon
{
get { return index < 12; }
}
#region Cache control
public static void ClearCache()
{
neighborCache.Clear();
positionCache.Clear();
}
#endregion
#region Enumeration
public static IEnumerable<Cell> AtLevel(int level)
{
var count = CountAtLevel(level);
for (uint i = 0; i < count; i++)
{
yield return new Cell(i);
}
}
public static uint CountAtLevel(int level)
{
return 10 * (1u << (level << 1)) + 2; // 10 * 4^n + 2
}
#endregion
#region Position
private static readonly List<Vector3[]> positionCache = new List<Vector3[]>();
public Vector3 Position
{
get
{
if (index == 0)
{
return new Vector3(0, 1, 0);
}
else if (index == 1)
{
return new Vector3(0, -1, 0);
}
else if (IsPentagon)
{
var lat = Math.Atan(0.5);
var lon = index * Math.PI / 5;
if (index % 2 != 0)
{
lat = -lat;
}
return new Vector3((float)(Math.Cos(lat) * Math.Cos(lon)), (float)Math.Sin(lat), (float)(Math.Cos(lat) * Math.Sin(lon)));
}
else
{
var thisLevel = this.Level;
for (var i = positionCache.Count; i < thisLevel; i++)
{
var cache = new Vector3[30 << (2 * i)];
var count = CountAtLevel(i);
for (uint j = 0; j < cache.Length; j++)
{
var cell = new Cell(count + j);
cache[j] = (cell.GetParent().Position + cell.getSecondParent().Position).normalized;
}
positionCache.Add(cache);
}
return positionCache[thisLevel - 1][this.subindex];
}
}
}
#endregion
#region Raycast
public static Cell? Raycast(Ray ray, int level, BoundsMap bounds, Func<Cell, float> heightAt, Transform gridTransform = null)
{
var hit = Triangle.Raycast(ray, level, bounds, heightAt, gridTransform);
if (!hit.HasValue) { return null; }
var barycentric = hit.Value.BarycentricCoordinate;
var triangle = hit.Value.Triangle;
if ((barycentric.x >= barycentric.y) && (barycentric.x >= barycentric.z))
{
return triangle.GetVertices(level).ElementAt(0);
}
else if ((barycentric.y >= barycentric.x) && (barycentric.y >= barycentric.z))
{
return triangle.GetVertices(level).ElementAt(1);
}
else
{
return triangle.GetVertices(level).ElementAt(2);
}
}
public IEnumerable<Vector3> GetVertices(int level)
{
var position = this.Position;
return this.GetNeighbors(level).Select(c => c.Position).AdjacentPairs().Select(p => (position + p.First + p.Second).normalized);
}
public IEnumerable<Vector3> GetVertices(int level, Func<Cell, float> heightAt)
{
var position = this.Position;
var height = heightAt(this);
foreach (var pair in this.GetNeighbors(level).AdjacentPairs())
{
yield return (position + pair.First.Position + pair.Second.Position).normalized * (height + heightAt(pair.First) + heightAt(pair.Second)) / 3;
}
}
#endregion
#region Triangulation
public struct Triangle
{
private enum FaceDirection
{
Up = 0,
Down = 1,
}
private readonly uint index;
public uint Index
{
get { return this.index; }
}
private Triangle(Cell cell, FaceDirection direction)
{
if (cell.Index < 2) { throw new ArgumentException("Cannot root a triangle at a polar cell"); }
this.index = (cell.Index - 2) * 2 + (uint)direction;
}
private Triangle(uint index)
{
this.index = index;
}
private Cell getRoot()
{
return new Cell(2 + this.index / 2);
}
private FaceDirection getDirection()
{
return (FaceDirection)(this.index % 2);
}
public static uint CountAtLevel(int level)
{
return (Cell.CountAtLevel(level) - 2) * 2;
}
public static IEnumerable<Triangle> AtLevel(int level)
{
for (uint i = 0; i < CountAtLevel(level); i++)
{
yield return new Triangle(i);
}
}
public Triangle GetParent(int level)
{
var cell = this.getRoot();
while (level < cell.Level)
{
cell = cell.GetParent();
}
return new Triangle(cell, this.getDirection());
}
public IEnumerable<Triangle> GetChildren(int level)
{
var root = this.getRoot();
if (level <= root.Level) { throw new ArgumentException("Cannot find triangle children at level index not higher than the root cell"); }
var dir = this.getDirection();
yield return this;
yield return new Triangle(root.getNeighbor(ChildType.Straight, level), dir);
var cell = root.getNeighbor(dir == FaceDirection.Down ? ChildType.Down : ChildType.Up, level);
yield return new Triangle(cell, FaceDirection.Down);
yield return new Triangle(cell, FaceDirection.Up);
}
public IEnumerable<Cell> GetVertices(int level)
{
var root = this.getRoot();
if (level < root.Level) { throw new ArgumentException("Cannot find triangle vertices at a level lower than the root cell"); }
yield return root;
if (this.getDirection() == FaceDirection.Up)
{
yield return root.getNeighbor(ChildType.Up, level);
yield return root.getNeighbor(ChildType.Straight, level);
}
else
{
yield return root.getNeighbor(ChildType.Straight, level);
yield return root.getNeighbor(ChildType.Down, level);
}
}
public static TriangleHit? Raycast(Ray ray, int level, BoundsMap bounds, Func<Cell, float> heightAt, Transform gridTransform = null)
{
if (gridTransform != null)
{
ray = new Ray(gridTransform.InverseTransformPoint(ray.origin), gridTransform.InverseTransformDirection(ray.direction));
}
var closest = (ray.origin - Vector3.Dot(ray.origin, ray.direction) * ray.direction).magnitude;
var candidates = new List<Triangle>(Triangle.AtLevel(0));
for (int i = 0; i < level; i++)
{
var triangles = candidates;
candidates = new List<Triangle>();
foreach (var triangle in triangles)
{
var max = bounds.GetMax(triangle, i);
if (max < closest) { continue; }
if (intersectsCell(ray, triangle, i, bounds.GetMin(triangle, i), max))
{
candidates.AddRange(triangle.GetChildren(i + 1));
}
}
}
return candidates.Select(t => t.Raycast(ray, level, heightAt)).Where(h => h.HasValue).WithMin(t => t.Value.Distance);
}
public TriangleHit? Raycast(Ray ray, int level, Func<Cell, float> heightAt)
{
Vector3 v0, v1, v2;
using (var vertices = GetVertices(level).GetEnumerator())
{
vertices.MoveNext(); v0 = vertices.Current.Position * heightAt(vertices.Current);
vertices.MoveNext(); v1 = vertices.Current.Position * heightAt(vertices.Current);
vertices.MoveNext(); v2 = vertices.Current.Position * heightAt(vertices.Current);
}
var e1 = v1 - v0;
var e2 = v2 - v0;
var p = Vector3.Cross(ray.direction, e2);
var a = Vector3.Dot(e1, p);
if (a <= 0) { return null; }
var f = 1 / a;
var s = ray.origin - v0;
var u = f * Vector3.Dot(s, p);
if (u < 0 || u > 1) { return null; }
var q = Vector3.Cross(s, e1);
var v = f * Vector3.Dot(ray.direction, q);
var w = u + v;
if (v < 0 || w > 1) { return null; }
var t = f * Vector3.Dot(e2, q);
return new TriangleHit(this, t, new Vector3(1 - w, u, v));
}
private static bool intersectsCell(Ray ray, Triangle triangle, int level, float min, float max)
{
Vector3? first;
sphereIntersection(ray, max, out first);
var radius = ray.origin.magnitude;
if (radius >= max)
{
if (first.HasValue && triangleContains(triangle, level, first.Value)) { return true; }
}
else
{
if ((radius >= min) && triangleContains(triangle, level, ray.origin)) { return true; }
}
return triangle.GetVertices(level).Select(c => c.Position).AdjacentPairs().Any(p => intersectsFace(ray, p.Second, p.First, min, max));
}
private static bool triangleContains(Triangle triangle, int level, Vector3 line)
{
return triangle.Raycast(new Ray(line.normalized, -line), level, c => 0.5f).HasValue;
}
private static bool intersectsFace(Ray ray, Vector3 a, Vector3 b, float min, float max)
{
var normal = Vector3.Cross(a, b);
var denominator = Vector3.Dot(ray.direction, normal);
if (denominator >= 0) { return false; }
var distance = -Vector3.Dot(ray.origin, normal) / denominator;
var point = ray.origin + distance * ray.direction;
var length = point.magnitude;
if (length > max) { return false; }
if (length < min) { return false; }
if (Vector3.Dot(Vector3.Cross(a, normal), point) > 0) { return false; }
if (Vector3.Dot(Vector3.Cross(b, normal), point) < 0) { return false; }
return true;
}
/// <summary>
/// Finds the first intersection by a ray with a sphere of given radius centered at the origin.
/// </summary>
private static bool sphereIntersection(Ray ray, float radius, out Vector3? point)
{
var a = radius * radius - ray.origin.sqrMagnitude;
if (a > 0) { point = null; return true; }
var v = -Vector3.Dot(ray.direction, ray.origin);
var d = v * v + a;
if (d < 0) { point = null; return false; }
var sqrt = (float)Math.Sqrt(d);
var second = v + sqrt;
if (second < 0) { point = null; return false; }
var first = v - sqrt;
point = ray.origin + ray.direction * (first > 0 ? first : second);
return true;
}
}
#endregion
#region Searching
/// <summary>
/// Finds the cell at the given level containing the given direction vector.
/// </summary>
public static Cell Containing(Vector3 line, int level)
{
var closest = new Cell(line.y < 0 ? 1u : 0);
for (var i = 0; i <= level; i++)
{
closest = closest.searchNeighbors(line, i);
}
return closest;
}
/// <summary>
/// Determines whether this cell contains the given direction vector at the given level.
/// </summary>
public bool Contains(Vector3 line, int level)
{
var dot = Vector3.Dot(this.Position, line);
return this.GetNeighbors(level).All(c => Vector3.Dot(c.Position, line) <= dot);
}
private Cell searchNeighbors(Vector3 line, int level)
{
return this.GetNeighbors(level).Prepend(this).WithMax(c => Vector3.Dot(c.Position, line));
}
#endregion
#region Neighbors
/// <summary>
/// Enumerates the cell neighbors at the same level as the current cell.
/// </summary>
public IEnumerable<Cell> GetNeighbors()
{
return GetNeighbors(this.Level);
}
/// <summary>
/// Enumerates the cell neighbors at the given level.
/// </summary>
public IEnumerable<Cell> GetNeighbors(int level)
{
if (level < Level) { throw new ArgumentException(); }
if (index == 0)
{
for (uint i = 10; i > 0; i -= 2)
{
yield return new Cell(i).approach(ChildType.Up, level);
}
}
else if (index == 1)
{
for (uint i = 3; i < 12; i += 2)
{
yield return new Cell(i).approach(ChildType.Down, level);
}
}
else
{
yield return this.getNeighbor(ChildType.Up, level);
yield return this.getNeighbor(ChildType.Straight, level);
yield return this.getNeighbor(ChildType.Down, level);
var root = IsPentagon;
if (!(root && index % 2 != 0))
{
yield return this.getBackNeighbor(ChildType.Down, level);
}
yield return this.getBackNeighbor(ChildType.Straight, level);
if (!(root && index % 2 == 0))
{
yield return this.getBackNeighbor(ChildType.Up, level);
}
}
}
#endregion
#region Grid structure
private ChildType direction
{
get { return (ChildType)(subindex % 3); }
}
private uint subindex
{
get
{
if (IsPentagon) { throw new InvalidOperationException("Top-level cells don't have a subindex"); }
return index - CountAtLevel(Level - 1);
}
}
private bool isPolar
{
get { return index < 2; }
}
public Cell GetParent()
{
if (Level == 0) { throw new InvalidOperationException("Cannot find parent of a top-level cell"); }
return new Cell(subindex / 3 + 2);
}
private Cell getSecondParent()
{
if (Level == 0) { throw new InvalidOperationException("Cannot find parent of a top-level cell"); }
return GetParent().getNeighbor(this.direction, Level - 1);
}
private Cell getChild(ChildType direction)
{
return getChild(direction, Level + 1);
}
private Cell getChild(ChildType direction, int level)
{
if (isPolar) { throw new ArgumentException("Cannot find child of a polar cell"); }
return new Cell((index - 2) * 3 + (byte)direction, level - 1);
}
private Cell approachSlow(ChildType direction, int levels)
{
var cell = this;
for (var i = 0; i < levels; i++)
{
cell = cell.getChild(direction);
}
return cell;
}
// Faster equivalent of approachSlow()
private Cell approach(ChildType direction, int levels)
{
if (levels == 0) { return this; }
if (isPolar) { throw new ArgumentException("Cannot find child of a polar cell"); }
var a = (uint)IntMath.Pow(3, (uint)levels);
return new Cell(this.index * a - (uint)((5 * (4 << (2 * this.Level)) * (a - (1 << (2 * levels))) - ((byte)direction - 4) * (a - 1)) / 2));
}
private static uint wrap(uint index)
{
return (index + 8) % 10 + 2;
}
private static readonly List<Cell[,]> neighborCache = new List<Cell[,]>();
private Cell getNeighbor(ChildType direction, int level)
{
var thisLevel = this.Level;
if (level < thisLevel) { throw new ArgumentException("Cannot find neighbor at a level index lower than this cell"); }
if (level == 0)
{
if (isPolar) { throw new ArgumentException("Cannot find neighbor of a polar cell"); }
if (direction == ChildType.Straight)
{
return new Cell(wrap(index + 2));
}
else if ((index % 2 == 0 && direction == ChildType.Up)
|| (index % 2 == 1 && direction == ChildType.Down))
{
return new Cell(index % 2);
}
else
{
return new Cell(wrap(index + 1));
}
}
else if (level == thisLevel)
{
for (var cacheLevel = neighborCache.Count + 1; cacheLevel <= thisLevel; cacheLevel++)
{
var cache = new Cell[30 << (2 * (cacheLevel - 1)), 3];
var count = CountAtLevel(cacheLevel - 1);
for (uint j = 0; j < cache.GetLength(0); j++)
{
for (byte k = 0; k < 3; k++)
{
var cell = new Cell(count + j);
var dir = (ChildType)k;
var thisDir = cell.direction;
var first = cell.GetParent();
if (thisDir == dir)
{
cache[j, k] = first.getNeighbor(dir, cacheLevel - 1);
}
else if (thisDir == dir.Flip())
{
cache[j, k] = first.getNeighbor(ChildType.Straight, cacheLevel);
}
else
{
if (dir == ChildType.Straight) { dir = thisDir; }
var other = first.getNeighbor(dir, cacheLevel - 1);
if (other.isPolarSeam() && (first.getRoot() != other.getRoot()))
{
cache[j, k] = first.getNeighbor(ChildType.Straight, cacheLevel - 1).getNeighbor(dir, cacheLevel);
}
else
{
cache[j, k] = other.getNeighbor(dir.Flip(), cacheLevel);
}
}
}
}
neighborCache.Add(cache);
}
return neighborCache[thisLevel - 1][this.subindex, (byte)direction];
}
else
{
return getChild(direction, level);
}
}
private Cell getRoot()
{
var cell = this;
while (!cell.IsPentagon)
{
cell = cell.GetParent();
}
return cell;
}
private Cell getBackNeighbor(ChildType direction, int level)
{
var thisLevel = this.Level;
if (level < thisLevel) { throw new ArgumentException("Cannot find neighbor at a level index lower than this cell"); }
if (thisLevel == 0)
{
if (isPolar) { throw new ArgumentException("Cannot find neighbor of a polar cell"); }
if (direction == ChildType.Straight)
{
return new Cell(wrap(index - 2)).approach(ChildType.Straight, level);
}
else
{
var north = index % 2 == 0;
var down = direction == ChildType.Down;
if (north != down) { throw new InvalidOperationException(); } // TODO: Exception text
return new Cell(wrap(index - 1)).approach(direction.Flip(), level);
}
}
else
{
var thisDir = this.direction;
var first = this.GetParent();
if (level != thisLevel)
{
first = first.getChild(thisDir, thisLevel + 1).approach(thisDir, level - thisLevel - 1);
}
if (thisDir == direction.Flip())
{
return first;
}
else if (thisDir == ChildType.Straight)
{
return first.getNeighbor(direction, level);
}
else
{
first = this.GetParent();
var other = thisDir.Flip();
var seam = this.isPolarSeam();
var commonDir = thisDir;
if (first.IsPentagon && ((thisDir == ChildType.Down) != (first.index % 2 == 0)))
{
commonDir = ChildType.Straight;
}
var common = first.getBackNeighbor(commonDir, thisLevel - 1);
if ((direction == ChildType.Straight) == seam)
{
return common.getNeighbor(ChildType.Straight, thisLevel).approach(seam ? thisDir : other, level - thisLevel);
}
else
{
return common.getNeighbor(seam ? thisDir : other, thisLevel).approach(ChildType.Straight, level - thisLevel);
}
}
}
}
private bool isPolarSeam()
{
if (this.IsPentagon) { return this.isPolar; }
var dir = this.direction;
var cell = this.GetParent();
while (!cell.IsPentagon)
{
if (cell.direction != dir) { return false; }
cell = cell.GetParent();
}
return cell.getNeighbor(dir, 0).isPolar;
}
#endregion
#region Standard overrides
public bool Equals(Cell other)
{
return index == other.index;
}
public override int GetHashCode()
{
return unchecked((int)index * 31);
}
public override string ToString()
{
return String.Format("C{0}", index);
}
public override bool Equals(object obj)
{
if (obj is Cell) { return Equals((Cell)obj); }
return false;
}
public static bool operator ==(Cell a, Cell b) { return a.Equals(b); }
public static bool operator !=(Cell a, Cell b) { return !(a == b); }
#endregion
}
}