-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCell.cs
518 lines (431 loc) · 16.4 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
using GeodesicGrid.EnumerableExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using Ray = UnityEngine.Ray;
using Transform = UnityEngine.Transform;
using Vector3 = UnityEngine.Vector3;
namespace GeodesicGrid
{
public struct Cell : IEquatable<Cell>
{
static Cell()
{
LicenseSentinel.Run();
}
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).EdgesCircular().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).EdgesCircular())
{
yield return (position + pair.First.Position + pair.Second.Position).normalized * (height + heightAt(pair.First) + heightAt(pair.Second)) / 3;
}
}
#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).MaxBy(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.GetFrontNeighbor(ChildType.Up, level);
yield return this.GetFrontNeighbor(ChildType.Straight, level);
yield return this.GetFrontNeighbor(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().GetFrontNeighbor(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[,]>();
public Cell GetFrontNeighbor(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.GetFrontNeighbor(dir, cacheLevel - 1);
}
else if (thisDir == dir.Flip())
{
cache[j, k] = first.GetFrontNeighbor(ChildType.Straight, cacheLevel);
}
else
{
if (dir == ChildType.Straight) { dir = thisDir; }
var other = first.GetFrontNeighbor(dir, cacheLevel - 1);
if (other.isPolarSeam() && (first.getRoot() != other.getRoot()))
{
cache[j, k] = first.GetFrontNeighbor(ChildType.Straight, cacheLevel - 1).GetFrontNeighbor(dir, cacheLevel);
}
else
{
cache[j, k] = other.GetFrontNeighbor(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.GetFrontNeighbor(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.GetFrontNeighbor(ChildType.Straight, thisLevel).approach(seam ? thisDir : other, level - thisLevel);
}
else
{
return common.GetFrontNeighbor(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.GetFrontNeighbor(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
}
}