hexgridspiral 0.3.0

Hexagonal Cube-Coordinate System with Spiralling Integer Tile Identifiers
Documentation
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
/*!
Hexagonal Cube-Coordinate System with Spiralling Integer Tile Identifiers

Read the [README](https://github.com/lucidBrot/hexgridspiral) for
* an Abstract
* Construction Examples
* A list of Features

*/
// We have code that uses the nightly toolchain. It is gated behind the "nightly" crate feature flag.
// This means the crate can still be used with stable rust - it will just not have all functions.
#![cfg_attr(feature = "nightly", feature(step_trait))]
#![cfg_attr(feature = "nightly", feature(coroutines))]
#![cfg_attr(feature = "nightly", feature(iter_from_coroutine))]
#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
#![cfg_attr(feature = "nightly", feature(doc_cfg))]

// The objects Tile, Ring, TileIndex, RingIndex are not supposed to be mutated.
// Instead, (they) make new objects.
use derive_more::with_trait::Sub;
use derive_more::{Add, Display, From, Into, Mul, Neg};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use serde::{Deserialize, Serialize};
use std::ops;

#[derive(
    Debug,
    Copy,
    Clone,
    PartialOrd,
    Ord,
    PartialEq,
    Eq,
    Add,
    Sub,
    Mul,
    Display,
    From,
    Into,
    Hash,
    Serialize,
    Deserialize,
)]
pub struct TileIndex(pub u64);

cfg_if::cfg_if! {if #[cfg(feature = "nightly")] {
#[cfg(any(feature = "nightly", doc))]
#[doc(cfg(feature = "nightly"))]
impl std::iter::Step for TileIndex {
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        return if end < start {
            // End < Start is illegal : https://doc.rust-lang.org/nightly/std/iter/trait.Step.html#tymethod.steps_between
            (0, None)
        } else {
            match usize::try_from((*end - *start).value() as usize) {
                // The happy path:
                Result::Ok(value) => (value, Some(value)),
                // Returns (usize::MAX, None) if the number of steps would overflow usize, or is infinite.
                Result::Err(_) => (usize::MAX, None),
            }
        };

        // This is currently a (lower-bound, upper-bound) tuple in nightly, "like size_hint".
        // It is exactly defined when the `n` must be `0` or `n` or `usize::max`. The rest seems not too relevant.
    }

    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(
            u64::try_from((start + u64::try_from(count).ok()?).value())
                .ok()?
                .into(),
        )
    }

    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        (start - u64::try_from(count).ok()?).try_into().ok()
    }
}
}}

/// Which Ring around the origin we're at, counting from 1.
/// Implementation Detail: The RingIndex wraps an integer that equals the number of tiles in one edge of the Ring (including both corners).
#[derive(Debug, Copy, Clone, PartialEq, Add, Sub, Mul, Display, From, Serialize, Deserialize)]
pub struct RingIndex(u64);

impl TileIndex {
    pub fn value(&self) -> u64 {
        self.0
    }

    pub fn is_origin(&self) -> bool {
        self.0 == 0
    }
}

impl RingIndex {
    pub const ORIGIN_RING: RingIndex = RingIndex(1);

    pub fn value(&self) -> u64 {
        let val = self.0;
        assert!(val > 0, "{val} is not a valid RingIndex value.");
        val
    }
}

// Define Addition for an u64 (offset) to a Tile/Ring-Index.
// Tbh this adds too much magic and the boilerplate is also needed for subtraction, multiplication, etc. and for all integer types...
impl ops::Add<u64> for TileIndex {
    type Output = TileIndex;

    fn add(self, rhs: u64) -> TileIndex {
        TileIndex(self.value() + rhs)
    }
}

impl ops::Sub<u64> for TileIndex {
    type Output = TileIndex;

    fn sub(self, rhs: u64) -> TileIndex {
        assert!(rhs <= self.value());
        TileIndex(self.value() - rhs)
    }
}

impl ops::Rem<u64> for TileIndex {
    type Output = TileIndex;

    fn rem(self, rhs: u64) -> TileIndex {
        TileIndex(self.value() % rhs)
    }
}

impl ops::Add<TileIndex> for u64 {
    type Output = TileIndex;

    fn add(self, rhs: TileIndex) -> TileIndex {
        TileIndex(self + rhs.value())
    }
}

impl ops::Add<u64> for RingIndex {
    type Output = RingIndex;

    fn add(self, rhs: u64) -> RingIndex {
        RingIndex(self.value() + rhs)
    }
}

impl ops::Add<RingIndex> for u64 {
    type Output = RingIndex;

    fn add(self, rhs: RingIndex) -> RingIndex {
        RingIndex(self + rhs.value())
    }
}

impl ops::Sub<u64> for RingIndex {
    type Output = RingIndex;

    fn sub(self, rhs: u64) -> RingIndex {
        assert!(rhs <= self.value());
        RingIndex(self.value() - rhs)
    }
}

/// A Ring is hexagonal and consists of tiles.
/// All Ring-Corner Tiles have the same number of steps to the origin.
/// The other tiles in the Ring are on straight edges between corners.
/// The [RingIndex] counts from 1 and thus is always equal to the [Ring::edge_size].
#[derive(Debug, Copy, Clone, PartialEq, Add, Display, From, Into, Serialize, Deserialize)]
pub struct Ring {
    /// ring-index
    n: RingIndex,
}

/// Hexgrid Spiral Tile
///
/// Identified by a single integer index ([TileIndex]) that spirals around the origin.
#[derive(Debug, Copy, Clone, PartialEq, Display, From, Into, Serialize, Deserialize)]
#[display("HGSTile: {h}")]
pub struct HGSTile {
    // tile-index
    h: TileIndex,
    ring: Ring,
}

/// CubeCoordinates Tile
/// For reference: <https://www.redblobgames.com/grids/hexagons/>
///
/// `r` is constant 0 along the x-Axis (towards right) while `q` increments and `s` decrements.
///
/// Towards the bottom (negative y-Axis), `r` increments while the other decrement equally to ensure the invariant `q+r+s=0` always holds.
///
/// Towards the bottom-right, `q` stays constant and is negative on the bottom side.
/// Towards the right, `r` stays constant and is *positive* on the bottom side.
/// Towards the top-right, `s` stays constant and is negative on the bottom side.
// TODO: Division is not implemented for CCTile. If needed, it should yield a CCTileFloat type.
#[derive(
    Debug,
    Copy,
    Clone,
    PartialEq,
    Display,
    From,
    Into,
    Eq,
    Neg,
    Add,
    Mul,
    Sub,
    Serialize,
    Deserialize,
)]
#[display("CCTile: ({q}, {r},{s})")]
pub struct CCTile {
    q: i64,
    r: i64,
    s: i64,
}

/// An identifier for each side of the ring's edge.
/// Numbered counterclockwise from the top-right edge.
#[derive(Debug, Copy, Clone, PartialEq, Add, Display, From, Into, Serialize, Deserialize)]
pub struct RingEdge(u8);

/// An identifier for each corner of the ring's edge.
/// Numbered counterclockwise, from the right corner.
/// The n-th corner is the start of the n-th edge.
#[derive(Debug, Copy, Clone, PartialEq, Add, Display, TryFromPrimitive, IntoPrimitive, Eq)]
#[repr(u8)]
pub enum RingCornerIndex {
    RIGHT = 0,
    TOPRIGHT = 1,
    TOPLEFT = 2,
    LEFT = 3,
    BOTTOMLEFT = 4,
    BOTTOMRIGHT = 5,
}

impl RingEdge {
    pub fn start(&self) -> RingCornerIndex {
        TryInto::<RingCornerIndex>::try_into(self.0).unwrap()
    }

    pub fn end(&self) -> RingCornerIndex {
        TryInto::<RingCornerIndex>::try_into((self.0 + 1) % 6).unwrap()
    }

    /// Returns a RingCornerIndex that signifies the edge direction. E.g. the edge going towards the top-left would return the top-left corner.
    pub fn direction(&self) -> RingCornerIndex {
        self.end().next()
    }

    /// Transforms two distinct corners into an edge.
    /// Not defined for just one corner.
    pub fn from_corners<'a>(a: &'a RingCornerIndex, b: &'a RingCornerIndex) -> Self {
        assert_ne!(a, b);
        let a_val: u8 = (*a).into();
        let b_val: u8 = (*b).into();
        let edge_start: RingCornerIndex =
            RingCornerIndex::try_from_primitive(u8::min(a_val, b_val)).unwrap();
        // if there is a zero-crossing, need to special-case:
        if ((*b == RingCornerIndex::BOTTOMRIGHT) && (*a == RingCornerIndex::RIGHT))
            || ((*a == RingCornerIndex::BOTTOMRIGHT) && (*b == RingCornerIndex::RIGHT))
        {
            // bottom-right edge
            return Self(5);
        } else {
            let res: RingEdge = u8::from(edge_start).into();
            debug_assert_eq!(edge_start, res.start());
            res
        }
    }

    pub fn from_primitive(p: u8) -> Self {
        Self(p % 6)
    }
}

impl RingCornerIndex {
    pub fn next(&self) -> Self {
        let v = *self as u8;
        let v2 = match v {
            0..=4 => v + 1,
            5 => 0,
            // TODO: Replace all panics and unwraps with actual error handling where possible.
            6_u8..=u8::MAX => panic!("Invalid corner index used as start."),
        };
        TryInto::<RingCornerIndex>::try_into(v2).unwrap()
    }

    pub fn all() -> impl std::iter::Iterator<Item = RingCornerIndex> {
        Self::all_from(Self::RIGHT)
    }

    // See https://blog.rust-lang.org/2024/10/17/Rust-1.82.0.html
    // the "Precise captures use" section.
    pub fn all_from(start: RingCornerIndex) -> impl std::iter::Iterator<Item = RingCornerIndex> {
        let mut ctr = start;
        let mut done = false;
        std::iter::from_fn(move || {
            ctr = ctr.next();
            if done {
                return None;
            }
            if ctr == start {
                done = true;
            };
            return Some(ctr);
        })
    }
}

impl HGSTile {
    pub fn new(tile_index: TileIndex) -> Self {
        return Self {
            h: tile_index,
            ring: Ring::new(ring_index_for_tile_index(tile_index)),
        };
    }

