-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathHexCoord.cs
726 lines (664 loc) · 23.1 KB
/
HexCoord.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
using UnityEngine;
using System;
using System.Collections.Generic;
namespace Settworks.Hexagons {
/// <summary>
/// Hexagon grid coordinate.
/// </summary>
/// <remarks>
/// Uses the q,r axial system detailed at http://www.redblobgames.com/grids/hexagons/.
/// These are "pointy topped" hexagons. The q axis points right, and the r axis points up-right.
/// When converting to and from Unity coordinates, the length of a hexagon side is 1 unit.
/// </remarks>
[Serializable]
public struct HexCoord {
/// <summary>
/// Position on the q axis.
/// </summary>
[SerializeField]
public int q;
/// <summary>
/// Position on the r axis.
/// </summary>
[SerializeField]
public int r;
/// <summary>
/// Initializes a new instance of the <see cref="Settworks.Hexagons.HexCoord"/> struct.
/// </summary>
/// <param name="q">Position on the q axis.</param>
/// <param name="r">Position on the r axis.</param>
public HexCoord(int q, int r) {
this.q = q;
this.r = r;
}
/// <summary>
/// Position on the cubic z axis.
/// </summary>
/// <remarks>
/// The q,r coordinate system is derived from an x,y,z cubic system with the constraint that x + y + z = 0.
/// Where x = q and y = r, this property derives z as <c>-q-r</c>.
/// </remarks>
public int Z {
get { return -q-r; }
}
/// <summary>
/// Offset x coordinate.
/// </summary>
/// <remarks>
/// Offset coordinates are a common alternative for hexagons, allowing pseudo-square grid operations.
/// Where y = r, this property represents the x coordinate as <c>q + r/2</c>.
/// </remarks>
public int O {
get { return q + (r>>1); }
}
/// <summary>
/// Unity position of this hex.
/// </summary>
public Vector2 Position() {
return q*Q_XY + r*R_XY;
}
/// <summary>
/// Get the maximum absolute cubic coordinate.
/// </summary>
/// <remarks>
/// In hexagonal space this is the polar radius, i.e. distance from 0,0.
/// </remarks>
public int AxialLength() {
if (q == 0 && r == 0) return 0;
if (q > 0 && r >= 0) return q + r;
if (q <= 0 && r > 0) return (-q < r)? r: -q;
if (q < 0) return -q - r;
return (-r > q)? -r: q;
}
/// <summary>
/// Get the minimum absolute cubic coordinate.
/// </summary>
/// <remarks>
/// This is the number of hexagon steps from 0,0 which are not along the maximum axis.
/// </remarks>
public int AxialSkew() {
if (q == 0 && r == 0) return 0;
if (q > 0 && r >= 0) return (q < r)? q: r;
if (q <= 0 && r > 0) return (-q < r)? Math.Min(-q, q + r): Math.Min(r, -q - r);
if (q < 0) return (q > r)? -q: -r;
return (-r > q)? Math.Min(q, -q -r): Math.Min(-r, q + r);
}
/// <summary>
/// Get the angle from 0,0 to the center of this hex.
/// </summary>
public float PolarAngle() {
Vector3 pos = Position();
return (float)Math.Atan2(pos.y, pos.x);
}
/// <summary>
/// Get the counterclockwise position of this hex in the ring at its distance from 0,0.
/// </summary>
public int PolarIndex() {
if (q == 0 && r == 0) return 0;
if (q > 0 && r >= 0) return r;
if (q <= 0 && r > 0) return (-q < r)? r - q: -3 * q - r;
if (q < 0) return -4 * (q + r) + q;
return (-r > q)? -4 * r + q: 6 * q + r;
}
/// <summary>
/// Get a neighboring hex.
/// </summary>
/// <remarks>
/// Neighbor 0 is to the right, others proceed counterclockwise.
/// </remarks>
/// <param name="index">Index of the desired neighbor. Cyclically constrained 0..5.</param>
public HexCoord Neighbor(int index) {
return NeighborVector(index) + this;
}
public HexCoord PolarNeighbor(bool CCW = false) {
if (q > 0) {
if (r < 0) {
if (q > -r) return this + neighbors[CCW? 1: 4];
if (q < -r) return this + neighbors[CCW? 0: 3];
return this + neighbors[CCW? 1: 3];
}
if (r > 0) return this + neighbors[CCW? 2: 5];
return this + neighbors[CCW? 2: 4];
}
if (q < 0) {
if (r > 0) {
if (r > -q) return this + neighbors[CCW? 3: 0];
if (r < -q) return this + neighbors[CCW? 4: 1];
return this + neighbors[CCW? 4: 0];
}
if (r < 0) return this + neighbors[CCW? 5: 2];
return this + neighbors[CCW? 5: 1];
}
if (r > 0) return this + neighbors[CCW? 3: 5];
if (r < 0) return this + neighbors[CCW? 0: 2];
return this;
}
/// <summary>
/// Enumerate this hex's six neighbors.
/// </summary>
/// <remarks>
/// Neighbor 0 is to the right, others proceed counterclockwise.
/// </remarks>
/// <param name="first">Index of the first neighbor to enumerate.</param>
public IEnumerable<HexCoord> Neighbors(int first = 0) {
foreach (HexCoord hex in NeighborVectors(first))
yield return hex + this;
}
/// <summary>
/// Get the Unity position of a corner vertex.
/// </summary>
/// <remarks>
/// Corner 0 is at the upper right, others proceed counterclockwise.
/// </remarks>
/// <param name="index">Index of the desired corner. Cyclically constrained 0..5.</param>
public Vector2 Corner(int index) {
return CornerVector(index) + Position();
}
/// <summary>
/// Enumerate this hex's six corners.
/// </summary>
/// <remarks>
/// Corner 0 is at the upper right, others proceed counterclockwise.
/// </remarks>
/// <param name="first">Index of the first corner to enumerate.</param>
public IEnumerable<Vector2> Corners(int first = 0) {
Vector2 pos = Position();
foreach (Vector2 v in CornerVectors(first))
yield return v + pos;
}
/// <summary>
/// Get the polar angle to a corner vertex.
/// </summary>
/// <remarks>
/// This is the angle in radians from the center of 0,0 to the selected corner of this hex.
/// </remarks>
/// <param name="index">Index of the desired corner.</param>
public float CornerPolarAngle(int index) {
Vector2 pos = Corner(index);
return (float)Math.Atan2(pos.y, pos.x);
}
/// <summary>
/// Get the polar angle to the clockwise bounding corner.
/// </summary>
/// <remarks>
/// The two polar bounding corners are those whose polar angles form the widest arc.
/// </remarks>
/// <param name="CCW">If set to <c>true</c>, gets the counterclockwise bounding corner.</param>
public float PolarBoundingAngle(bool CCW = false) {
return CornerPolarAngle(PolarBoundingCornerIndex(CCW));
}
/// <summary>
/// Get the XY position of the clockwise bounding corner.
/// </summary>
/// <remarks>
/// The two polar bounding corners are those whose polar angles form the widest arc.
/// </remarks>
/// <param name="CCW">If set to <c>true</c>, gets the counterclockwise bounding corner.</param>
public Vector2 PolarBoundingCorner(bool CCW = false) {
return Corner(PolarBoundingCornerIndex(CCW));
}
/// <summary>
/// Get the index of the clockwise bounding corner.
/// </summary>
/// <remarks>
/// The two polar bounding corners are those whose polar angles form the widest arc.
/// </remarks>
/// <param name="CCW">If set to <c>true</c>, gets the counterclockwise bounding corner.</param>
/// <param name="neighbor">If set to <c>true</c>, gets the other corner shared by the same ring-neighbor as normal return.</param>
public int PolarBoundingCornerIndex(bool CCW = false) {
if (q == 0 && r == 0) return 0;
if (q > 0 && r >= 0) return CCW?
(q > r)? 1: 2:
(q < r)? 5: 4;
if (q <= 0 && r > 0) return (-q < r)?
CCW?
(r > -2 * q)? 2: 3:
(r < -2 * q)? 0: 5:
CCW?
(q > -2 * r)? 3: 4:
(q < -2 * r)? 1: 0;
if (q < 0) return CCW?
(q < r)? 4: 5:
(q > r)? 2: 1;
return (-r > q)?
CCW?
(r < -2 * q)? 5: 0:
(r > -2 * q)? 3: 2:
CCW?
(q < -2 * r)? 0: 1:
(q > -2 * r)? 4: 3;
}
/// <summary>
/// Get the half sextant of origin containing this hex.
/// </summary>
/// <remarks>
/// CornerSextant is HalfSextant/2. NeighborSextant is (HalfSextant+1)/2.
/// </remarks>
public int HalfSextant() {
if (q > 0 && r >= 0 || q == 0 && r == 0)
return (q > r)? 0 : 1;
if (q <= 0 && r > 0)
return (-q < r)?
(r > -2 * q)? 2: 3:
(q > -2 * r)? 4: 5;
if (q < 0)
return (q < r)? 6: 7;
return (-r > q)?
(r < -2 * q)? 8: 9:
(q < -2 * r)? 10: 11;
}
/// <summary>
/// Get the corner index of 0,0 closest to this hex's polar vector.
/// </summary>
public int CornerSextant() {
if (q > 0 && r >= 0 || q == 0 && r == 0) return 0;
if (q <= 0 && r > 0) return (-q < r)? 1: 2;
if (q < 0) return 3;
return (-r > q)? 4: 5;
}
/// <summary>
/// Get the neighbor index of 0,0 through which this hex's polar vector passes.
/// </summary>
public int NeighborSextant() {
if (q == 0 && r == 0) return 0;
if (q > 0 && r >= 0) return (q <= r)? 1: 0;
if (q <= 0 && r > 0) return (-q <= r)?
(r <= -2 * q)? 2: 1:
(q <= -2 * r)? 3: 2;
if (q < 0) return (q >= r)? 4: 3;
return (-r > q)?
(r >= -2 * q)? 5: 4:
(q >= -2 * r)? 0: 5;
}
/// <summary>
/// Rotate around 0,0 in sextant increments.
/// </summary>
/// <returns>
/// A new <see cref="Settworks.Hexagons.HexCoord"/> representing this one after rotation.
/// </returns>
/// <param name="sextants">How many sextants to rotate by.</param>
public HexCoord SextantRotation(int sextants) {
if (this == origin) return this;
sextants = NormalizeRotationIndex(sextants, 6);
if (sextants == 0) return this;
if (sextants == 1) return new HexCoord(-r, -Z);
if (sextants == 2) return new HexCoord(Z, q);
if (sextants == 3) return new HexCoord(-q, -r);
if (sextants == 4) return new HexCoord(r, Z);
return new HexCoord(-Z, -q);
}
/// <summary>
/// Mirror across a cubic axis.
/// </summary>
/// <remarks>
/// The cubic axes are "diagonal" to the hexagons, passing through two opposite corners.
/// </remarks>
/// <param name="axis">A corner index through which the axis passes.</param>
/// <returns>A new <see cref="Settworks.Hexagons.HexCoord"/> representing this one after mirroring.</returns>
public HexCoord Mirror(int axis = 1) {
if (this == origin) return this;
axis = NormalizeRotationIndex(axis, 3);
if (axis == 0) return new HexCoord(r, q);
if (axis == 1) return new HexCoord(Z, r);
return new HexCoord(q, Z);
}
/// <summary>
/// Scale as a vector, truncating result.
/// </summary>
/// <returns>This <see cref="Settworks.Hexagons.HexCoord"/> after scaling.</returns>
public HexCoord Scale(float factor) {
q = (int)(q * factor);
r = (int)(r * factor);
return this;
}
/// <summary>
/// Scale as a vector.
/// </summary>
/// <returns>This <see cref="Settworks.Hexagons.HexCoord"/> after scaling.</returns>
public HexCoord Scale(int factor) {
q *= factor;
r *= factor;
return this;
}
/// <summary>
/// Scale as a vector.
/// </summary>
/// <returns><see cref="UnityEngine.Vector2"/> representing the scaled vector.</returns>
public Vector2 ScaleToVector(float factor)
{ return new Vector2(q * factor, r * factor); }
/// <summary>
/// Determines whether this hex is within a specified rectangle.
/// </summary>
/// <returns><c>true</c> if this instance is within the specified rectangle; otherwise, <c>false</c>.</returns>
public bool IsWithinRectangle(HexCoord cornerA, HexCoord cornerB) {
if (r > cornerA.r && r > cornerB.r || r < cornerA.r && r < cornerB.r)
return false;
bool reverse = cornerA.O > cornerB.O; // Travel right to left.
bool offset = cornerA.r % 2 != 0; // Starts on an odd row, bump alternate rows left.
bool trim = Math.Abs(cornerA.r - cornerB.r) % 2 == 0; // Even height, trim alternate rows.
bool odd = (r - cornerA.r) % 2 != 0; // This is an alternate row.
int width = Math.Abs(cornerA.O - cornerB.O);
bool hasWidth = width != 0;
if (reverse && (odd && (trim || !offset) || !(trim || offset || odd))
|| !reverse && (trim && odd || offset && !trim && hasWidth))
width -= 1;
int x = (O - cornerA.O) * (reverse? -1: 1);
if (reverse && odd && !offset
|| !reverse && offset && odd && hasWidth)
x -= 1;
return (x <= width && x >= 0);
}
/// <summary>
/// Determines whether this hex is on the infinite line passing through points a and b.
/// </summary>
public bool IsOnCartesianLine(Vector2 a, Vector2 b) {
Vector2 AB = b - a;
bool bias = Vector3.Cross(AB, Corner(0) - a).z > 0;
for (int i = 1; i < 6; i++) {
if (bias != (Vector3.Cross(AB, Corner(i) - a).z > 0))
return true;
}
return false;
}
/// <summary>
/// Determines whether this the is on the line segment between points a and b.
/// </summary>
public bool IsOnCartesianLineSegment(Vector2 a, Vector2 b) {
Vector2 AB = b - a;
float mag = AB.sqrMagnitude;
Vector2 AC = Corner(0) - a;
bool within = AC.sqrMagnitude <= mag && Vector2.Dot(AB, AC) >= 0;
int sign = Math.Sign(Vector3.Cross(AB, AC).z);
for (int i = 1; i < 6; i++) {
AC = Corner(i) - a;
bool newWithin = AC.sqrMagnitude <= mag && Vector2.Dot(AB, AC) >= 0;
int newSign = Math.Sign(Vector3.Cross(AB, AC).z);
if ((within || newWithin) && (sign * newSign <= 0))
return true;
within = newWithin;
sign = newSign;
}
return false;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Settworks.Hexagons.HexCoord"/>.
/// </summary>
/// <remarks>
/// Matches the formatting of <see cref="UnityEngine.Vector2.ToString()"/>.
/// </remarks>
public override string ToString () {
return "(" + q + "," + r + ")";
}
/*
* Static Methods
*/
/// <summary>
/// HexCoord at (0,0)
/// </summary>
public static readonly HexCoord origin = default(HexCoord);
/// <summary>
/// Distance between two hexes.
/// </summary>
public static int Distance(HexCoord a, HexCoord b) {
return (a - b).AxialLength();
}
/// <summary>
/// Normalize a rotation index within 0 <= index < cycle.
/// </summary>
public static int NormalizeRotationIndex(int index, int cycle = 6) {
if (index < 0 ^ cycle < 0)
return (index % cycle + cycle) % cycle;
else
return index % cycle;
}
/// <summary>
/// Determine the equality of two rotation indices for a given cycle.
/// </summary>
public static bool IsSameRotationIndex(int a, int b, int cycle = 6) {
return 0 == NormalizeRotationIndex(a - b, cycle);
}
/// <summary>
/// Vector from a hex to a neighbor.
/// </summary>
/// <remarks>
/// Neighbor 0 is to the right, others proceed counterclockwise.
/// </remarks>
/// <param name="index">Index of the desired neighbor vector. Cyclically constrained 0..5.</param>
public static HexCoord NeighborVector(int index)
{ return neighbors[NormalizeRotationIndex(index, 6)]; }
/// <summary>
/// Enumerate the six neighbor vectors.
/// </summary>
/// <remarks>
/// Neighbor 0 is to the right, others proceed counterclockwise.
/// </remarks>
/// <param name="first">Index of the first neighbor vector to enumerate.</param>
public static IEnumerable<HexCoord> NeighborVectors(int first = 0) {
first = NormalizeRotationIndex(first, 6);
for (int i = first; i < 6; i++)
yield return neighbors[i];
for (int i = 0; i < first; i++)
yield return neighbors[i];
}
/// <summary>
/// Neighbor index of 0,0 through which a polar angle passes.
/// </summary>
public static int AngleToNeighborIndex(float angle)
{ return Mathf.RoundToInt(angle / SEXTANT); }
/// <summary>
/// Polar angle for a neighbor of 0,0.
/// </summary>
public static float NeighborIndexToAngle(int index)
{ return index * SEXTANT; }
/// <summary>
/// Unity position vector from hex center to a corner.
/// </summary>
/// <remarks>
/// Corner 0 is at the upper right, others proceed counterclockwise.
/// </remarks>
/// <param name="index">Index of the desired corner. Cyclically constrained 0..5.</param>
public static Vector2 CornerVector(int index) {
return corners[NormalizeRotationIndex(index, 6)];
}
/// <summary>
/// Enumerate the six corner vectors.
/// </summary>
/// <remarks>
/// Corner 0 is at the upper right, others proceed counterclockwise.
/// </remarks>
/// <param name="first">Index of the first corner vector to enumerate.</param>
public static IEnumerable<Vector2> CornerVectors(int first = 0) {
if (first == 0) {
foreach (Vector2 v in corners)
yield return v;
} else {
first = NormalizeRotationIndex(first, 6);
for (int i = first; i < 6; i++)
yield return corners[i];
for (int i = 0; i < first; i++)
yield return corners[i];
}
}
/// <summary>
/// Corner of 0,0 closest to a polar angle.
/// </summary>
public static int AngleToCornerIndex(float angle)
{ return Mathf.FloorToInt(angle / SEXTANT); }
/// <summary>
/// Polar angle for a corner of 0,0.
/// </summary>
public static float CornerIndexToAngle(int index)
{ return (index + 0.5f) * SEXTANT; }
/// <summary>
/// Half sextant of 0,0 through which a polar angle passes.
/// </summary>
public static int AngleToHalfSextant(float angle)
{ return Mathf.RoundToInt(2 * angle / SEXTANT); }
/// <summary>
/// Polar angle at which a half sextant begins.
/// </summary>
public static float HalfSextantToAngle(int index)
{ return index * SEXTANT / 2; }
/// <summary>
/// <see cref="Settworks.Hexagons.HexCoord"/> containing a Unity position.
/// </summary>
public static HexCoord AtPosition(Vector2 position)
{ return FromQRVector(VectorXYtoQR(position)); }
/// <summary>
/// <see cref="Settworks.Hexagons.HexCoord"/> from hexagonal polar coordinates.
/// </summary>
/// <remarks>
/// Hexagonal polar coordinates approximate a circle to a hexagonal ring.
/// </remarks>
/// <param name="radius">Hex distance from 0,0.</param>
/// <param name="index">Counterclockwise index.</param>
public static HexCoord AtPolar(int radius, int index) {
if (radius == 0) return origin;
if (radius < 0) radius = -radius;
index = NormalizeRotationIndex(index, radius * 6);
int sextant = index / radius;
index %= radius;
if (sextant == 0) return new HexCoord(radius - index, index);
if (sextant == 1) return new HexCoord(-index, radius);
if (sextant == 2) return new HexCoord(-radius, radius - index);
if (sextant == 3) return new HexCoord(index - radius, -index);
if (sextant == 4) return new HexCoord(index, -radius);
return new HexCoord(radius, index - radius);
}
/// <summary>
/// Find the hexagonal polar index closest to angle at radius.
/// </summary>
/// <remarks>
/// Hexagonal polar coordinates approximate a circle to a hexagonal ring.
/// </remarks>
/// <param name="radius">Hex distance from 0,0.</param>
/// <param name="angle">Desired polar angle.</param>
public static int FindPolarIndex(int radius, float angle) {
return (int)Math.Round(angle * radius * 3 / Mathf.PI);
}
/// <summary>
/// <see cref="Settworks.Hexagons.HexCoord"/> from offset coordinates.
/// </summary>
/// <remarks>
/// Offset coordinates are a common alternative for hexagons, allowing pseudo-square grid operations.
/// This conversion assumes an offset of x = q + r/2.
/// </remarks>
public static HexCoord AtOffset(int x, int y) {
return new HexCoord(x - (y>>1), y);
}
/// <summary>
/// <see cref="Settworks.Hexagons.HexCoord"/> containing a floating-point q,r vector.
/// </summary>
/// <remarks>
/// Hexagonal geometry makes normal rounding inaccurate. If working with floating-point
/// q,r vectors, use this method to accurately convert them back to
/// <see cref="Settworks.Hexagons.HexCoord"/>.
/// </remarks>
public static HexCoord FromQRVector(Vector2 QRvector) {
float z = -QRvector.x -QRvector.y;
int ix = (int)Math.Round(QRvector.x);
int iy = (int)Math.Round(QRvector.y);
int iz = (int)Math.Round(z);
if (ix + iy + iz != 0) {
float dx = Math.Abs(ix - QRvector.x);
float dy = Math.Abs(iy - QRvector.y);
float dz = Math.Abs(iz - z);
if (dx >= dy && dx >= dz)
ix = -iy-iz;
else if (dy >= dz)
iy = -ix-iz;
}
return new HexCoord(ix, iy);
}
/// <summary>
/// Convert an x,y vector to a q,r vector.
/// </summary>
public static Vector2 VectorXYtoQR(Vector2 XYvector) {
return XYvector.x*X_QR + XYvector.y*Y_QR;
}
/// <summary>
/// Convert a q,r vector to an x,y vector.
/// </summary>
public static Vector2 VectorQRtoXY(Vector2 QRvector) {
return QRvector.x*Q_XY + QRvector.y*R_XY;
}
/// <summary>
/// Get the corners of a QR-space rectangle containing every cell touching an XY-space rectangle.
/// </summary>
public static HexCoord[] CartesianRectangleBounds(Vector2 cornerA, Vector2 cornerB) {
Vector2 min = new Vector2(Math.Min(cornerA.x, cornerB.x), Math.Min(cornerA.y, cornerB.y));
Vector2 max = new Vector2(Math.Max(cornerA.x, cornerB.x), Math.Max(cornerA.y, cornerB.y));
HexCoord[] results = {
HexCoord.AtPosition(min),
HexCoord.AtPosition(max)
};
Vector2 pos = results[0].Position();
if (pos.y - 0.5f >= min.y)
results[0] += neighbors[4];
else if (pos.x >= min.x)
results[0] += neighbors[3];
pos = results[1].Position();
if (pos.y + 0.5f <= max.y)
results[1] += neighbors[1];
else if (pos.x <= max.x)
results[1] += neighbors[0];
return results;
}
/*
* Operators
*/
// Cast to Vector2 in QR space. Explicit to avoid QR/XY mix-ups.
public static explicit operator Vector2(HexCoord h)
{ return new Vector2(h.q, h.r); }
// +, -, ==, !=
public static HexCoord operator +(HexCoord a, HexCoord b)
{ return new HexCoord(a.q+b.q, a.r+b.r); }
public static HexCoord operator -(HexCoord a, HexCoord b)
{ return new HexCoord(a.q-b.q, a.r-b.r); }
public static bool operator ==(HexCoord a, HexCoord b)
{ return a.q == b.q && a.r == b.r; }
public static bool operator !=(HexCoord a, HexCoord b)
{ return a.q != b.q || a.r != b.r; }
// Mandatory overrides: Equals(), GetHashCode()
public override bool Equals(object o)
{ return (o is HexCoord) && this == (HexCoord)o; }
public override int GetHashCode() {
return q & (int)0xFFFF | r<<16;
}
/*
* Constants
*/
/// <summary>
/// One sixth of a full rotation (radians).
/// </summary>
public static readonly float SEXTANT = Mathf.PI / 3;
/// <summary>
/// Square root of 3.
/// </summary>
public static readonly float SQRT3 = Mathf.Sqrt(3);
// The directions array. These are private to prevent overwriting elements.
static readonly HexCoord[] neighbors = {
new HexCoord(1, 0),
new HexCoord(0, 1),
new HexCoord(-1, 1),
new HexCoord(-1, 0),
new HexCoord(0, -1),
new HexCoord(1, -1)
};
// Corner locations in XY space. Private for same reason as neighbors.
static readonly Vector2[] corners = {
new Vector2(Mathf.Sin(SEXTANT), Mathf.Cos(SEXTANT)),
new Vector2(0, 1),
new Vector2(Mathf.Sin(-SEXTANT), Mathf.Cos(-SEXTANT)),
new Vector2(Mathf.Sin(Mathf.PI + SEXTANT), Mathf.Cos(Mathf.PI - SEXTANT)),
new Vector2(0, -1),
new Vector2(Mathf.Sin(Mathf.PI - SEXTANT), Mathf.Cos(Mathf.PI - SEXTANT))
};
// Vector transformations between QR and XY space.
// Private to keep IntelliSense tidy. Safe to make public, but sensible uses are covered above.
static readonly Vector2 Q_XY = new Vector2(SQRT3, 0);
static readonly Vector2 R_XY = new Vector2(SQRT3/2, 1.5f);
static readonly Vector2 X_QR = new Vector2(SQRT3/3, 0);
static readonly Vector2 Y_QR = new Vector2(-1/3f, 2/3f);
}
}