    /// Shorthand for creating a tile in HexGridSpiral format with TileIndex(n).
    pub fn make(tile_index: u64) -> Self {
        HGSTile::new(TileIndex(tile_index))
    }

    pub fn is_origin_tile(&self) -> bool {
        self.h == TileIndex(0)
    }

    pub fn increment_spiral(&self) -> Self {
        Self::new(self.h + TileIndex(1))
    }

    /// `steps` steps along the spiral. May be negative, but may not lead to a negative tile-index.
    pub fn spiral_steps(&self, steps: i64) -> Self {
        assert!(steps <= self.h.value() as i64);
        Self::new(TileIndex((self.h.value() as i64 + steps) as u64))
    }

    /// Moves `steps` steps along the ring, in circular fashion, counter-clockwise.
    /// May be negative; can not lead to a negative tile-index.
    pub fn ring_steps(&self, steps: i64) -> Self {
        let ring_size = self.ring.size();
        let ring_min = self.ring_min();
        let current_offset_in_ring = self.h.value() - ring_min.h.value();
        let new_offset_in_ring = (current_offset_in_ring
            + (steps.rem_euclid(ring_size as i64) as u64))
            .rem_euclid(ring_size);
        Self::new(ring_min.h + new_offset_in_ring)
    }

    pub fn decrement_spiral(&self) -> Self {
        assert!(
            self.h.value() > 0,
            "Can not decrement from the origin-tile."
        );
        Self::new(self.h - TileIndex(1))
    }

    // The maximum tile-index in the current ring.
    pub fn ring_max(&self) -> Self {
        HGSTile::new(self.ring.max())
    }

    pub fn ring_min(&self) -> Self {
        HGSTile::new(self.ring.min())
    }

    /// Edge-index on the ring, where the tile resides.
    /// Not well-defined for the origin-tile.
    pub fn ring_edge(&self) -> RingEdge {
        self.ring.edge(self.h)
    }

    pub fn cc(&self) -> CCTile {
        self.into()
    }

    pub fn spiral_index(&self) -> TileIndex {
        self.h
    }

    pub fn ring(&self) -> Ring {
        self.ring
    }
}

impl Sub<i32> for TileIndex {
    type Output = TileIndex;

    fn sub(self, rhs: i32) -> Self::Output {
        TileIndex((self.value() as i64 - rhs as i64) as u64)
    }
}

impl Ring {
    pub fn new(ring_index: RingIndex) -> Self {
        Ring { n: ring_index }
    }

    pub fn from_tile_index(tile_index: &TileIndex) -> Self {
        Ring::new(ring_index_for_tile_index(*tile_index))
    }

    pub fn next_ring(&self) -> Ring {
        Ring { n: self.n + 1 }
    }

    pub fn prev_ring(&self) -> Ring {
        assert!(self.n.value() > 0, "Cannot decrement the innermost circle.");
        Ring { n: self.n - 1 }
    }

    pub fn neighbors_in_ring(&self, tile: &HGSTile) -> Vec<HGSTile> {
        // in most cases, they are simply one up and down the tile index.
        // The exception is the case where it is the maximum or minimum entry.
        let base = ring_min(self.n);
        let h_offset = tile.h - base;
        let size = ring_size(self.n);
        let lesser_neighbor: HGSTile = HGSTile::new(base + ((h_offset - 1) % size));
        let greater_neighbor: HGSTile = HGSTile::new(base + ((h_offset + 1) % size));
        return vec![lesser_neighbor, greater_neighbor];
    }

    /// Edge size of the [Ring], counting both ends (Ring corners).
    pub fn full_edge_size(&self) -> u64 {
        return self.n.value();
    }

    pub fn size(&self) -> u64 {
        return ring_size(self.n);
    }

    pub fn min(&self) -> TileIndex {
        return ring_min(self.n);
    }

    pub fn max(&self) -> TileIndex {
        return ring_max(self.n);
    }

    /// Edge index on the ring where the Tile h resides in.
    pub fn edge(&self, h: TileIndex) -> RingEdge {
        assert!(!h.is_origin());
        // The ring-minimum has offset 1
        // The ring-maximum has offset 0.
        let b = self.min();
        let ring = Ring::from_tile_index(&h);
        let side_size = ring.full_edge_size() - 1;
        assert!(h >= b);
        let offset: u64 = (h - b).value();
        let ring_size = ring.size();
        assert!(
            offset < ring_size,
            "offset={offset:?}, ringsize={ring_size:?}, h={h:?}, ring={ring:?}"
        );
        return RingEdge::from_primitive((offset / side_size).try_into().unwrap());
    }

    /// Length of the edge of the ring, counting only one corner.
    pub fn edge_size(&self) -> u64 {
        self.full_edge_size() - 1
    }

    /// Get the c-th corner of the ring as tile index.
    pub fn corner(&self, c: RingCornerIndex) -> TileIndex {
        let val: u8 = c.into();
        // The start of the edge i is the corner at index i.
        if val == 0 {
            return self.max();
        }

        // need to make  edge_len * num_edges  steps from the starting corner.
        // The ring.min() is already at step 1.
        return self.min() + self.edge_size() * (val as u64) - 1;
    }

    pub fn random_tile_in_ring<RNG: rand::Rng>(&self, rng: &mut RNG) -> TileIndex {
        TileIndex(rng.random_range(self.min().value()..=self.max().value()))
    }

    /// Like `ring.n` but counts from zero. I.e. the Origin-Tile is in the ring 1, which has radius 0.
    pub fn radius(&self) -> u64 {
        (self.n - RingIndex::ORIGIN_RING).value()
    }

    pub fn ring_index(&self) -> RingIndex {
        self.n
    }
}

fn ring_size(n: RingIndex) -> u64 {
    // n is the edge-length with both corners. A hexagon has six sides.
    // The origin ring is the exception
    if n == RingIndex::ORIGIN_RING {
        return 1;
    }
    return (n.value() - 1) * 6;
}

// The ring-max lies always on a ring-corner tile.
fn ring_max(n: RingIndex) -> TileIndex {
    /*
     max(n) := max(n-1) + size(n)
     That leads to a sum:
     max(n) := sum_{i=1}^{n}{size(i)}
             = sum_{i=1}^{n}{6*(i-1)}
             = 6 sum_{i=0}^{n-1}{i}
     Which is known as a Triangular Number, computable in closed-form.
     max(n) := (n-1)*n/2
    */
    if n.value() == 0 {
        return TileIndex(0);
    }
    return TileIndex(3 * (n.value() - 1) * n.value());
}

/// Compute the ring-index n for the ring with the maximum element h.
/// You can also pass any other tile-index.
/// This is the inversion of ring_max.
pub fn ring_index_for_tile_index(h: TileIndex) -> RingIndex {
    // Since the equation in ring_max is quadratic, we get two potential solutions for n.
    // But one of them is, for positive h, always negative and thus invalid.
    // For a maximum it's an integer result.
    // For a nonmaximum value in the ring, it'll be lower than that integer but higher than the next-lower integer result.
    // And since the results (n) can be any integer value, it is thus always close enough to be roundable.
    return RingIndex((1. / 6. * (3. + f64::sqrt((12 * h.value() + 9) as f64))).ceil() as u64);
}

fn ring_min(n: RingIndex) -> TileIndex {
    if n == RingIndex::ORIGIN_RING {
        return TileIndex(0);
    }
    return ring_max(n - 1) + 1;
}

impl Sub<i64> for TileIndex {
    type Output = TileIndex;

    fn sub(self, rhs: i64) -> Self::Output {
        TileIndex(((self.value() as i64) - rhs) as u64)
    }
}

impl CCTile {
    pub fn new(tile_index: TileIndex) -> Self {
        HGSTile::new(tile_index).into()
    }

    pub fn make(tile_index: u64) -> Self {
        HGSTile::make(tile_index).into()
    }

    pub fn origin() -> CCTile {
        CCTile::from_qrs(0, 0, 0)
    }
    pub fn from_qrs(q: i64, r: i64, s: i64) -> CCTile {
        assert_eq!(
            q + r + s,
            0,
            "q + r + s does not sum up to zero for the tile ({q},{r},{s})!"
        );
        CCTile { q, r, s }
    }
    pub fn from_qr(q: i64, r: i64) -> CCTile {
        CCTile::from_qrs(q, r, 0 - q - r)
    }
    pub fn from_qrs_tuple(t: (i64, i64, i64)) -> CCTile {
        CCTile::from_qrs(t.0, t.1, t.2)
    }

    pub fn into_qrs_tuple(&self) -> (i64, i64, i64) {
        (self.q, self.r, self.s)
    }

    pub fn unit(direction: &RingCornerIndex) -> CCTile {
        CCTile::from_qrs_tuple(match direction {
            RingCornerIndex::RIGHT => (1, 0, -1),
            RingCornerIndex::TOPRIGHT => (1, -1, 0),
            RingCornerIndex::TOPLEFT => (0, -1, 1),
            RingCornerIndex::LEFT => (-1, 0, 1),
            RingCornerIndex::BOTTOMLEFT => (-1, 1, 0),
            RingCornerIndex::BOTTOMRIGHT => (0, 1, -1),
        })
    }

    pub fn units() -> impl Iterator<Item = CCTile> {
        RingCornerIndex::all().map(|rci| CCTile::unit(&rci))
    }

    /// `self` must be a *corner* of a ring with ring-index >= 2.
    /// Returns the corresponding direction.
    pub fn corner_to_direction(corner: &Self) -> RingCornerIndex {
        assert!(corner.is_corner());
        assert!(!corner.is_origin_tile());
        if corner.r == 0 {
            // We are on the r-axis, so it must be LEFT or RIGHT
            if corner.q > 0 {
                return RingCornerIndex::RIGHT;
            } else {
                return RingCornerIndex::LEFT;
            }
        }
        if corner.q == 0 {
            if corner.r < 0 {
                return RingCornerIndex::TOPLEFT;
            } else {
                return RingCornerIndex::BOTTOMRIGHT;
            }
        }
        if corner.s == 0 {
            if corner.q > 0 {
                return RingCornerIndex::TOPRIGHT;
            } else {
                return RingCornerIndex::BOTTOMLEFT;
            }
        }
        panic!("This can't happen. A non-origin corner tile has no axis set to 0.")
    }

    /// Returns `true`  iff the tile lies on the corner of a ring
    pub fn is_corner(&self) -> bool {
        self.q == 0 || self.r == 0 || self.s == 0
    }

    /// Adapted Euclidean Distance by
    /// Xiangguo Li
    ///
    /// <https://www.researchgate.net/publication/235779843_Storage_and_addressing_scheme_for_practical_hexagonal_image_processing>
    /// DOI <https://doi.org/10.1117/1.JEI.22.1.010502>
    ///
    /// I did not read much of the paper, but it's probably what you get when you splat the 3D-embedding cartesian coordinates to the 2D-plane.
    pub fn norm_euclidean(&self) -> f64 {
        let li = Self::origin().euclidean_distance_to(self);
        let redblob = f64::sqrt(self.norm_euclidean_sq() as f64);
        // I don't think this makes sense... why should this be equal?
        debug_assert_eq!(li, redblob as f64);
        redblob
    }

    pub fn norm_euclidean_sq(&self) -> i64 {
        self.q * self.q + self.r * self.r + self.q * self.r
    }

    /// The distance between this tile and the origin, in discrete steps.
    ///
    /// The blogpost <https://www.redblobgames.com/grids/hexagons/#distances-cube>
    /// explains this theoretically.
    /// Much easier is to observe:
    ///
    /// Along the corner axes, the distance to the origin is simply the max coordinate (absolute value).
    /// For the other entries in the ring, the maximum coordinate is the same value.
    ///
    ///
    /// Taking the maximum here is equal to computing
    /// ` (abs(q) + abs(r) + abs(s)) / 2`
    /// because we know that `q+r+s == 0` and we also know that two of the three coordinates must be of the same sign (pigeonhole principle). That means the third must be in absolute value as big as the two of the same sign. So the maximal abs is equivalent to the above.. qed.
    pub fn norm_steps(&self) -> u64 {
        self.max_coord()
    }

    fn max_coord(&self) -> u64 {
        let result = [self.q, self.r, self.s]
            .iter()
            .map(|coord| coord.abs() as u64)
            .max()
            .unwrap();
        assert!(result > 0 || *self == Self::from_qrs(0, 0, 0));
        result
    }

    /// Distance in discrete steps on the hexagonal grid.
    pub fn grid_distance_to(&self, other: &CCTile) -> u64 {
        (*self - *other).norm_steps()
    }

    /// Squared Euclidean Distance, see [Self::euclidean_distance_to]
    pub fn euclidean_distance_sq(&self, other: &CCTile) -> i64 {
        let dq = self.q - other.q;
        let dr = self.r - other.r;
        // let _li = dq * dq + dr * dr - dq * dr;
        let redblob = dq * dq + dr * dr + dq * dr;
        redblob
    }

    /// Euclidean Distance by Xiangguo Li
    /// adapted by redblobgames
    ///
    /// $$
    /// distance(a, b) := (a.q - b.q) ** 2 + (a.r - b.r) ** 2 + (a.q - b.q)(a.r - b.r)
    /// $$
    ///
    /// <https://www.researchgate.net/publication/235779843_Storage_and_addressing_scheme_for_practical_hexagonal_image_processing>
    /// DOI <https://doi.org/10.1117/1.JEI.22.1.010502>
    /// Equation 9 in section 3.3.
    ///
    /// Adaptation: <https://www.redblobgames.com/grids/hexagons/#distances-cube>
    ///
    /// Li uses "- dq * dr" in Eq. 9 while redblob uses + dq*dr.
    /// This is because the neighbors around (0,0) in Li 2013 are enumerated as
    /// `(0,1), (1, 1), (1, 0), (0, -1), (-1, -1), (-1, 0)`
    /// We (and redblob) use instead a numbering that sums to zero or one (in the first ring), never to two.
    /// `(0,-1), (1, -1), (1, 0), (0, 1), (-1, 1), (-1, 0)`
    /// It is evident that flipping our `r` axis' sign makes them equivalent.
    /// The sign flip does not matter in the squares, but propagates to the sign of `dr`.
    /// Hence we compute
    /// ```
    /// # let (dq, dr) = (1, 1);
    /// let redblob = dq * dq + dr * dr + dq * dr;
    /// ```
    /// instead of
    /// ```
    /// # let (dq, dr) = (1, 1);
    /// let _li = dq * dq + dr * dr - dq * dr;
    /// ```
    pub fn euclidean_distance_to(&self, other: &CCTile) -> f64 {
        f64::sqrt(self.euclidean_distance_sq(other) as f64)
    }

    pub fn is_origin_tile(&self) -> bool {
        self.q == 0 && self.r == 0 && self.s == 0
    }

    /// Which wedge of the grid the current tile is in.
    /// The wedges are defined as in <https://www.redblobgames.com/grids/hexagons/directions.html> in the first diagram.
    /// That is that the wedge borders go through the corners of the origin-tile, not through the corners of the HGS rings.
    /// Returns a second wedge if there are two wedges because the tile lies on their border.
    /// If so, the two wedges are sorted that the first is right before the second in counter-clockwise rotation.
    /// Returns no wedges if the tile is the origin.
    // TODO: Test this
    pub fn wedge_around_ringcorner(&self) -> Vec<RingCornerIndex> {
        // > Hex grids have six primary directions.
        // > Look at the max of |s-q|, |r-s|, |q-r|, and it will tell you which wedge you're in.
        // For the maximum, in `|a-b|` the `a` and `b` have opposite signs (except at 0,0,0).
        // If they are of equal abs value, we are on the border of a wedge. Inside the wedge, one of them is larger.
        // It's a bit more intuitive when using |q|, |r|, |s| instead but then the wedges would cross the corners.
        // TODO: understand this reasoning better.

        if self.is_origin_tile() {
            return vec![];
        }

        // positive: top-right
        let q_r = (self.q - self.r).abs();
        // positive: bottom-right
        let r_s = (self.r - self.s).abs();
        // positive: left
        let s_q = (self.s - self.q).abs();

        let rci_qr = if self.q - self.r > 0 {
            RingCornerIndex::TOPRIGHT
        } else {
            RingCornerIndex::BOTTOMLEFT
        };
        let rci_rs = if self.r - self.s > 0 {
            RingCornerIndex::BOTTOMRIGHT
        } else {
            RingCornerIndex::TOPLEFT
        };
        let rci_sq = if self.s - self.q > 0 {
            RingCornerIndex::LEFT
        } else {
            RingCornerIndex::RIGHT
        };
        let corner_indices = [rci_sq, rci_rs, rci_qr];

        let axes = [s_q, r_s, q_r];
        let mut sorted_indices = [0, 1, 2];
        sorted_indices.sort_by_key(|el| axes[*el]);
        let [_min_index, middle_index, max_index] = sorted_indices;
        let max: i64 = axes[sorted_indices[2]];
        let middle: i64 = axes[sorted_indices[1]];
        let min: i64 = axes[sorted_indices[0]];

        assert!(min <= max);
        if max > middle {
            return vec![corner_indices[max_index]];
        }

        assert_eq!(middle, max);
        // We have two wedges. Need to return them sorted consistently: the second should come ccw after the first.
        let edge =
            RingEdge::from_corners(&corner_indices[middle_index], &corner_indices[max_index]);
        return vec![edge.start(), edge.end()];
    }

    // The closest ring-corner. If tied, the previous corner in ccw direction (or the next corner in clockwise direction)
    // Might be this tile itself.
    // TODO: Test
    pub fn closest_corner_hgs(&self) -> HGSTile {
        assert!(!self.is_origin_tile());
        // get corner index
        let w = self.wedge_around_ringcorner()[0];
        // get ring radius
        let r = Ring::from(*self);
        HGSTile::new(r.corner(w))
    }

    // The previous ring-corner in ccw direction (or the next corner in clockwise direction)
    // Might be this tile itself.
    // TODO: Test
    pub fn previous_corner_cc(&self) -> CCTile {
        // TODO: This is used in converting from CCTile to HGSTile, so it may not rely on conversion to hgs.
        assert!(!self.is_origin_tile());
        let closest_corner = self.closest_corner_cc();
        if &closest_corner == self {
            return closest_corner;
        }
        let pre_closest_corner = closest_corner.rot60cw();
        // One of these must be the previous corner of self.
        // If closest_corner already is the previous corner, then the
        // pre_closest_corner will not be on the same ring-edge as self anymore.
        //
        // One the same ring-edge (and beyond, on the same line), one coordinate
        // remains constant. When we now take a turn on the ring (around a corner),
        // this coord will change.
        if self.are_colinear_with(&pre_closest_corner, &closest_corner) {
            return pre_closest_corner;
        }
        // All coordinates were different. The pre_corner is too far away.
        return closest_corner;
        // It can never happen that two coordinates match. Either one, zero, or three.

        // I believe this function could also be implemented by simply checking whether the pre_corner is colinear with the tile.
        // Which, again a belief, I think we can do simply by checking whether at least one coordinate is the same value.
        // This would need some testing though.
    }

    pub fn is_colinear_with(&self, other: &CCTile) -> bool {
        self.q == other.q || self.r == other.r || self.s == other.s
    }

    pub fn are_colinear_with(&self, other: &CCTile, third: &CCTile) -> bool {
        if other.q == third.q {
            if self.q == other.q {
                // We're on the same line as both corners, so
                // we should be in the middle of them.
                return true;
            }
        }
        if other.r == third.r {
            if self.r == other.r {
                // We're on the same line as both corners, so
                // we should be in the middle of them.
                return true;
            }
        }
        if other.s == third.s {
            if self.s == other.s {
                // We're on the same line as both corners, so
                // we should be in the middle of them.
                return true;
            }
        }
        return false;
    }

    // The closest ring-corner. If there are two, the previous in ccw direction (or the next corner in clockwise direction)
    // Might be this tile itself.
    pub fn closest_corner_cc(&self) -> CCTile {
        assert!(!self.is_origin_tile());
        // get corner index
        let w = self.wedge_around_ringcorner()[0];
        // get ring radius
        let r = Ring::from(*self);
        let direction = CCTile::unit(&w);
        direction * ((r.n.value() as i64) - 1)
    }

    /// Rotate 60 degrees counter-clockwise
    /// To rotate by other amounts, consider using spiral steps in HGSTile notation.
    /// <https://www.redblobgames.com/grids/hexagons/#rotation>
    pub fn rot60ccw(&self) -> CCTile {
        CCTile::from_qrs(-self.s, -self.q, -self.r)
    }
    /// Rotate 60 degrees clockwise
    /// <https://www.redblobgames.com/grids/hexagons/#rotation>
    pub fn rot60cw(&self) -> CCTile {
        CCTile::from_qrs(-self.r, -self.s, -self.q)
    }

    /// See <https://www.redblobgames.com/grids/hexagons/#reflection> for a
    /// visualization.
    ///
    /// This function reflects a tile across an axis.
    /// It can be ambiguous what an "axis" means, so to be clear:
    /// When reflecting along the q-Axis, we mean here that the q-coordinate stays constant.
    /// ```
    /// use hexgridspiral::CCTile;
    /// let tile = CCTile::from_qrs(4, -3, -1);
    /// let tile_r = tile.reflect_along_constant_axis(false, true, false);
    /// assert_eq!(tile_r, (-1, -3, 4).into());
    /// let tile_q = tile.reflect_along_constant_axis(true, false, false);
    /// assert_eq!(tile_q, (4, -1, -3).into());
    /// ```
    /// Applies multiple reflections if multiple orders are specified. In this case the order is Q,R,S such that
    /// ```
    /// use hexgridspiral::CCTile;
    /// let tile = CCTile::from_qrs(4, -3, -1);
    /// let tile_q = tile.reflect_along_constant_axis(true, false, false);
    /// let tile_qr = tile_q.reflect_along_constant_axis(false, true, false);
    /// let tile_qrs = tile_qr.reflect_along_constant_axis(false, false, true);
    /// let tile_direct_qrs = tile.reflect_along_constant_axis(true, true, true);
    /// assert_eq!(tile_qrs, tile_direct_qrs);
    /// ```
    /// So for readability it's probably better to just specify each seperately in sequence.
    pub fn reflect_along_constant_axis(&self, q_: bool, r_: bool, s_: bool) -> CCTile {
        // swap the coordinates that are not on the constant axis.
        let (mut q, mut r, mut s) = (self.q, self.r, self.s);
        if q_ {
            (r, s) = (s, r);
        }
        if r_ {
            (q, s) = (s, q);
        }
        if s_ {
            (q, r) = (r, q);
        }
        CCTile::from_qrs(q, r, s)
    }

    /// Reflect the tile to the other side of the line where the specified axis remains constant.
    /// Applies multiple times if multiple orders are specified, in order Q,R,S.
    /// > "To reflect over a line that's not at 0, pick a reference point on that line. Subtract the reference point, perform the reflection, then add the reference point back."
    /// > -- [](https://www.redblobgames.com/grids/hexagons/#reflection)
    // TODO: Read all comments on the redblobgames post.
    pub fn reflect_orthogonally_across_constant_axis(
        &self,
        q_: bool,
        r_: bool,
        s_: bool,
    ) -> CCTile {
        self.reflect_along_constant_axis(q_, r_, s_)
            .reflect_diagonally()
    }

    /// Reflects diagonally: along the line through this tile and the origin.
    /// The resulting tile lies on the opposite side of the origin, with the same distance.
    ///
    /// If it is unclear what this function does, check out <https://www.redblobgames.com/grids/hexagons/#reflection>.
    pub fn reflect_diagonally(&self) -> CCTile {
        CCTile::from_qrs(-self.q, -self.r, -self.s)
    }

    /// Reflects the `self` tile across the left-to-right axis that runs through the origin.
    /// ```rust
    /// let t = hexgridspiral::CCTile::from_qrs(2, -1, -1);
    /// let reflected = t.reflect_vertically();
    /// assert_eq!(reflected, (1, 1, -2).into());
    /// ```
    pub fn reflect_vertically(&self) -> CCTile {
        self.reflect_orthogonally_across_constant_axis(false, true, false)
    }

    /// Reflects the `self` tile across the top-to-bottom axis that runs through the origin.
    /// ```rust
    /// let t = hexgridspiral::CCTile::from_qrs(2, -1, -1);
    /// let reflected = t.reflect_horizontally();
    /// assert_eq!(reflected, (-1, -1, 2).into());
    /// ```
    pub fn reflect_horizontally(&self) -> CCTile {
        self.reflect_along_constant_axis(false, true, false)
    }

    /// Reflections like done with [Self::reflect_orthogonally_across_constant_axis],
    /// [Self::reflect_along_constant_axis], and [Self::reflect_diagonally], but with a reference point that is not necessarily the origin.
    ///
    /// This is done by subtracting a tile on the line (the reference point), reflecting as usual, and then adding the tile again.
    ///
    /// Usage will look like this:
    /// ```rust
    /// use hexgridspiral::CCTile;
    /// let tile1 = CCTile::from_qrs(1, -1, 0);
    /// // We want to reflect across the line where r == 1
    /// // so we choose an arbitrary tile on that line.
    /// let r = 1;
    /// let arbitrary_q = 10;
    /// let reference_point = CCTile::from_qr(arbitrary_q, r);
    ///
    /// let reflected_tile1: CCTile = tile1.reflect_with_reference_point(&reference_point,
    ///     |t: &CCTile | {t.reflect_orthogonally_across_constant_axis(false, true, false)}
    /// );
    /// assert_eq!(reflected_tile1, CCTile::from_qrs(-1, 3, -2));
    /// ```
    pub fn reflect_with_reference_point(
        &self,
        reference_point: &CCTile,
        reflection_fn: fn(&CCTile) -> CCTile,
    ) -> CCTile {
        let shifted = *self - *reference_point;
        let reflected = reflection_fn(&shifted);
        let unshifted = reflected + *reference_point;
        unshifted
    }

    pub fn spiral_steps(&self, steps: i64) -> Self {
        let ht: HGSTile = (*self).into();
        let ht2 = ht.spiral_steps(steps);
        ht2.into()
    }

    /// computes the coordinates in the plane as floats.
    /// * `unit_step` : The size of one step from a hex tile's center to its neighboring tile's center.
    /// The `unit_step` is twice the incircle radius of the hex. Or `sqrt(3) * outcircle_radius`.
    /// * `origin` : The pixel position of the origin-tile's center.
    ///
    /// The resulting pixel coordinates are in a system where positive x corresponds to [RingCornerIndex::RIGHT] and
    /// positive y corresponds to the UP-direction between ([RingCornerIndex::TOPLEFT] and [RingCornerIndex::TOPRIGHT])..
    pub fn to_pixel(&self, origin: (f64, f64), unit_step: f64) -> (f64, f64) {
        // We have point-top hexes. Call the hex inner-radius iR and the hex outer-radius oR.
        // The width (aka iR) of a hex equals sqrt(3)/2 * height (aka oR).
        // On the redblobgames website, they call the "size" what I'd call oR.
        // On the x-axis, two centers are exactly 2*iR away.
        // On the y-axis, they are not on the same x-coord, so it's different.
        // There they are 3/4 * oR away from each other.
        // oR is the outer radius of the hex circumcircle; or the edge length.
        // The unit_step is two times the height of a equilateral triangle, so
        // unit_step = sqrt(3.)/2*oR*2
        let outer_radius = unit_step / f64::sqrt(3.);
        let _redblob_size = outer_radius;
        // Walk both unit vectors.
        // Math according to https://www.redblobgames.com/grids/hexagons/#hex-to-pixel-axial
        // the unit vectors are, relative to the hex-edge length,
        // q_unit := (x = sqrt(3), y = 0) and r_unit := ( x= sqrt(3)/2, y=-3/2)
        // corresponding to q and r vectors from the origin tile to the next tile in pixels.
        // Note that the y in the r_unit basis vector should be negative because I make y go upwards, not downwards.

        // We can observe the following on an example or by looking at our unit vectors:
        // One step of incrementing q is one step along the x-axis.
        // But moving along the x-axis does not change r ... why does it contribute here?
        // Because it matters: One step of incrementing r, given a fixed q. That is also half a step along the x axis.
        let x = unit_step * ((self.q as f64) + (self.r as f64) / 2.);

        // Expressing the basis vectors in terms of unit_step:
        // One step of incrementing q given a fixed r is half a step along the y axis.
        // One step of incrementing r given a fixed q is some fraction of a step along the negative y axis.
        // To compute the fraction, look at the triangle (hex1 center, hex2 center, y-axis).
        // We know the hypotenuse (`c`) is unit_step long.
        // And the x-axis is given above.
        // Then dy = sqrt(dx^2 + c^2)
        // Or, because this is in a equilateral triangle,
        // the dy is the height thereof, so sqrt(3.)/2 * unit_step.
        // mine2:
        let y = f64::sqrt(3.) / 2. * unit_step * (-self.r as f64);

        // redblob: Equivalent to my "mine2" formula, because `redblob_size * sqrt(3) = unit_step`:
        // Unit_step is twice the height of the equilateral triangle spanned by two oR and an edge.
        //let y = redblob_size * 3. / 2. * (-self.r as f64);

        return (origin.0 + x, origin.1 + y);
    }

    pub fn hgs(&self) -> HGSTile {
        self.into()
    }

    pub fn spiral_index(&self) -> TileIndex {
        self.hgs().h
    }

    /// Wrapper around [CCTile::from_pixel_] with unit_step of size 1.
    pub fn from_pixel(pixel: (f64, f64)) -> Self {
        Self::from_pixel_(pixel, (0., 0.), 1.)
    }

    /// Inversion of the formula in [CCTile::to_pixel] and rounding to the nearest hex tile.
    /// `unit_step` determines the scaling - it is the distance between two adjacent hex tile centers, in pixel units.
    pub fn from_pixel_(pixel: (f64, f64), origin: (f64, f64), unit_step: f64) -> Self {
        let x = pixel.0 - origin.0;
        let y = pixel.1 - origin.1;
        // Based on to_pixel formulas:
        // let x = unit_step * ((self.q as f64) + (self.r as f64) / 2.);
        // let y = f64::sqrt(3.)/2.*unit_step*(-self.r as f64);
        let r = -2. / f64::sqrt(3.) * y / unit_step;
        let q = x / unit_step - (r / 2.);
        Self::round_to_nearest_tile(q, r)
    }

    // https://www.redblobgames.com/grids/hexagons/#rounding
    pub fn round_to_nearest_tile(frac_q: f64, frac_r: f64) -> Self {
        // infer s from the sum-to-zero constraint
        let frac_s: f64 = 0. - frac_q - frac_r;
        // round to nearest integer
        let mut q = f64::round(frac_q);
        let mut r = f64::round(frac_r);
        let mut s = f64::round(frac_s);

        // find error
        let q_diff = f64::abs(q - frac_q);
        let r_diff = f64::abs(r - frac_r);
        let s_diff = f64::abs(s - frac_s);

        // fix the largest error coordinate
        if q_diff > r_diff && q_diff > s_diff {
            q = -r - s
        } else if r_diff > s_diff {
            r = -q - s
        } else {
            s = -q - r
        };

        Self::from_qrs(q as i64, r as i64, s as i64)
    }

    /// Compute all reachable tiles in `steps`.
    /// Explained in <https://www.redblobgames.com/grids/hexagons/#range-coordinate> .
    pub fn movement_range(&self, steps: u64) -> MovementRange {
        let n: i64 = steps as i64;
        MovementRange {
            q_min: self.q - n,
            q_max: self.q + n,
            r_min: self.r - n,
            r_max: self.r + n,
            s_min: self.s - n,
            s_max: self.s + n,
        }
    }

    /// How big a single row step in the direction [RingCornerIndex::TOPRIGHT] is in pixels.
    /// - `unit_step`: The step size between two adjacent tile centers, in pixels (floats, not manhattan distance).
    pub fn pixel_step_vertical(unit_step: f64) -> (f64, f64) {
        // Notably, the step down is (oR + 0.5*edge), equals (1.5 * edge),
        // equals (1.5 * 2 iR/sqrt(3.)), equals (1.5 * unit_step/sqrt(3.)),
        // equals (unit_step* 3/2 /sqrt(3.)),
        // equals (unit_step * sqrt(3.) / 2).
        (unit_step, unit_step * f64::sqrt(3.) / 2.)
    }
}

/// <https://www.redblobgames.com/grids/hexagons/#range-coordinate>
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct MovementRange {
    q_min: i64,
    q_max: i64,
    r_min: i64,
    r_max: i64,
    s_min: i64,
    s_max: i64,
}
impl MovementRange {
    pub fn around(tile: &CCTile, steps: i64) -> Self {
        let n: i64 = i64::abs(steps);
        MovementRange {
            q_min: tile.q - n,
            q_max: tile.q + n,
            r_min: tile.r - n,
            r_max: tile.r + n,
            s_min: tile.s - n,
            s_max: tile.s + n,
        }
    }

    // TODO: Subtraction of two MovementRanges would also be a nice feature.

    pub fn intersect(&self, other: &MovementRange) -> MovementRange {
        // The intersection in one direction is [max_lower, min_upper].
        MovementRange {
            q_min: i64::max(self.q_min, other.q_min),
            q_max: i64::min(self.q_max, other.q_max),
            r_min: i64::max(self.r_min, other.r_min),
            r_max: i64::min(self.r_max, other.r_max),
            s_min: i64::max(self.s_min, other.s_min),
            s_max: i64::min(self.s_max, other.s_max),
        }
    }

    pub fn contains(&self, tile: &CCTile) -> bool {
        tile.q <= self.q_max
            && tile.r <= self.r_max
            && tile.s <= self.s_max
            && self.q_min <= tile.q
            && self.r_min <= tile.r
            && self.s_min <= tile.s
    }

    cfg_if::cfg_if! {if #[cfg(feature = "nightly")] {
        #[cfg(any(feature = "nightly", doc))]
        #[doc(cfg(feature = "nightly"))]
        pub fn count_tiles(&self) -> usize {
            let mut count = 0;
            for _ in *self {
                count += 1;
            }
            return count;
        }
    }
    }
}

cfg_if::cfg_if! {if #[cfg(feature = "nightly")] {
#[cfg(any(feature = "nightly", doc))]
#[doc(cfg(feature = "nightly"))]
impl IntoIterator for MovementRange {
    type Item = CCTile;
    type IntoIter = impl Iterator<Item = Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        let it = std::iter::from_coroutine(
            #[coroutine]
            move || {
                // We would loop over all values of q, r, and s, but filter out the ones that do not satisfy
                // our usual constraint ` q + r + s == 0`. This loop computes s to ensure this is fulfilled.
                //
                // We loop from min to max around our center... that would be from -N to +N. But then
                // there are some tiles we accidentally cover.
                // Along the axes, the value can deviate at most N from the center.
                // But we know that the extreme value of r on the axis where q is constant will be larger than
                // toward the top or bottom of our (hexagonal) range.
                // So if q is smaller, r may be larger, otherwise not.
                for q in (self.q_min)..=self.q_max {
                    // We loop from -N to N, so we only need to cover one side per iteration.

                    // choose the less extreme minimum
                    let r_min = i64::max(self.r_min, -q - self.s_max);
                    // choose the less extreme maximum
                    let r_max = i64::min(self.r_max, -q - self.s_min);
                    for r in r_min..=r_max {
                        #[cfg(feature = "nightly")]
                        yield CCTile::from_qr(q, r);
                    }
                }
            },
        );
        it
    }
}
}}

// Conversion from HexGridSpiral to Cube Coordinates:
// We can easily get the previous corner.
// Then add the rest.
impl From<HGSTile> for CCTile {
    fn from(item: HGSTile) -> Self {
        (&item).into()
    }
}

impl From<&HGSTile> for CCTile {
    fn from(item: &HGSTile) -> Self {
        if item.is_origin_tile() {
            return CCTile::origin();
        }
        let edge_section = item.ring_edge();
        let corner_index = edge_section.start();
        // Find the previous corner in Cube Coordinates
        // This part is straightforward because it's simply moving along an axis
        let cc_axis_unit = CCTile::unit(&corner_index);
        let cc_edge_start = cc_axis_unit * (item.ring.radius() as i64);
        // Then make steps in the edge direction
        let cc_edge_unit = CCTile::unit(&edge_section.direction());
        let corner_h = item.ring.corner(corner_index);
        if corner_h > item.h {
            // corner_h is the maximum in the ring.
            let fake_corner_h = corner_h - item.ring.size();
            let steps_from_corner = item.h - fake_corner_h;
            return cc_edge_start + cc_edge_unit * (steps_from_corner.value() as i64);
        }
        let steps_from_corner = item.h - corner_h;
        return cc_edge_start + cc_edge_unit * (steps_from_corner.value() as i64);
    }
}

impl From<&CCTile> for Ring {
    fn from(item: &CCTile) -> Self {
        Ring::new(RingIndex(item.norm_steps() + 1))
    }
}

impl From<CCTile> for Ring {
    fn from(item: CCTile) -> Self {
        (&item).into()
    }
}

impl From<&CCTile> for HGSTile {
    fn from(item: &CCTile) -> Self {
        let ring = Ring::from(item);
        let ring_index = ring.n;
        if ring.n == RingIndex::ORIGIN_RING {
            return HGSTile::new(TileIndex(0));
        }
        assert!(
            !item.is_origin_tile(),
            "This can not happen, the ring index of {item:?} is not 1. It is {ring_index:?}"
        );
        let wedges = item.wedge_around_ringcorner();
        // If the item tile is a ring-corner, there will only be one wedge. Otherwise, if it is the border of a wedge, there might be two.
        // TODO: does rust do runtime checks at release build runtime for these vecs? Just out of curiosity.
        let closest_corner_hgs = HGSTile::new(ring.corner(wedges[0]));
        // If there are two wedges, the tile lies on the diagonal axes that lie between the usual CC grid axes.
        if wedges.len() == 2 {
            // This can only happen on rings with odd full edgelengths, otherwise there is no tile on the wedge border.
            assert_eq!(ring.full_edge_size() % 2, 1);
            let corner0_hgs = closest_corner_hgs;
            let corner1_hgs = HGSTile::new(ring.corner(wedges[1]));
            // corner0_hgs is in ccw order right before corner1_hgs.
            // If corner0_hgs is the ring-maximum, we have to special-case the addition to stay in the ring.
            if corner1_hgs.h < corner0_hgs.h {
                return HGSTile::new(corner0_hgs.ring_min().h + ring.edge_size() / 2 - 1);
            } else {
                return HGSTile::new(corner0_hgs.h + ring.edge_size() / 2);
            }
        }
        assert_eq!(wedges.len(), 1);
        // We have the corner in the middle of this wedge (corner0). How do we get the correct tile's hsg index?
        let previous_corner = &item.previous_corner_cc();
        let offset_along_edge_hgs = item.grid_distance_to(previous_corner);

        // We need to find the previous_corner's hgs index.
        // We know it is a corner, so we can look up it's orientation.
        let rci = CCTile::corner_to_direction(previous_corner);
        let previous_corner_hgs = HGSTile::new(ring.corner(rci));

        // issue-1: If the previous corner happens to be the ring's maximum,
        // we need to ensure we stay in the same ring.

        return previous_corner_hgs.ring_steps(offset_along_edge_hgs as i64);
    }
}

// Conversion from Cube Coordinates to HexGridSpiral:
// TODO: Thoroughly test this.
impl From<CCTile> for HGSTile {
    fn from(item: CCTile) -> Self {
        (&item).into()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use approx_eq::assert_approx_eq;

    #[test]
    fn test_multiplication_with_unit() {
        let u = CCTile::unit(&RingCornerIndex::RIGHT);
        let two_u_mul = u * 2;
        let two_u_add = u + u;
        assert_eq!(two_u_mul, two_u_add);
        println!("Testing Tests works.");
    }

    #[test]
    fn test_hexgridspiral_cc_conversion() {
        let origin = CCTile::from_qr(0, 0);
        let tile0: HGSTile = origin.into();
        let h0 = tile0.h;
        assert_eq!(h0, TileIndex(0));

        let o_cc: CCTile = CCTile::from(HGSTile::make(9));
        let nine = CCTile::from_qr(1, -2);
        assert_eq!(nine, o_cc);
    }

    #[test]
    fn test_hexgridspiral_cc_conversion_issue1() {
        let hgs_tile = HGSTile::make(37);
        assert_eq!(hgs_tile.h, TileIndex(37), "TileIndex was wrong A1");

        // Check that the three ways to construct the CCTile(37) agree.
        let cc_37_from_hgs: CCTile = CCTile::from(HGSTile::make(37));
        let cc_37_from_qr = CCTile::from_qr(4, -1);
        assert_eq!(cc_37_from_hgs, cc_37_from_qr);
        let cc_37_from_qrs = CCTile::from_qrs(4, -1, -3);
        assert_eq!(cc_37_from_hgs, cc_37_from_qrs);

        // Get TileIndex from hgs
        let hgs_from_cc_from_hgs: HGSTile = cc_37_from_hgs.into();
        let h_37_from_cc_from_hgs = hgs_from_cc_from_hgs.h;
        assert_eq!(
            h_37_from_cc_from_hgs,
            TileIndex(37),
            "TileIndex was wrong (cc from hgs)"
        );

        // Get TileIndex from qr
        let hgs_37_from_qr: HGSTile = cc_37_from_qr.into();
        let h_37_from_qr = hgs_37_from_qr.h;
        assert_eq!(h_37_from_qr, TileIndex(37), "TileIndex was wrong (qr)");

        // Get TileIndex from qrs
        let hgs_37: HGSTile = cc_37_from_qrs.into();
        let h_37 = hgs_37.h;
        assert_eq!(h_37, TileIndex(37), "TileIndex was wrong (qrs)");
    }

    #[test]
    fn test_cc_hexgridspiral_conversion() {
        let origin = HGSTile::make(0);
        let tile0: CCTile = origin.into();
        assert_eq!(tile0, CCTile::origin());

        // after corner
        let nine = CCTile::from_qr(1, -2);
        let nine_to_hgs = nine.hgs();
        assert_eq!(nine_to_hgs, HGSTile::make(9));

        // before corner
        let seven2 = CCTile::from_qr(2, -1);
        assert_eq!(seven2.hgs(), HGSTile::make(7));

        let seven = CCTile::from_qrs(2, -1, -1);
        assert_eq!(seven.hgs(), HGSTile::make(7));

        // corner
        let eight = CCTile::from_qrs(2, -2, 0);
        assert_eq!(eight.hgs(), HGSTile::make(8));

        // before a corner, and not in the wedge of the previous corner
        let tile_a = CCTile::from_qr(1, -3);
        assert_eq!(tile_a.hgs(), HGSTile::make(23));
    }

    #[test]
    fn test_hexcount_steps_from_zero() {
        let start = HGSTile::new(TileIndex(0));
        let mut x1 = start.increment_spiral();
        for _i in 1..6 {
            x1 = x1.increment_spiral();
        }
        // we did six steps, so should be same as skipping one ring.
        let x2 = start.ring.next_ring().max();
        assert!(x1.h == x2, "Six spiral-steps should equal one ring-step in the first non-origin ring, but we got {x1} and {x2}.");
        assert!(x2.value() == 6);
    }

    #[test]
    fn test_hexcount_steps_from_one() {
        let start = HGSTile::new(TileIndex(1));
        let mut x1 = start.increment_spiral();
        for _i in 1..6 {
            x1 = x1.increment_spiral();
        }
        // we did six steps from ring_min, so should be same as skipping one ring.
        let x2 = start.ring.next_ring().min();
        assert_eq!(x1.h, x2);
    }

    #[test]
    fn test_hexcount_steps_from_seven() {
        let start = HGSTile::new(TileIndex(7));
        let mut x1 = start;
        for _i in 0..start.ring.size() {
            x1 = x1.increment_spiral();
        }
        // we did six steps from ring_min, so should be same as skipping one ring.
        let x2 = start.ring.next_ring().min();
        assert_eq!(x1.h, x2);
    }

    #[test]
    fn test_ring_max_min() {
        let min1 = ring_min(RingIndex::ORIGIN_RING.into());
        let max1 = ring_max(RingIndex::ORIGIN_RING.into());
        assert!(min1.value() == 0);
        assert!(max1.value() == 0);

        let min2 = ring_min(2.into());
        let max2 = ring_max(2.into());
        assert!(min2.value() == 1);
        assert!(max2.value() == 6, "Should be 6 but was {max1}");

        let min3 = ring_min(3.into());
        let max3 = ring_max(3.into());
        assert_eq!(min3.value(), 7);
        assert_eq!(max3.value(), 18);
    }

    #[test]
    fn test_ring_size() {
        for n in 1..10 {
            let ring = Ring::new(n.into());
            assert_eq!(ring.size(), ring.max().value() - ring.min().value() + 1);
        }
    }

    #[test]
    fn test_ring_index_for_min() {
        let a = ring_index_for_tile_index(TileIndex(0));
        let b = ring_index_for_tile_index(TileIndex(1));
        let c = ring_index_for_tile_index(TileIndex(7));
        assert_eq!(a, RingIndex(1));
        assert_eq!(b, RingIndex(2));
        assert_eq!(c, RingIndex(3));
    }

    #[test]
    fn test_ring_index_for_max() {
        let a = ring_index_for_tile_index(TileIndex(0));
        assert_eq!(a, RingIndex(1));

        let b = ring_index_for_tile_index(TileIndex(6));
        assert_eq!(b, RingIndex(2));

        let d = ring_index_for_tile_index(TileIndex(18));
        assert_eq!(d, RingIndex(3));

        let c = ring_index_for_tile_index(TileIndex(36));
        assert_eq!(c, RingIndex(4));
    }

    #[test]
    fn test_ring_index_for_any() {
        for h in 1..=6 {
            let b = ring_index_for_tile_index(TileIndex(h));
            assert_eq!(b, RingIndex(2));
        }

        for h in 19..=35 {
            let d = ring_index_for_tile_index(TileIndex(h));
            assert_eq!(d, RingIndex(4));
        }
    }

    #[test]
    fn test_ring_max() {
        let a = ring_max(RingIndex(1));
        let b = ring_max(RingIndex(2));
        let c = ring_max(RingIndex(3));
        assert_eq!(a, TileIndex(0));
        assert_eq!(b, TileIndex(6));
        assert_eq!(c, TileIndex(18));
    }

    #[test]
    fn test_wedge_around_ringcorner1() {
        // innermost ring
        let topright = CCTile::from_qr(1, -1);
        let rci_vec = topright.wedge_around_ringcorner();
        assert_eq!(rci_vec.len(), 1);
        let mut rci = rci_vec[0];
        assert_eq!(rci, RingCornerIndex::TOPRIGHT);

        rci = rci.next();
        let topleft = topright + CCTile::unit(&RingCornerIndex::LEFT);
        let rci2_vec = topleft.wedge_around_ringcorner();
        assert_eq!(rci2_vec.len(), 1);
        assert_eq!(rci2_vec[0], rci);
    }

    #[test]
    fn test_wedge_around_ringcorner2() {
        // bottom right, not on the diagonal of the wedge border
        let tile = CCTile::from_qrs(1, 3, -4);
        let rci_vec = tile.wedge_around_ringcorner();
        assert_eq!(rci_vec.len(), 1);
        let rci = rci_vec[0];
        assert_eq!(rci, RingCornerIndex::BOTTOMRIGHT);
    }

    #[test]
    fn test_wedge_around_ringcorner3() {
        // bottom left, on the diagonal where two wedges meet
        let tile = CCTile::from_qrs(-4, 2, 2);
        let rci_vec = tile.wedge_around_ringcorner();
        assert_eq!(rci_vec.len(), 2);
        // the first result should be ccw before the second
        assert_eq!(rci_vec[0], RingCornerIndex::LEFT);
        assert_eq!(rci_vec[1], RingCornerIndex::BOTTOMLEFT);
    }

    cfg_if::cfg_if! {if #[cfg(feature = "nightly")] {
    #[test]
    fn test_ring_index_for_tile_index_small() {
        for ring_index in 1..3 {
            let ring = Ring::new(ring_index.into());
            assert!(ring.n.value() > 0);
            for tile_index in ring.min()..=ring.max() {
                let ring_index_returned = ring_index_for_tile_index(tile_index);
                assert_eq!(ring_index, ring_index_returned.value());
            }
        }
    }
    }}

    #[test]
    fn test_ring_index_construction_speed() {
        for ring_index in 100000..120000 {
            // test a few random tiles
            let ring = Ring::new(ring_index.into());
            let ring_index_returned = ring_index_for_tile_index(ring.min());
            assert_eq!(ring_index, ring_index_returned.value());
        }

        for ring_index in 100000..120000 {
            // test a few random tiles
            let ring = Ring::new(ring_index.into());
            let ring_index_returned = ring_index_for_tile_index(ring.max());
            assert_eq!(ring_index, ring_index_returned.value());
        }

        for ring_index in 100..120 {
            // test a few random tiles
            let ring = Ring::new(ring_index.into());
            let mid = ring.min() + (ring.size() / 2);
            let ring_index_returned = ring_index_for_tile_index(mid);
            assert_eq!(ring_index, ring_index_returned.value());
        }
    }
    #[test]
    fn test_ring_index_for_tile_index_big() {
        let mut rng = <rand_chacha::ChaCha20Rng as rand::SeedableRng>::seed_from_u64(40);
        for ring_index in 100..120 {
            // test a few random tiles
            let ring = Ring::new(ring_index.into());
            let tile_index = ring.random_tile_in_ring(&mut rng);
            let ring_index_returned = ring_index_for_tile_index(tile_index);
            assert_eq!(ring_index, ring_index_returned.value());
        }
    }

    #[test]
    fn test_norm_steps() {
        let u1 = CCTile::unit(&RingCornerIndex::RIGHT);
        assert_eq!(u1.norm_steps(), 1);

        let u2 = u1 + u1;
        assert_eq!(u2.norm_steps(), 2);

        let t1 = CCTile::from_qrs(1, -2, 1);
        let t2 = CCTile::from_qrs(2, -2, 0);
        let t3 = CCTile::from_qrs(0, 2, -2);
        let n1 = t1.norm_steps();
        assert_eq!(n1, 2);
        assert_eq!(t2.norm_steps(), n1);
        assert_eq!(t3.norm_steps(), n1);

        assert_eq!(CCTile::from_qr(0, 0).norm_steps(), 0);

        // test several rings
        for ring_step in 1..4 {
            // tiles located opposite each other
            for direction in CCTile::units() {
                let tile_a = direction * ring_step;
                let tile_b = direction * -ring_step;
                assert_eq!(tile_a.norm_steps(), tile_b.norm_steps());
                assert_eq!(tile_a.norm_steps(), ring_step.try_into().unwrap());
            }
        }

        let tile35 = HGSTile::make(35).cc();
        assert_eq!(tile35.norm_steps(), 3);
    }

    #[test]
    fn test_ring_edge_is_ordered_ccw() {
        let ring_edge = RingEdge::from_corners(&RingCornerIndex::RIGHT, &RingCornerIndex::TOPRIGHT);
        assert_eq!(
            vec![ring_edge.start(), ring_edge.end()],
            vec![RingCornerIndex::RIGHT, RingCornerIndex::TOPRIGHT]
        );

        let ring_edge =
            RingEdge::from_corners(&RingCornerIndex::LEFT, &RingCornerIndex::BOTTOMLEFT);
        assert_eq!(
            vec![ring_edge.start(), ring_edge.end()],
            vec![RingCornerIndex::LEFT, RingCornerIndex::BOTTOMLEFT]
        );

        let ring_edge2 =
            RingEdge::from_corners(&RingCornerIndex::BOTTOMRIGHT, &RingCornerIndex::BOTTOMLEFT);
        assert_eq!(
            vec![ring_edge2.start(), ring_edge2.end()],
            vec![RingCornerIndex::BOTTOMLEFT, RingCornerIndex::BOTTOMRIGHT]
        );

        // More generally:
        for rci_a in RingCornerIndex::all() {
            let rci_b = rci_a.next();
            let ring_edge = RingEdge::from_corners(&rci_a, &rci_b);
            assert_eq!(ring_edge.start(), rci_a);
            assert_eq!(ring_edge.end(), rci_b);

            let ring_edge2 = RingEdge::from_corners(&rci_b, &rci_a);
            assert_eq!(ring_edge2.start(), rci_a);
            assert_eq!(ring_edge2.end(), rci_b);
        }
    }

    #[test]
    fn test_ring_edge() {
        let r0 = RingEdge(0);
        assert_eq!(r0.start(), RingCornerIndex::RIGHT);
        assert_eq!(r0.end(), RingCornerIndex::TOPRIGHT);

        let r1 = RingEdge::from_primitive(1);
        assert_eq!(
            vec![r1.start(), r1.end()],
            vec![RingCornerIndex::TOPRIGHT, RingCornerIndex::TOPLEFT]
        );

        let r2 = RingEdge::from_primitive(2);
        assert_eq!(
            vec![r2.start(), r2.end()],
            vec![RingCornerIndex::TOPLEFT, RingCornerIndex::LEFT]
        );

        let r3 = RingEdge::from_primitive(3);
        assert_eq!(
            vec![r3.start(), r3.end()],
            vec![RingCornerIndex::LEFT, RingCornerIndex::BOTTOMLEFT]
        );

        let r4 = RingEdge::from_primitive(4);
        assert_eq!(
            vec![r4.start(), r4.end()],
            vec![RingCornerIndex::BOTTOMLEFT, RingCornerIndex::BOTTOMRIGHT]
        );

        let r5 = RingEdge::from_primitive(5);
        assert_eq!(
            vec![r5.start(), r5.end()],
            vec![RingCornerIndex::BOTTOMRIGHT, RingCornerIndex::RIGHT]
        );

        let r6 = RingEdge::from_primitive(6);
        assert_eq!(
            vec![r6.start(), r6.end()],
            vec![RingCornerIndex::RIGHT, RingCornerIndex::TOPRIGHT]
        );
    }

    #[test]
    fn test_ring_edge_from_corners() {
        let r0 = RingEdge::from_primitive(0);
        assert_eq!(
            vec![r0.start(), r0.end()],
            vec![RingCornerIndex::RIGHT, RingCornerIndex::TOPRIGHT]
        );

        let ring_corner0: RingCornerIndex = RingCornerIndex::try_from_primitive(0).unwrap();
        let ring_corner1: RingCornerIndex = RingCornerIndex::try_from_primitive(1).unwrap();
        let r0c = RingEdge::from_corners(&ring_corner0, &ring_corner1);
        assert_eq!(
            vec![r0c.start(), r0c.end()],
            vec![RingCornerIndex::RIGHT, RingCornerIndex::TOPRIGHT]
        );

        let r0c2 = RingEdge::from_corners(&ring_corner1, &ring_corner0);
        assert_eq!(
            vec![r0c2.start(), r0c2.end()],
            vec![RingCornerIndex::RIGHT, RingCornerIndex::TOPRIGHT]
        );
    }

    #[test]
    fn test_ring_corner_index_all() {
        let a = RingCornerIndex::all().count();
        assert_eq!(a, 6);
    }

    #[test]
    fn test_rot60_cc() {
        // test all corners
        let mut i = 0;
        for r in RingCornerIndex::all_from(RingCornerIndex::BOTTOMLEFT) {
            i += 1;
            let t = CCTile::unit(&r) * i;
            let q = CCTile::unit(&r.next()) * i;
            assert_eq!(t.rot60ccw(), q);
            assert_eq!(q.rot60cw(), t);
        }

        // Also test some not-corner tiles
        for h in (1..100).step_by(7) {
            let not_corner: CCTile = HGSTile::new(TileIndex(h)).into();
            let a = not_corner.rot60cw().rot60cw().rot60cw();
            let b = not_corner.rot60ccw().rot60ccw().rot60ccw();
            assert_eq!(a, b);
        }
    }

    #[test]
    fn test_euclidean_distance() {
        let tile0 = HGSTile::make(0);
        let tile1 = CCTile::unit(&RingCornerIndex::RIGHT);
        assert_eq!(
            tile1.euclidean_distance_to(&Into::<CCTile>::into(tile0)),
            1.
        );

        let tile2 = CCTile::unit(&RingCornerIndex::TOPRIGHT);
        assert_eq!(tile1.euclidean_distance_to(&tile1), 0.);
        assert_eq!(tile1.euclidean_distance_to(&tile2), 1.);
        assert_eq!(tile2.euclidean_distance_to(&tile1), 1.);

        let tile7: CCTile = HGSTile::make(7).into();
        let tileo: CCTile = CCTile::origin();
        assert_eq!(tile7.euclidean_distance_to(&tile1), 1.);
        assert_eq!(tile7.euclidean_distance_sq(&tileo), 3);

        let tile8 = CCTile::make(8);
        assert_eq!(tile8.euclidean_distance_to(&tileo), 2.);
        assert_eq!(tile8.euclidean_distance_to(&tile7), 1.);

        let tile_minus_8 = tile8 * (-1);
        // this tile should have the same norm to the origin
        let norm8 = tile8.norm_euclidean();
        let norm8_minus = tile_minus_8.norm_euclidean();
        assert_eq!(norm8, norm8_minus);
        let norm_distance = tile8.euclidean_distance_to(&tile_minus_8);
        assert_eq!(norm_distance, 2. * norm8);
    }

    #[test]
    fn test_conversion_to_pixel() {
        {
            let tile1_cc = CCTile::make(1);
            assert_eq!(tile1_cc, CCTile::from_qr(1, -1));
            let tile1_px = tile1_cc.to_pixel((0., 0.), 1.);
            assert_eq!(tile1_px, (0.5, f64::sqrt(3.) / 2.));
        }

        let tile1_cc = CCTile::unit(&RingCornerIndex::RIGHT);
        let tile1_px = tile1_cc.to_pixel((0., 0.), 1.);
        assert_eq!(tile1_px, (1., 0.));

        let tile_right = tile1_cc * 5;
        assert_eq!(tile_right.to_pixel((1., 2.), 1.), (6., 2.));

        // Same at larger scale:
        assert_eq!(tile1_cc.to_pixel((0., 0.), 10000.), (10000., 0.));

        // Same with a tile that is not at r == 0:
        let tile2 = CCTile::unit(&RingCornerIndex::TOPLEFT);
        assert_eq!(tile2, CCTile::from_qr(0, -1));
        let tile2_px = tile2.to_pixel((0., 0.), 1.);
        let inner_radius = 0.5;
        let outer_radius = 2. / f64::sqrt(3.) * inner_radius;
        let y_should = 1.5 * outer_radius;
        assert_approx_eq!(tile2_px.0, -0.5);
        assert_approx_eq!(tile2_px.1, y_should);
        // Sanity Check that the library is not always saying it's approximately equal
        assert!(f64::abs(tile2_px.1 - y_should) < f64::EPSILON * 5.);

        // Test with a tile where both q and r are relevant, and origin and unit step are non-default.
        let tile35 = HGSTile::make(35).cc();
        let pixel35 = tile35.to_pixel((2., 3.), 4.);
        // Tile 35, aka (3, 1, -4), is 2.5 steps to the right and one step down.
        let pxstep = CCTile::pixel_step_vertical(4.);
        let should_be_pixel_35 = (2. + 2.5 * pxstep.0, 3. - pxstep.1);
        assert_eq!(pixel35, should_be_pixel_35);
    }

    #[test]
    fn test_conversion_from_pixel_and_back2() {
        let origin = (0., 0.);
        // TODO: What about other unit step sizes?
        let unit_step = 1.;

        {
            let h = TileIndex(7);
            let tile = CCTile::new(h);
            let expected_pixel_x = unit_step * 1.5;
            let expected_pixel_y = unit_step * f64::sqrt(3.) / 2.;
            let pixel = tile.to_pixel(origin, unit_step);
            assert_approx_eq!(pixel.0, expected_pixel_x);
            assert_approx_eq!(pixel.1, expected_pixel_y);
            let tile2 = CCTile::from_pixel(pixel);
            assert_eq!(tile, tile2);
        }
    }

    #[test]
    fn test_conversion_from_pixel() {
        let origin = (0., 0.);
        let unit_step = 1.;

        // Origin should be at (0,0)
        {
            let tile = CCTile::make(0);
            assert_eq!(tile.to_pixel(origin, unit_step), (0., 0.));
            assert_eq!(CCTile::from_pixel((0., 0.)), tile);
        }

        {
            let tile1 = CCTile::make(1);
            assert_eq!(CCTile::from_pixel((0.5, f64::sqrt(3.) / 2.)), tile1);
        }

        // First-ring tile
        //
        // Imagine same-sided triangles in the hex.
        // triangle_height = sqrt(3)/2. * triangle_edge
        // unit_step = 2*triangle_height
        //
        // Now imagine a same-sided triangle formed by three hexes.
        // y = big_triangle_height = sqrt(3)/2. * big_triangle_edge
        //   = sqrt(3)/2. * unit_step
        {
            let tile = CCTile::make(1);
            assert_eq!(tile, CCTile::from_qr(1, -1));
            let pixel = tile.to_pixel(origin, unit_step);
            assert_approx_eq!(pixel.0, 0.5);
            assert_approx_eq!(pixel.1, f64::sqrt(3.) / 2. * unit_step);
        }
    }

    #[test]
    fn test_conversion_from_pixel_and_back() {
        let origin = (0., 0.);
        // TODO: What about other unit step sizes?
        let unit_step = 1.;
        // TODO: Test to create from_pixel with other unit step and origin?
        // Test that to and from pixel are consistent.
        for h in [0, 1, 2, 4, 5, 6, 8, 10, 27, 100] {
            let tile = CCTile::make(h);
            let pixel = tile.to_pixel(origin, unit_step);
            let tile2 = CCTile::from_pixel(pixel);
            assert_eq!(tile, tile2);
        }
    }

    #[cfg(feature = "nightly")]
    #[test]
    fn test_movement_range() {
        for h in [0, 1, 2, 4, 5, 6, 7, 10, 27, 100] {
            let o = CCTile::make(h);
            for max_steps in 0..10 {
                let m = o.movement_range(max_steps);
                // Everything in the range must be close enough.
                for tile in m {
                    assert!(tile.grid_distance_to(&o) <= max_steps);
                }
                // Everything close enough must be in the range.
                // We check this by ensuring that the number of entries is correct.
                let collected: Vec<CCTile> = m.into_iter().collect();
                let num_tiles = collected.len() as u64;
                // num_tiles should equal the number of differently-sized rings' tiles.
                // `1 +  0 + 6 * 1 + 6 * 2 + ... + 6 * num_steps`
                // which is equal to `6 * sum_from_0_to_num_steps`.
                let s = 1 + 6 * ((0..=max_steps).sum::<u64>());
                assert_eq!(s, num_tiles);
            }
        }
    }

    #[test]
    #[cfg(feature = "nightly")]
    fn test_movement_range_intersection() {
        let tile_a = CCTile::origin() + CCTile::unit(&RingCornerIndex::LEFT);
        let tile_b = CCTile::origin() + CCTile::unit(&RingCornerIndex::RIGHT) * 2;
        //_ _ A O _ B _ _
        let range_a = tile_a.movement_range(2);
        assert!(range_a.contains(&tile_a));
        assert_eq!(range_a.contains(&CCTile::origin()), true);
        assert_eq!(range_a.count_tiles(), 19);

        let range_b = tile_b.movement_range(1);
        assert!(range_b.contains(&tile_b));
        assert_eq!(range_b.count_tiles(), 7);
        assert_eq!(range_b.contains(&CCTile::origin()), false);

        let range_ab = range_a.intersect(&range_b);
        assert_eq!(range_ab.contains(&tile_a), false);
        assert_eq!(range_ab.contains(&tile_b), false);
        assert_eq!(range_ab.contains(&CCTile::origin()), false);

        let mut num_elems = 0;
        for _elem in range_ab {
            num_elems += 1;
        }
        assert_eq!(num_elems, 1);
    }

    #[test]
    fn test_spiral_steps() {
        let ht: HGSTile = CCTile::unit(&RingCornerIndex::RIGHT).into();
        assert_eq!(ht.h.value(), 6);
        let ht_minus1 = ht.decrement_spiral();
        assert_eq!(ht_minus1.h, ht.h - 1);
        let ht2 = ht.spiral_steps(3);
        assert_eq!(ht2.h.value(), 9);
    }

    #[test]
    // used in readme, so should be correct pls
    fn readme_hgs1() {
        let tile = CCTile::from_qrs(2, -1, -1);
        assert_eq!(tile.spiral_index(), TileIndex(7));
        let tile2 = tile.spiral_steps(2);
        assert_eq!(tile2.spiral_index(), TileIndex(9));
        assert_eq!(tile2, CCTile::from_qrs(1, -2, 1));
    }

    #[test]
    fn test_reflect() {
        let tile = CCTile::from_qrs(4, -3, -1);
        let tile_r = tile.reflect_along_constant_axis(false, true, false);
        assert_eq!(tile_r, (-1, -3, 4).into());
        let tile_q = tile.reflect_along_constant_axis(true, false, false);
        assert_eq!(tile_q, (4, -1, -3).into());
        let tile_s = tile.reflect_along_constant_axis(false, false, true);
        assert_eq!(tile_s, (-3, 4, -1).into());

        let tile_reflected = tile.reflect_diagonally();
        assert_eq!(tile_reflected, (-4, 3, 1).into());

        let tile_ortho_r = tile.reflect_orthogonally_across_constant_axis(false, true, false);
        assert_eq!(tile_ortho_r, (1, 3, -4).into());
        let tile_ortho_s = tile.reflect_orthogonally_across_constant_axis(false, false, true);
        assert_eq!(tile_ortho_s, (3, -4, 1).into());
        let tile_ortho_q = tile.reflect_orthogonally_across_constant_axis(true, false, false);
        assert_eq!(tile_ortho_q, (-4, 1, 3).into());
    }

    #[test]
    fn test_grid_distance_to() {
        let tile_left = CCTile::unit(&RingCornerIndex::LEFT);
        let tile_right = CCTile::unit(&RingCornerIndex::RIGHT);
        assert_eq!(tile_left.grid_distance_to(&tile_right), 2);
        let tile1 = CCTile::from_qrs(1, 2, -3);
        assert_eq!(tile1.grid_distance_to(&tile_right), 2);
        assert_eq!(tile_right.grid_distance_to(&tile1), 2);
        assert_eq!(tile1.grid_distance_to(&tile1), 0);
        assert_eq!(tile1.grid_distance_to(&tile_left), 4);
        let tile2 = CCTile::from_qrs(-3, 2, 1);
        assert_eq!(tile2.grid_distance_to(&tile1), 4);
    }

    #[test]
    fn test_circular_steps_general() {
        for idx in 0..=10 {
            let hgs_tile = HGSTile::make(idx);
            let ring_size = hgs_tile.ring.size() as i64;

            let walk_one_circle = hgs_tile.ring_steps(ring_size);
            assert_eq!(walk_one_circle, hgs_tile);
            let walk_two_circles = hgs_tile.ring_steps(2 * ring_size);
            assert_eq!(walk_two_circles, hgs_tile);
            let walk_backwards_one_circle = hgs_tile.ring_steps(-1 * ring_size);
            assert_eq!(walk_backwards_one_circle, hgs_tile);

            let single_step_forward = hgs_tile.ring_steps(1);
            let single_step_backward_again = single_step_forward.ring_steps(-1);
            assert_eq!(single_step_backward_again, hgs_tile);
        }
    }

    #[test]
    fn test_circular_steps_specifics() {
        let hgs0 = HGSTile::make(0);
        let hgs0_plus_1 = hgs0.ring_steps(1);
        assert_eq!(
            hgs0_plus_1, hgs0,
            "The origin ring should only consist of one tile."
        );

        // Tests for circle at ring 1
        let hgs1 = HGSTile::make(1);
        let hgs1_plus_1 = hgs1.ring_steps(1);
        assert_eq!(hgs1_plus_1.h.value(), 1 + 1);
        let hgs2 = HGSTile::make(2);
        let hgs2_plus_1 = hgs2.ring_steps(1);
        assert_eq!(hgs2_plus_1.h.value(), 2 + 1);
        let hgs3 = HGSTile::make(3);
        let hgs3_plus_1 = hgs3.ring_steps(1);
        assert_eq!(hgs3_plus_1.h.value(), 3 + 1);
        let hgs4 = HGSTile::make(4);
        let hgs4_plus_1 = hgs4.ring_steps(1);
        assert_eq!(hgs4_plus_1.h.value(), 4 + 1);
        let hgs5 = HGSTile::make(5);
        let hgs5_plus_1 = hgs5.ring_steps(1);
        assert_eq!(hgs5_plus_1.h.value(), 5 + 1);
        let hgs6 = HGSTile::make(6);
        let hgs6_plus_1 = hgs6.ring_steps(1);
        assert_eq!(hgs6_plus_1.h.value(), 1);

        // Test for specific tiles
        let hgs7 = HGSTile::make(7);
        let hgs7_plus_1 = hgs7.ring_steps(1);
        assert_eq!(hgs7_plus_1.h, TileIndex(8));
        let hgs7_minus_1 = hgs7.ring_steps(-1);
        assert_eq!(hgs7_minus_1.h, TileIndex(18));

        let hgs37 = HGSTile::make(37);
        let hgs37_plus_1 = hgs37.ring_steps(1);
        assert_eq!(hgs37_plus_1.h, TileIndex(38));
        let hgs37_minus_1 = hgs37.ring_steps(-1);
        assert_eq!(hgs37_minus_1.h, TileIndex(60));

        let hgs38 = HGSTile::make(38);
        let hgs38_plus_1 = hgs38.ring_steps(1);
        assert_eq!(hgs38_plus_1.h, TileIndex(39));
        let hgs38_minus_1 = hgs38.ring_steps(-1);
        assert_eq!(hgs38_minus_1.h, TileIndex(37));

        let hgs13 = HGSTile::make(13);
        let hgs13_plus_1 = hgs13.ring_steps(1);
        assert_eq!(hgs13_plus_1.h, TileIndex(14));
        let hgs13_minus_1 = hgs13.ring_steps(-1);
        assert_eq!(hgs13_minus_1.h, TileIndex(12));
        let hgs13_plus_2 = hgs13.ring_steps(2);
        assert_eq!(hgs13_plus_2.h, TileIndex(15));
    }
}