ghast-pathfinder 0.5.6

Physics-exact path planning and path following for the ghast Minecraft Java Edition bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3): every move type is validated against the vanilla-exact ghast-physics
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
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
//! The planner: A* over feet blocks with physics-measured move costs.

use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet};

use crate::Version;
use crate::class::{Class, flag};
use crate::control::ControllerConfig;
use crate::cost::Costs;
use crate::door;
use crate::goal::{Goal, Heuristic};
use crate::jump;
use crate::moves::{
    HEIGHT, JUMP_APEX, JUMP_MARGIN, MAX_JUMP_UP, MoveKind, NodeKind, STEP, Spot, ceiling, clear,
    climb_wall, spot,
};
use crate::sim::{SimOutcome, SimReport, simulate};
use crate::world::{BlockSource, BuildKeyHasher, Grid, Sections};

/// Digging through blocks (off by default): cost per block in ticks
/// `base + ticks_per_hardness * hardness`, blocks harder than `max_hardness` are never dug.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DigCost {
    /// Fixed ticks per block (aiming, the server's confirmation).
    pub base: f64,
    /// Ticks per unit of vanilla hardness (hand on dirt ≈ 30, a good pickaxe on stone ≈ 4).
    pub ticks_per_hardness: f64,
    /// Hardest block that may be dug.
    pub max_hardness: f64,
}

impl Default for DigCost {
    fn default() -> Self {
        DigCost {
            base: 6.0,
            ticks_per_hardness: 30.0,
            max_hardness: 2.0,
        }
    }
}

/// Planner options. Build with [`Config::default`] and the `with_*` methods.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Config {
    /// Sprint on straight runs (costs assume sprinting; needs food > 6). Default on.
    pub sprint: bool,
    /// Jump over gaps: up to 3 blocks on the level, onto a block one higher or up to two
    /// lower, each only where the vanilla-exact physics lands the jump (some need sprinting).
    /// Default on.
    pub parkour: bool,
    /// Highest drop onto a floor, in blocks (3 = no fall damage). Default 3.
    pub max_fall: f64,
    /// Highest drop into water at least 2 blocks deep. Default 16.
    pub max_water_fall: f64,
    /// Swim. Default on.
    pub swim: bool,
    /// Climb ladders and vines. Default on.
    pub climb: bool,
    /// Dig through blocks in the way (default off): tunnels, jump-ups into dug space,
    /// straight down ([`MoveKind::DigDown`]) and staircases down (a [`MoveKind::Descend`]
    /// with digs). The follower digs with the held item.
    pub dig: Option<DigCost>,
    /// Place blocks, at this cost in ticks per block (default off): fill a one-deep hole,
    /// bridge over a gap (sneaking to the edge, placing against the side of the floor block),
    /// tower straight up (jump, place under the feet). The follower places the held item: the
    /// caller keeps blocks in hand.
    pub place: Option<f64>,
    /// Node budget per plan; when exhausted the best partial path is returned. Default
    /// 250 000: enough to search all the terrain a client loads at view distance 10 on a
    /// flat world (a maze whose way is far longer than the straight line needs that); at
    /// most some 30–40 MB while it runs and half a second of one desktop core.
    pub max_nodes: usize,
    /// Heuristic weight (1 = optimal; larger plans faster, slightly longer paths).
    pub heuristic_weight: f64,
    /// What the player's body can do (26.1 attributes; vanilla by default).
    pub(crate) limits: Limits,
}

/// Plan-time movement limits of the player.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Limits {
    /// Highest step walked up.
    pub(crate) step: f64,
    /// Highest block jumped onto.
    pub(crate) jump_up: f64,
    /// The measured gap-jump table applies (vanilla jump, gravity, speed and size).
    pub(crate) parkour: bool,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            step: STEP,
            jump_up: MAX_JUMP_UP,
            parkour: true,
        }
    }
}

impl Limits {
    /// The limits of a 26.1 player from its attributes and effects: step height, the apex of a
    /// standing jump (jump strength, jump boost, gravity); the gap-jump table only with vanilla
    /// jump, gravity, movement speed and scale.
    #[cfg(ghast_modern)]
    pub(crate) fn of(p: &ghast_physics::modern::PlayerState) -> Limits {
        let a = &p.attributes;
        let boost = p
            .effects
            .jump_boost
            .map_or(0.0, |amp| 0.1 * f64::from(amp + 1));
        let power = a.jump_strength.value() + boost;
        let gravity = a.gravity.value();
        let (mut y, mut v, mut apex) = (0.0f64, power, 0.0f64);
        for _ in 0..200 {
            y += v;
            apex = apex.max(y);
            v = (v - gravity) * 0.98;
            if v <= 0.0 {
                break;
            }
        }
        let eq = |x: f64, d: f64| (x - d).abs() < 1e-9;
        let vanilla = eq(a.jump_strength.value(), f64::from(0.42f32))
            && boost == 0.0
            && eq(gravity, 0.08)
            && eq(a.movement_speed.base(), f64::from(0.1f32))
            && eq(a.scale.value(), 1.0)
            && !p.effects.slow_falling
            && p.effects.levitation.is_none();
        Limits {
            step: f64::from(p.step_height()).min(STEP),
            // Room for the arc: what the vanilla jump keeps above the 1-block step (~0.25).
            jump_up: MAX_JUMP_UP.min(apex - 0.2),
            parkour: vanilla,
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            sprint: true,
            parkour: true,
            max_fall: 3.0,
            max_water_fall: 16.0,
            swim: true,
            climb: true,
            dig: None,
            place: None,
            max_nodes: 250_000,
            heuristic_weight: 1.0,
            limits: Limits::default(),
        }
    }
}

impl Config {
    /// Sprinting on or off.
    #[must_use]
    pub fn with_sprint(mut self, on: bool) -> Self {
        self.sprint = on;
        self
    }
    /// Gap jumps on or off.
    #[must_use]
    pub fn with_parkour(mut self, on: bool) -> Self {
        self.parkour = on;
        self
    }
    /// Highest drop onto a floor.
    #[must_use]
    pub fn with_max_fall(mut self, blocks: f64) -> Self {
        self.max_fall = blocks;
        self
    }
    /// Swimming on or off.
    #[must_use]
    pub fn with_swim(mut self, on: bool) -> Self {
        self.swim = on;
        self
    }
    /// Climbing on or off.
    #[must_use]
    pub fn with_climb(mut self, on: bool) -> Self {
        self.climb = on;
        self
    }
    /// Digging (None = off).
    #[must_use]
    pub fn with_dig(mut self, dig: Option<DigCost>) -> Self {
        self.dig = dig;
        self
    }
    /// Placing blocks: filling holes, bridging, towering up (cost in ticks per block; None =
    /// off).
    #[must_use]
    pub fn with_place(mut self, cost: Option<f64>) -> Self {
        self.place = cost;
        self
    }
    /// Node budget.
    #[must_use]
    pub fn with_max_nodes(mut self, n: usize) -> Self {
        self.max_nodes = n;
        self
    }
    /// Heuristic weight (>= 1).
    #[must_use]
    pub fn with_heuristic_weight(mut self, w: f64) -> Self {
        self.heuristic_weight = w.max(1.0);
        self
    }
}

/// A block to place before (or during) a step: the new block at `pos`, clicked on the face of
/// `against` toward `pos` (`against` is a neighbour of `pos`: the block below it when filling
/// a hole or towering up, the floor block beside it when bridging).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Place {
    /// Where the new block goes.
    pub pos: [i32; 3],
    /// The block whose face is clicked.
    pub against: [i32; 3],
}

impl Place {
    /// The clicked face of [`Place::against`] as a unit offset (`pos - against`): `[0, 1, 0]`
    /// is the top face.
    #[must_use]
    pub fn face(&self) -> [i32; 3] {
        [
            self.pos[0] - self.against[0],
            self.pos[1] - self.against[1],
            self.pos[2] - self.against[2],
        ]
    }
}

/// One step of a path: the feet block to reach and how.
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
    /// Feet block.
    pub pos: [i32; 3],
    /// Feet height when standing there (swim / climb steps: the block's y).
    pub feet_y: f64,
    /// The move that reaches this step from the previous one.
    pub kind: MoveKind,
    /// How the player is held up here.
    pub node: NodeKind,
    /// Blocks to break before the move (in order).
    pub dig: Vec<[i32; 3]>,
    /// Block to place before the move.
    pub place: Option<Place>,
}

impl Step {
    /// Centre of the step at feet height.
    #[must_use]
    pub fn target(&self) -> [f64; 3] {
        [
            f64::from(self.pos[0]) + 0.5,
            self.feet_y,
            f64::from(self.pos[2]) + 0.5,
        ]
    }
}

/// A planned path.
#[derive(Clone, Debug, PartialEq)]
pub struct Path {
    /// `steps[0]` is the start; the last step reaches the goal (or the best node found).
    pub steps: Vec<Step>,
    /// Estimated cost in ticks.
    pub cost: f64,
    /// The goal was not reached (node budget, unknown terrain, or unreachable): the path ends
    /// at the node closest to the goal (or, when the node budget ran out with no node closer
    /// than the start, at the most promising node not expanded yet). Replan from there.
    pub partial: bool,
    /// Nodes expanded.
    pub expanded: usize,
    /// The version the path was planned for.
    pub version: Version,
}

/// Why planning failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PlanError {
    /// The start block is not loaded.
    StartUnknown,
    /// The player cannot stand in the start block (inside a block, in lava, ...).
    StartBlocked,
    /// No node closer to the goal is reachable.
    NoPath,
}

impl std::fmt::Display for PlanError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            PlanError::StartUnknown => "start block not loaded",
            PlanError::StartBlocked => "cannot stand at the start",
            PlanError::NoPath => "no path",
        })
    }
}

impl std::error::Error for PlanError {}

/// The path planner. Cheap to clone; holds only its configuration.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Pathfinder {
    cfg: Config,
}

#[derive(Clone, Copy)]
pub(crate) struct Edge {
    pub(crate) to: [i32; 3],
    pub(crate) spot: Spot,
    pub(crate) kind: MoveKind,
    pub(crate) cost: f64,
    pub(crate) dig: [Option<[i32; 3]>; 3],
    pub(crate) place: Option<Place>,
}

/// A search node (kept small: a large search holds a few hundred thousand of them).
#[derive(Clone)]
struct Rec {
    pos: [i32; 3],
    spot: Spot,
    g: f64,
    h: f64,
    parent: u32,
    /// Index into [`SearchState::work`] of the digs / place of the move here, or `NO_WORK`.
    work: u32,
    kind: MoveKind,
    closed: bool,
}

/// [`Rec::work`] of a move without digs or places.
const NO_WORK: u32 = u32::MAX;

/// Digs and place of a move.
type Work = ([Option<[i32; 3]>; 3], Option<Place>);

#[derive(Clone, PartialEq)]
struct Open {
    f: f64,
    h: f64,
    idx: u32,
}

impl Eq for Open {}

impl PartialOrd for Open {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Open {
    fn cmp(&self, other: &Self) -> Ordering {
        // Min-heap on f, then on h (deeper nodes first).
        other
            .f
            .total_cmp(&self.f)
            .then_with(|| other.h.total_cmp(&self.h))
    }
}

/// A node key: 26 bits of x and z, 12 of y (the low 8 in bits 0-7, the high 4 in bits
/// 60-63, so heights 0..256 keep their old keys; 26.1 builds from -2048 to 2047).
#[inline]
pub(crate) fn pack(p: [i32; 3]) -> u64 {
    (p[0] as u32 as u64 & 0x3ff_ffff) << 34
        | (p[2] as u32 as u64 & 0x3ff_ffff) << 8
        | (p[1] as u8 as u64)
        | ((p[1] >> 8) as u32 as u64 & 0xf) << 60
}

impl Pathfinder {
    /// A planner with this configuration.
    #[must_use]
    pub fn new(cfg: Config) -> Self {
        Pathfinder { cfg }
    }

    /// The configuration.
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.cfg
    }

    /// The start block of a player at feet position `pos` (the block under the feet when it
    /// stands on a partial block, else the block containing the feet).
    #[must_use]
    pub fn start_block(pos: [f64; 3]) -> [i32; 3] {
        [
            pos[0].floor() as i32,
            (pos[1] + 1e-4).floor() as i32,
            pos[2].floor() as i32,
        ]
    }

    /// Plans a path from the feet block `from` to `goal`.
    ///
    /// # Errors
    /// [`PlanError`] when the start is unknown or blocked, or no node closer to the goal can
    /// be reached.
    pub fn plan<S: BlockSource + ?Sized>(
        &self,
        version: Version,
        world: &S,
        from: [i32; 3],
        goal: &Goal,
    ) -> Result<Path, PlanError> {
        self.plan_avoiding(version, world, from, goal, &HashSet::new())
    }

    /// Like [`Pathfinder::plan`], never using the moves in `banned` (`(from, to)` feet blocks).
    ///
    /// # Errors
    /// See [`Pathfinder::plan`].
    pub fn plan_avoiding<S: BlockSource + ?Sized>(
        &self,
        version: Version,
        world: &S,
        from: [i32; 3],
        goal: &Goal,
        banned: &HashSet<([i32; 3], [i32; 3])>,
    ) -> Result<Path, PlanError> {
        let mut search = self.search(version, from, goal.clone(), banned.clone());
        match search.step(world, Budget::UNLIMITED) {
            Some(r) => r,
            None => unreachable!("an unlimited slice finishes the search"),
        }
    }

    /// The same search as [`Pathfinder::plan_avoiding`], run in slices: each
    /// [`Search::step`] expands at most a [`Budget`] of nodes (and stops at its time limit),
    /// so a long plan never blocks one tick. The result is identical to the one-shot plan on
    /// the same world: the slices only pause the same A*. The world is read during the steps
    /// (a slice may see blocks that changed since the previous one).
    ///
    /// ```
    /// use std::collections::HashSet;
    /// use ghast_pathfinder::{Budget, Config, Goal, Pathfinder, Version};
    ///
    /// let mut world = ghast_physics::v1_8::memory_world();
    /// world.load_chunks(-2, -2, 2, 2);
    /// world.fill_raw([-30, 63, -30], [30, 63, 30], 1 << 4);
    /// world.fill_raw([5, 64, -20], [5, 66, 20], 1 << 4); // a wall to go around
    /// let pf = Pathfinder::new(Config::default());
    /// let mut search = pf.search(Version::V1_8, [0, 64, 0], Goal::Block([10, 64, 0]), HashSet::new());
    /// let path = loop {
    ///     // e.g. once per tick:
    ///     if let Some(r) = search.step(&world, Budget::nodes(200)) {
    ///         break r.unwrap();
    ///     }
    /// };
    /// assert_eq!(path, pf.plan(Version::V1_8, &world, [0, 64, 0], &Goal::Block([10, 64, 0])).unwrap());
    /// ```
    #[must_use]
    pub fn search(
        &self,
        version: Version,
        from: [i32; 3],
        goal: Goal,
        banned: HashSet<([i32; 3], [i32; 3])>,
    ) -> Search {
        Search {
            cfg: self.cfg.clone(),
            heur: self.heuristic(Costs::of(version)),
            version,
            from,
            goal,
            banned,
            state: None,
            result: None,
            exhausted: false,
        }
    }

    /// Plans, then runs the path through the vanilla-exact physics ([`crate::simulate`]) with
    /// a [`crate::Controller`]; a move the simulation fails is avoided and the path replanned,
    /// up to `attempts` plans. Returns the last path and its simulation: check
    /// [`SimReport::outcome`] (anything but [`crate::SimOutcome::Arrived`] means even the
    /// last plan failed in the simulation, at [`SimReport::reached`]).
    ///
    /// ```
    /// use ghast_pathfinder::{Config, Goal, Pathfinder, SimOutcome, Version};
    ///
    /// let mut world = ghast_physics::v1_8::memory_world();
    /// world.load_chunks(-1, -1, 1, 1);
    /// world.fill_raw([-10, 63, -10], [10, 63, 10], 1 << 4);
    /// let pf = Pathfinder::new(Config::default());
    /// let (path, sim) = pf.plan_verified(Version::V1_8, &world, [0, 64, 0], &Goal::Block([6, 64, 3]), 3).unwrap();
    /// assert_eq!(sim.outcome, SimOutcome::Arrived);
    /// assert!(!path.partial);
    /// ```
    ///
    /// # Errors
    /// See [`Pathfinder::plan`].
    pub fn plan_verified<S: BlockSource + ?Sized>(
        &self,
        version: Version,
        world: &S,
        from: [i32; 3],
        goal: &Goal,
        attempts: usize,
    ) -> Result<(Path, SimReport), PlanError> {
        let ctrl = ControllerConfig::default().with_sprint(self.cfg.sprint);
        self.plan_verified_avoiding(
            version,
            world,
            from,
            goal,
            &mut HashSet::new(),
            attempts,
            &ctrl,
        )
    }

    /// [`Pathfinder::plan_verified`] with moves to avoid (failed moves are added to `banned`)
    /// and the controller options the simulation uses.
    ///
    /// # Errors
    /// See [`Pathfinder::plan`].
    #[allow(clippy::too_many_arguments)]
    pub fn plan_verified_avoiding<S: BlockSource + ?Sized>(
        &self,
        version: Version,
        world: &S,
        from: [i32; 3],
        goal: &Goal,
        banned: &mut HashSet<([i32; 3], [i32; 3])>,
        attempts: usize,
        controller: &ControllerConfig,
    ) -> Result<(Path, SimReport), PlanError> {
        let mut last = None;
        for _ in 0..attempts.max(1) {
            let path = self.plan_avoiding(version, world, from, goal, banned)?;
            let sim = simulate(&path, world, controller);
            if sim.outcome == SimOutcome::Arrived {
                return Ok((path, sim));
            }
            let k = (sim.reached + 1).min(path.steps.len() - 1);
            if k == 0 || !banned.insert((path.steps[k - 1].pos, path.steps[k].pos)) {
                return Ok((path, sim));
            }
            last = Some((path, sim));
        }
        Ok(last.expect("at least one attempt"))
    }

    fn heuristic(&self, c: &Costs) -> Heuristic {
        let per_block = 1.0
            / if self.cfg.sprint {
                c.sprint_speed
            } else {
                c.walk_speed
            };
        let per_up = (c.jump_up)
            .min(1.0 / c.climb_up_speed)
            .min(1.0 / c.swim_up_speed)
            .max(1.0);
        let fall = c.fall_ticks(24.0) / 24.0;
        let per_down = fall
            .min(1.0 / c.climb_down_speed)
            .min(1.0 / c.swim_down_speed);
        Heuristic {
            per_block,
            per_up,
            per_down,
        }
    }
}

/// How much work one [`Search::step`] may do.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Budget {
    /// Most nodes to expand (at least 1).
    pub nodes: usize,
    /// Wall-clock limit, checked every 64 nodes (`None`: no limit).
    pub time: Option<std::time::Duration>,
}

impl Budget {
    /// No limit: the step finishes the search.
    pub const UNLIMITED: Budget = Budget {
        nodes: usize::MAX,
        time: None,
    };

    /// At most `n` nodes.
    #[must_use]
    pub const fn nodes(n: usize) -> Budget {
        Budget {
            nodes: n,
            time: None,
        }
    }

    /// And at most `d` of wall-clock time.
    #[must_use]
    pub const fn with_time(mut self, d: std::time::Duration) -> Budget {
        self.time = Some(d);
        self
    }
}

/// The open A* state of a [`Search`].
#[derive(Clone)]
struct SearchState {
    cache: Sections,
    recs: Vec<Rec>,
    work: Vec<Work>,
    index: HashMap<u64, u32, BuildKeyHasher>,
    open: BinaryHeap<Open>,
    best: u32,
    expanded: usize,
    edges: Vec<Edge>,
    /// Nodes reached by a placing building move so far ([`BUILDING_NODES`]).
    building: usize,
}

/// Most nodes one search reaches by placing moves (towering, bridging): far more than any real
/// path places, small next to the node budget. Digging moves are only held to progress: a deep
/// descent through solid ground has to try many columns (the dig costs dwarf the heuristic).
const BUILDING_NODES: usize = 4096;

/// How much further from the goal (in [`Goal::blocks_left`] terms) a building move may lead:
/// a sideways bridge step adds at most `sqrt(2) - 1`, a step straight away a whole block.
const BUILD_SLACK: f64 = 0.5;

/// A move that builds its own way (see [`BUILDING_NODES`]). Tunnels, jump-ups into dug space
/// and filled holes are not counted: they stay next to the terrain.
fn is_building(e: &Edge) -> bool {
    match e.kind {
        MoveKind::Pillar | MoveKind::DigDown => true,
        MoveKind::Descend => e.dig[0].is_some(),
        _ => e.place.is_some_and(|p| p.face()[1] == 0),
    }
}

/// A resumable path search ([`Pathfinder::search`]). Owns its state (`Send`, no borrows),
/// so it can live in a behaviour between ticks.
#[derive(Clone)]
pub struct Search {
    cfg: Config,
    heur: Heuristic,
    version: Version,
    from: [i32; 3],
    goal: Goal,
    banned: HashSet<([i32; 3], [i32; 3])>,
    state: Option<SearchState>,
    result: Option<Result<Path, PlanError>>,
    /// The open set ran out (every reachable node was expanded).
    exhausted: bool,
}

impl std::fmt::Debug for Search {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Search")
            .field("from", &self.from)
            .field("goal", &self.goal)
            .field("expanded", &self.expanded())
            .field("done", &self.result.is_some())
            .finish_non_exhaustive()
    }
}

impl Search {
    /// 26.1: plans with the moves the live player's attributes and effects allow (step height,
    /// jump strength, jump boost, gravity; gap jumps only with vanilla jump, gravity, movement
    /// speed and scale) instead of the vanilla ones. Call before the first [`Search::step`].
    #[cfg(ghast_modern)]
    #[must_use]
    pub fn with_modern_player(mut self, player: &ghast_physics::modern::PlayerState) -> Search {
        self.cfg.limits = Limits::of(player);
        self
    }

    /// Nodes expanded so far.
    #[must_use]
    pub fn expanded(&self) -> usize {
        self.state.as_ref().map_or(0, |s| s.expanded)
    }

    /// The start feet block.
    #[must_use]
    pub fn from(&self) -> [i32; 3] {
        self.from
    }

    /// The goal.
    #[must_use]
    pub fn goal(&self) -> &Goal {
        &self.goal
    }

    /// Whether the search has finished (the next [`Search::step`] returns the result).
    #[must_use]
    pub fn is_done(&self) -> bool {
        self.result.is_some()
    }

    /// Whether the search ended because every node reachable from the start through known
    /// (loaded) terrain was expanded, not because of the node budget
    /// ([`Config::max_nodes`]). A partial result of an exhausted search is final for the
    /// world as it is: no path to the goal exists through the loaded terrain, and the path
    /// ends at the reachable node closest to the goal.
    #[must_use]
    pub fn exhausted(&self) -> bool {
        self.exhausted
    }

    /// Runs the search for at most `budget` in `world`; the result once it is done (`None`:
    /// call again). After the result, further steps return it again.
    ///
    /// # Errors
    /// The result is the one of [`Pathfinder::plan`].
    pub fn step<S: BlockSource + ?Sized>(
        &mut self,
        world: &S,
        budget: Budget,
    ) -> Option<Result<Path, PlanError>> {
        if let Some(r) = &self.result {
            return Some(r.clone());
        }
        let started = budget.time.map(|_| std::time::Instant::now());
        let cache = self.state.as_mut().map(|s| std::mem::take(&mut s.cache));
        let mut g = match cache {
            Some(c) => Grid::with_cache(world, self.version, c),
            None => Grid::new(world, self.version),
        };
        if self.state.is_none() {
            let start = match start_spot(&mut g, self.from) {
                Ok(s) => s,
                Err(e) => {
                    self.result = Some(Err(e));
                    return self.result.clone();
                }
            };
            let h0 = self.goal.estimate(self.from, &self.heur);
            let mut st = SearchState {
                cache: Sections::default(),
                recs: Vec::with_capacity(4096),
                work: Vec::new(),
                index: HashMap::with_capacity_and_hasher(4096, BuildKeyHasher),
                open: BinaryHeap::with_capacity(4096),
                best: 0,
                expanded: 0,
                edges: Vec::with_capacity(32),
                building: 0,
            };
            st.recs.push(Rec {
                pos: self.from,
                spot: start,
                g: 0.0,
                h: h0,
                parent: u32::MAX,
                work: NO_WORK,
                kind: MoveKind::Start,
                closed: false,
            });
            st.index.insert(pack(self.from), 0);
            st.open.push(Open {
                f: h0 * self.cfg.heuristic_weight,
                h: h0,
                idx: 0,
            });
            self.state = Some(st);
        }
        let costs = Costs::of(self.version);
        let w = self.cfg.heuristic_weight;
        let st = self.state.as_mut().expect("initialised above");
        let limit = budget.nodes.max(1);
        let mut n = 0usize;
        // `Some(found)` once the search ends.
        let mut end: Option<Option<u32>> = None;
        loop {
            if n >= limit {
                break;
            }
            if n % 64 == 63
                && let (Some(t0), Some(max)) = (started, budget.time)
                && t0.elapsed() >= max
            {
                break;
            }
            let Some(Open { idx, .. }) = st.open.pop() else {
                self.exhausted = true;
                end = Some(None);
                break;
            };
            let r = &mut st.recs[idx as usize];
            if r.closed {
                continue;
            }
            r.closed = true;
            let (pos, sp, gcost) = (r.pos, r.spot, r.g);
            if self.goal.is_reached(pos) {
                end = Some(Some(idx));
                break;
            }
            st.expanded += 1;
            n += 1;
            if st.expanded > self.cfg.max_nodes {
                end = Some(None);
                break;
            }
            st.edges.clear();
            successors(
                &mut g,
                &self.cfg,
                self.version,
                costs,
                pos,
                &sp,
                &mut st.edges,
            );
            for e in &st.edges {
                if !self.banned.is_empty() && self.banned.contains(&(pos, e.to)) {
                    continue;
                }
                let ng = gcost + e.cost;
                let key = pack(e.to);
                // Building moves (towering, bridging, digging down) never away from the goal,
                // and a bounded number of placing ones per search: they open the whole sky /
                // void / ground to the search, which would otherwise expand all of it before
                // giving up on an unreachable goal. "Away" is more than [`BUILD_SLACK`] blocks
                // further: a bridge one cell sideways round an obstacle, or a staircase step
                // that trades one block across for one down, still counts as on the way.
                let building = is_building(e);
                if building
                    && self.goal.blocks_left(e.to) > self.goal.blocks_left(pos) + BUILD_SLACK
                {
                    continue;
                }
                let work = |w: &mut Vec<Work>| {
                    if e.dig[0].is_none() && e.place.is_none() {
                        NO_WORK
                    } else {
                        w.push((e.dig, e.place));
                        (w.len() - 1) as u32
                    }
                };
                match st.index.get(&key) {
                    Some(&i) => {
                        let rr = &mut st.recs[i as usize];
                        if rr.closed || ng >= rr.g - 1e-9 {
                            continue;
                        }
                        rr.g = ng;
                        rr.parent = idx;
                        rr.spot = e.spot;
                        rr.kind = e.kind;
                        let h = rr.h;
                        let wk = work(&mut st.work);
                        st.recs[i as usize].work = wk;
                        st.open.push(Open {
                            f: ng + h * w,
                            h,
                            idx: i,
                        });
                    }
                    None => {
                        if building && e.place.is_some() {
                            if st.building >= BUILDING_NODES {
                                continue;
                            }
                            st.building += 1;
                        }
                        let h = self.goal.estimate(e.to, &self.heur);
                        let i = st.recs.len() as u32;
                        let wk = work(&mut st.work);
                        st.recs.push(Rec {
                            pos: e.to,
                            spot: e.spot,
                            g: ng,
                            h,
                            parent: idx,
                            work: wk,
                            kind: e.kind,
                            closed: false,
                        });
                        st.index.insert(key, i);
                        let b = &st.recs[st.best as usize];
                        if h < b.h || (h == b.h && ng < b.g) {
                            st.best = i;
                        }
                        st.open.push(Open {
                            f: ng + h * w,
                            h,
                            idx: i,
                        });
                    }
                }
            }
        }
        st.cache = g.into_cache();
        let found = end?;
        let r = st.finish(found, self.exhausted, self.version);
        // The search state is not needed any more.
        let expanded = st.expanded;
        self.state = Some(SearchState {
            cache: Sections::default(),
            recs: Vec::new(),
            work: Vec::new(),
            index: HashMap::default(),
            open: BinaryHeap::new(),
            best: 0,
            expanded,
            edges: Vec::new(),
            building: 0,
        });
        self.result = Some(r);
        self.result.clone()
    }
}

impl SearchState {
    fn finish(
        &self,
        found: Option<u32>,
        exhausted: bool,
        version: Version,
    ) -> Result<Path, PlanError> {
        let (end, partial) = match found {
            Some(i) => (i, false),
            None if self.best != 0 => (self.best, true),
            // Out of nodes with nothing closer than the start (a dead end of a maze): the
            // most promising node not expanded yet, where the search would have gone on.
            None if !exhausted => match self
                .open
                .iter()
                .filter(|o| !self.recs[o.idx as usize].closed)
                .min_by(|a, b| a.f.total_cmp(&b.f).then(a.h.total_cmp(&b.h)))
            {
                Some(o) => (o.idx, true),
                None => return Err(PlanError::NoPath),
            },
            None => return Err(PlanError::NoPath),
        };
        let mut steps = Vec::new();
        let mut i = end;
        while i != u32::MAX {
            let r = &self.recs[i as usize];
            let (dig, place) = match self.work.get(r.work as usize) {
                Some((d, p)) => (d.iter().flatten().copied().collect(), *p),
                None => (Vec::new(), None),
            };
            steps.push(Step {
                pos: r.pos,
                feet_y: r.spot.floor,
                kind: r.kind,
                node: r.spot.kind,
                dig,
                place,
            });
            i = r.parent;
        }
        steps.reverse();
        Ok(Path {
            cost: self.recs[end as usize].g,
            steps,
            partial,
            expanded: self.expanded,
            version,
        })
    }
}

fn start_spot<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    p: [i32; 3],
) -> Result<Spot, PlanError> {
    if g.unknown(p[0], p[1], p[2]) || g.unknown(p[0], p[1] - 1, p[2]) {
        return Err(PlanError::StartUnknown);
    }
    if let Some(s) = spot(g, p[0], p[1], p[2]) {
        return Ok(s);
    }
    // Mid-air or in a place the model does not stand in: start as if standing at the block's
    // bottom if the body fits there at all.
    let base = f64::from(p[1]);
    if clear(g, p[0], p[2], base, base + HEIGHT) {
        return Ok(Spot {
            kind: NodeKind::Ground,
            floor: base,
            floor_flags: 0,
            water: false,
            submerged: false,
            climb: false,
        });
    }
    Err(PlanError::StartBlocked)
}

const CARDINALS: [(i32, i32); 4] = [(0, 1), (1, 0), (0, -1), (-1, 0)];
const DIAGONALS: [(i32, i32); 4] = [(1, 1), (1, -1), (-1, 1), (-1, -1)];

/// Extra ticks for the floor a step ends on.
fn floor_penalty(s: &Spot, per_block: f64) -> f64 {
    let mut p = 0.0;
    if s.floor_flags & flag::SLOW != 0 {
        p += per_block * 1.5;
    }
    if s.floor_flags & flag::SLIPPERY != 0 {
        p += 2.0;
    }
    if s.floor_flags & flag::BOUNCY != 0 {
        p += 12.0;
    }
    if s.submerged {
        p += 4.0;
    }
    p
}

fn dig_cost<S: BlockSource + ?Sized>(g: &mut Grid<'_, S>, d: &DigCost, p: [i32; 3]) -> Option<f64> {
    let c = g.class(p[0], p[1], p[2]);
    if !c.has(flag::SOLID) {
        return Some(0.0);
    }
    if !c.has(flag::DIGGABLE) || f64::from(c.hardness) > d.max_hardness {
        return None;
    }
    // Never open a liquid or bring down a falling block.
    if g.class(p[0], p[1] + 1, p[2])
        .has(flag::FALLING | flag::WATER | flag::LAVA)
    {
        return None;
    }
    for (dx, dz) in CARDINALS {
        if g.class(p[0] + dx, p[1], p[2] + dz)
            .has(flag::WATER | flag::LAVA)
        {
            return None;
        }
    }
    Some(d.base + d.ticks_per_hardness * f64::from(c.hardness))
}

fn push(out: &mut Vec<Edge>, to: [i32; 3], spot: Spot, kind: MoveKind, cost: f64) {
    out.push(Edge {
        to,
        spot,
        kind,
        cost,
        dig: [None; 3],
        place: None,
    });
}

/// All moves out of `p` (standing as `s`).
pub(crate) fn successors<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cfg: &Config,
    version: Version,
    c: &Costs,
    p: [i32; 3],
    s: &Spot,
    out: &mut Vec<Edge>,
) {
    moves_from(g, cfg, version, c, p, s, out);
    if g.saw_doors() {
        through_doors(g, p, s, out);
    }
}

/// [`successors`] before the door checks.
fn moves_from<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cfg: &Config,
    version: Version,
    c: &Costs,
    p: [i32; 3],
    s: &Spot,
    out: &mut Vec<Edge>,
) {
    let per_block = 1.0
        / if cfg.sprint {
            c.sprint_speed
        } else {
            c.walk_speed
        };
    let swim_block = 1.0 / c.swim_speed;
    let [x, y, z] = p;
    let f0 = s.floor;

    // Vertical moves.
    match s.kind {
        NodeKind::Swim if cfg.swim => {
            if let Some(t) = spot(g, x, y + 1, z) {
                push(
                    out,
                    [x, y + 1, z],
                    t,
                    MoveKind::Swim,
                    1.0 / c.swim_up_speed + floor_penalty(&t, per_block),
                );
            }
            if let Some(t) = spot(g, x, y - 1, z) {
                push(
                    out,
                    [x, y - 1, z],
                    t,
                    MoveKind::Swim,
                    1.0 / c.swim_down_speed,
                );
            }
        }
        NodeKind::Ground if cfg.swim && s.water => {
            // Rise out of shallow water to swim at the surface.
            if let Some(t) = spot(g, x, y + 1, z)
                && t.kind == NodeKind::Swim
            {
                push(out, [x, y + 1, z], t, MoveKind::Swim, 1.0 / c.swim_up_speed);
            }
        }
        _ => {}
    }
    if cfg.climb && s.climb {
        if let Some(t) = spot(g, x, y + 1, z)
            && t.climb
            && (climb_wall(g, x, y, z).is_some() || climbs_without_wall(version))
        {
            push(
                out,
                [x, y + 1, z],
                t,
                MoveKind::ClimbUp,
                1.0 / c.climb_up_speed,
            );
        }
        if s.kind == NodeKind::Climb
            && let Some(t) = spot(g, x, y - 1, z)
            && (t.climb || t.kind == NodeKind::Ground)
        {
            push(
                out,
                [x, y - 1, z],
                t,
                MoveKind::ClimbDown,
                1.0 / c.climb_down_speed,
            );
        }
    }

    // Dig out the floor and fall onto the next one below.
    if s.kind == NodeKind::Ground
        && !s.water
        && let Some(d) = &cfg.dig
    {
        dig_down(g, cfg, d, c, p, f0, out);
    }
    // Tower up: jump, place a block under the feet.
    if s.kind == NodeKind::Ground
        && !s.water
        && let Some(pc) = cfg.place
    {
        pillar(g, pc, c, p, s, out);
    }

    let swimming = s.kind == NodeKind::Swim;
    let climbing = s.kind == NodeKind::Climb;
    if (swimming && !cfg.swim) || (climbing && !cfg.climb) {
        return;
    }

    // Cardinal moves.
    for (dx, dz) in CARDINALS {
        let (bx, bz) = (x + dx, z + dz);
        let mut found = false;
        // One block up: step-up, jump-up, swim out, climb off.
        if let Some(t) = spot(g, bx, y + 1, bz)
            && t.kind == NodeKind::Ground
        {
            let dh = t.floor - f0;
            if climbing {
                if dh <= 1.5 + 1e-6 && clear(g, x, z, f0 + HEIGHT, t.floor + HEIGHT) {
                    push(
                        out,
                        [bx, y + 1, bz],
                        t,
                        MoveKind::ClimbExit,
                        1.0 / c.climb_up_speed + per_block + floor_penalty(&t, per_block),
                    );
                    found = true;
                }
            } else if swimming || s.water {
                if dh <= 1.2 && clear(g, x, z, f0 + HEIGHT, t.floor + HEIGHT + 0.4) {
                    push(
                        out,
                        [bx, y + 1, bz],
                        t,
                        MoveKind::Swim,
                        swim_block + c.jump_up + floor_penalty(&t, per_block),
                    );
                    found = true;
                }
            } else if dh <= cfg.limits.step + 1e-6 {
                if clear(g, x, z, f0 + HEIGHT, t.floor + HEIGHT) {
                    push(
                        out,
                        [bx, y + 1, bz],
                        t,
                        MoveKind::Walk,
                        per_block + 0.5 + floor_penalty(&t, per_block),
                    );
                    found = true;
                }
            } else if dh <= cfg.limits.jump_up && jump_room(g, x, z, bx, bz, f0, &t) {
                push(
                    out,
                    [bx, y + 1, bz],
                    t,
                    MoveKind::Ascend,
                    c.jump_up + floor_penalty(&t, per_block),
                );
                found = true;
            }
        }
        // Dig through to reach the step above (jump-up into a tunnel).
        if !found
            && !swimming
            && !climbing
            && let Some(d) = &cfg.dig
            && (f0 - f64::from(y)).abs() < 1e-6
        {
            found |= dig_up(g, d, c, p, (dx, dz), out);
        }
        if found {
            continue;
        }
        // Same level and drops.
        let lowest = y - (cfg.max_fall.max(cfg.max_water_fall).ceil() as i32) - 1;
        let mut yt = y;
        while yt >= lowest.max(g.y_range().0 + 1) {
            if let Some(t) = spot(g, bx, yt, bz) {
                let dh = t.floor - f0;
                let top = t.floor.max(f0) + HEIGHT;
                if dh > cfg.limits.step + 1e-6 {
                    // A higher floor in the same block (soul sand, a slab on a step).
                    if !swimming
                        && !climbing
                        && dh <= cfg.limits.jump_up
                        && jump_room(g, x, z, bx, bz, f0, &t)
                    {
                        push(
                            out,
                            [bx, yt, bz],
                            t,
                            MoveKind::Ascend,
                            c.jump_up + floor_penalty(&t, per_block),
                        );
                    } else if (swimming || s.water) && dh <= 1.2 {
                        push(out, [bx, yt, bz], t, MoveKind::Swim, swim_block + c.jump_up);
                    }
                } else if dh >= -STEP - 1e-6 {
                    let kind = if swimming || t.kind == NodeKind::Swim || (s.water && t.water) {
                        MoveKind::Swim
                    } else {
                        MoveKind::Walk
                    };
                    let ok = match t.kind {
                        NodeKind::Swim => cfg.swim,
                        NodeKind::Climb => cfg.climb,
                        NodeKind::Ground => true,
                    };
                    if ok
                        && clear(g, x, z, f0 + HEIGHT, top)
                        && clear(g, bx, bz, t.floor + HEIGHT, top)
                    {
                        let cost = if kind == MoveKind::Swim {
                            swim_block
                        } else {
                            per_block
                        };
                        push(
                            out,
                            [bx, yt, bz],
                            t,
                            kind,
                            cost + floor_penalty(&t, per_block),
                        );
                    }
                } else if t.kind == NodeKind::Climb && cfg.climb && -dh <= 1.5 + 1e-6 {
                    // Onto a ladder from above: fall into it and hold on.
                    if clear(g, bx, bz, t.floor + HEIGHT, f0 + HEIGHT) {
                        push(
                            out,
                            [bx, yt, bz],
                            t,
                            MoveKind::ClimbDown,
                            per_block + (-dh) / c.climb_down_speed,
                        );
                    }
                } else if !climbing {
                    let drop = -dh;
                    let deep = t.kind == NodeKind::Swim && g.class(bx, yt - 1, bz).has(flag::WATER);
                    let into_water = t.kind == NodeKind::Swim || t.water;
                    let limit = if deep {
                        cfg.max_water_fall
                    } else {
                        cfg.max_fall
                    };
                    let landing_ok = t.floor_flags & (flag::FRAGILE | flag::BOUNCY) == 0;
                    if drop <= limit + 1e-6
                        && landing_ok
                        && (cfg.swim || !into_water)
                        && t.kind != NodeKind::Climb
                        && clear(g, bx, bz, t.floor + HEIGHT, f0 + HEIGHT)
                    {
                        push(
                            out,
                            [bx, yt, bz],
                            t,
                            MoveKind::Descend,
                            per_block + c.fall_ticks(drop) + 2.0 + floor_penalty(&t, per_block),
                        );
                    }
                }
                found = true;
                break;
            }
            // Keep falling only through cells the body passes.
            if !clear(g, bx, bz, f64::from(yt), f64::from(yt) + 1.0) {
                break;
            }
            yt -= 1;
        }
        if !found
            && !swimming
            && !climbing
            && let Some(d) = &cfg.dig
        {
            dig_through(g, d, per_block, p, f0, (dx, dz), out);
            dig_stair(g, d, c, per_block, p, f0, (dx, dz), out);
        }
        if !found && !swimming && !climbing && g.saw_doors() {
            open_block(g, version, per_block, p, f0, (dx, dz), out);
        }
        // Filling a one-deep hole competes with dropping into it.
        if !swimming
            && !climbing
            && let Some(pc) = cfg.place
            && spot(g, bx, y, bz).is_none()
            && !fill_hole(g, pc, per_block, p, f0, (dx, dz), out)
        {
            bridge(g, pc, per_block, p, s, (dx, dz), out);
        }
        if cfg.parkour
            && cfg.limits.parkour
            && !swimming
            && !climbing
            && s.kind == NodeKind::Ground
            && !s.water
        {
            parkour(g, cfg, version, p, s, (dx, dz), out);
        }
    }

    // Diagonals (flat-ish only).
    if climbing {
        return;
    }
    for (dx, dz) in DIAGONALS {
        let (bx, bz) = (x + dx, z + dz);
        for yt in [y + 1, y, y - 1] {
            let Some(t) = spot(g, bx, yt, bz) else {
                continue;
            };
            let dh = t.floor - f0;
            if dh > cfg.limits.step + 1e-6 || dh < -STEP - 1e-6 {
                if yt == y {
                    break;
                }
                continue;
            }
            if (t.kind == NodeKind::Swim) != swimming {
                break;
            }
            let lo = t.floor.max(f0);
            let hi = lo + HEIGHT;
            // The box crosses both side columns: each needs a floor near the path's (a hole
            // beside the corner catches a box that strays from the diagonal).
            let floored = |g: &mut Grid<'_, S>, sx: i32, sz: i32| {
                [y, yt].iter().any(|&yy| {
                    spot(g, sx, yy, sz).is_some_and(|sp| {
                        sp.kind == NodeKind::Ground && sp.floor >= t.floor.min(f0) - STEP - 1e-6
                    })
                })
            };
            if !swimming && (!floored(g, x + dx, z) || !floored(g, x, z + dz)) {
                break;
            }
            if clear(g, x + dx, z, lo, hi)
                && clear(g, x, z + dz, lo, hi)
                && clear(g, x, z, f0 + HEIGHT, hi)
                && clear(g, bx, bz, t.floor + HEIGHT, hi)
            {
                let base = if swimming || (s.water && t.water) {
                    swim_block
                } else {
                    per_block
                };
                let kind = if swimming || (s.water && t.water) {
                    MoveKind::Swim
                } else {
                    MoveKind::Diagonal
                };
                push(
                    out,
                    [bx, yt, bz],
                    t,
                    kind,
                    base * std::f64::consts::SQRT_2
                        + floor_penalty(&t, per_block)
                        + if dh > 1e-6 { 0.5 } else { 0.0 },
                );
            }
            break;
        }
    }
}

/// Room for a standing jump from `f0` in column (x, z) onto `t` in column (bx, bz).
fn jump_room<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    x: i32,
    z: i32,
    bx: i32,
    bz: i32,
    f0: f64,
    t: &Spot,
) -> bool {
    let top = f0 + HEIGHT + JUMP_APEX;
    let ca = ceiling(g, x, z, f0 + HEIGHT, top);
    let cb = ceiling(g, bx, bz, t.floor + HEIGHT, top);
    let apex = ca.min(cb) - HEIGHT - f0;
    apex >= (t.floor - f0) + JUMP_MARGIN
}

/// Gap jumps from `p` in direction `d`: over 1 to 4 columns onto a block up to one higher or
/// two lower, each only in a mode validated in the physics (see [`crate::jump`]) and only
/// where every cell the body sweeps in that mode is free.
fn parkour<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cfg: &Config,
    version: Version,
    p: [i32; 3],
    s: &Spot,
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) {
    let [x, y, z] = p;
    // Exact full-block floors with ordinary friction at the take-off.
    if (s.floor - f64::from(y)).abs() > 1e-6 || !jump::plain_floor(g.class(x, y - 1, z)) {
        return;
    }
    // Something to walk onto (or step up onto) next to the take-off: no gap.
    let walkable = |g: &mut Grid<'_, S>, cx: i32, cz: i32| {
        [y + 1, y].iter().any(|&yy| {
            spot(g, cx, yy, cz).is_some_and(|t| (t.floor - s.floor).abs() <= STEP + 1e-6)
        })
    };
    if walkable(g, x + dx, z + dz) {
        return;
    }
    let jumps = jump::Jumps::of(version);
    for gap in 1..=jumps.widest() {
        // A floor at the take-off level ends the run of gaps: walk there, jump from there.
        if gap > 1 && walkable(g, x + dx * i32::from(gap), z + dz * i32::from(gap)) {
            return;
        }
        let a = i32::from(gap) + 1;
        let (tx, tz) = (x + dx * a, z + dz * a);
        for dy in jump::DYS {
            let ty = y + i32::from(dy);
            let Some(t) = spot(g, tx, ty, tz) else {
                continue;
            };
            if t.kind != NodeKind::Ground
                || t.water
                || (t.floor - f64::from(ty)).abs() > 1e-6
                || !jump::plain_floor(g.class(tx, ty - 1, tz))
            {
                continue;
            }
            let Some(spec) = jump::select(&jumps, p, (dx, dz), gap, dy, cfg.sprint, |q| {
                g.class(q[0], q[1], q[2])
            }) else {
                continue;
            };
            if f64::from(spec.fall) > cfg.max_fall + 1e-6 {
                continue;
            }
            push(
                out,
                [tx, ty, tz],
                t,
                MoveKind::Parkour { gap },
                f64::from(spec.cost),
            );
        }
    }
}

/// Extra ticks of a door move: the click, the server's answer.
const DOOR_TICKS: f64 = 8.0;

/// The door slabs ([`flag::PANEL`]) in column (x, z) between heights `lo` and `hi`
/// (absolute): `(y, class)`, at most four.
fn panels_in<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    x: i32,
    z: i32,
    lo: f64,
    hi: f64,
) -> ([(i32, Class); 4], usize) {
    let mut out = [(0, Class::UNKNOWN); 4];
    let mut n = 0;
    for y in lo.floor() as i32..=(hi - 1e-6).floor() as i32 {
        let c = g.class(x, y, z);
        if c.has(flag::PANEL) && n < 4 {
            out[n] = (y, c);
            n += 1;
        }
    }
    (out, n)
}

/// Door slabs: keeps a move only when it crosses none of them, turns a walk through one
/// closed (or swung-into-the-way) wooden door into a [`MoveKind::Door`] move, and drops every
/// other move touching a door cell that is not a straight cardinal one.
fn through_doors<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    p: [i32; 3],
    s: &Spot,
    out: &mut Vec<Edge>,
) {
    let [x, _, z] = p;
    let mut i = 0;
    while i < out.len() {
        let e = out[i];
        let (dx, dz) = (e.to[0] - x, e.to[2] - z);
        if dx == 0 && dz == 0 {
            // Straight up or down at the centre: a side slab is never in the way.
            i += 1;
            continue;
        }
        let lo = s.floor.min(e.spot.floor);
        let hi = s.floor.max(e.spot.floor) + HEIGHT;
        let (from, nf) = panels_in(g, x, z, lo, hi);
        let (to, nt) = panels_in(g, e.to[0], e.to[2], lo, hi);
        if nf == 0 && nt == 0 {
            i += 1;
            continue;
        }
        let keep = if dx.abs() + dz.abs() != 1 || matches!(e.kind, MoveKind::Parkour { .. }) {
            false
        } else {
            let (out_wall, in_wall) = (door::wall_of(dx, dz), door::wall_of(-dx, -dz));
            let mut blocker: Option<([i32; 3], bool)> = None;
            let mut many = false;
            for (col, list, n, wall) in [
                ([x, z], &from, nf, out_wall),
                ([e.to[0], e.to[2]], &to, nt, in_wall),
            ] {
                for &(y, c) in &list[..n] {
                    if c.wall != wall {
                        continue;
                    }
                    let at = [col[0], y, col[1]];
                    // Doors and gates only: a trapdoor's slab across the way lies flat once
                    // clicked, which this move does not model.
                    let open = c.has(flag::OPENABLE) && !c.has(flag::HATCH);
                    match blocker {
                        None => blocker = Some((at, open)),
                        Some((b, o)) => {
                            // Both halves of one door: click the lower one.
                            if b[0] == at[0] && b[2] == at[2] {
                                blocker = Some((if at[1] < b[1] { at } else { b }, o && open));
                            } else {
                                many = true;
                            }
                        }
                    }
                }
            }
            match blocker {
                None => true,
                Some((at, true))
                    if !many
                        && e.kind == MoveKind::Walk
                        && e.dig[0].is_none()
                        && e.place.is_none() =>
                {
                    out[i].kind = MoveKind::Door { block: at };
                    out[i].cost += DOOR_TICKS;
                    true
                }
                Some(_) => false,
            }
        };
        if keep {
            i += 1;
        } else {
            out.remove(i);
        }
    }
}

/// Through a closed fence gate or a trapdoor in the neighbour (bx, y, bz) at feet or head
/// height: click it, walk in, where its clicked state lets the body through (a trapdoor swings
/// to a side; across the way it would still block).
fn open_block<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    version: Version,
    per_block: f64,
    p: [i32; 3],
    f0: f64,
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) {
    let [x, y, z] = p;
    if (f0 - f64::from(y)).abs() > 1e-6 {
        return;
    }
    let (bx, bz) = (x + dx, z + dz);
    let entry = door::wall_of(-dx, -dz);
    // The body's part of each cell, and whether a class lets it pass.
    let passes = |c: &Class, hi: f32| {
        !c.blocks_standing(0.0, hi) && !(c.has(flag::PANEL) && c.wall == entry)
    };
    let mut blocker = None;
    for (yy, hi) in [(y, 1.0f32), (y + 1, (HEIGHT - 1.0) as f32)] {
        let c = g.class(bx, yy, bz);
        if c.has(flag::AVOID | flag::LAVA) {
            return;
        }
        if passes(&c, hi) {
            continue;
        }
        if !c.has(flag::OPENABLE) || blocker.is_some() {
            return;
        }
        blocker = Some((yy, hi));
    }
    let Some((yy, hi)) = blocker else {
        return;
    };
    let fl = g.class(bx, y - 1, bz);
    if !fl.has(flag::SUPPORT)
        || fl.has(flag::IRREGULAR | flag::AVOID_FLOOR)
        || fl.top < 1.0 - 1e-6
        || fl.top_any > 1.0 + 1e-6
    {
        return;
    }
    match door::toggled_class(version, g.source(), [bx, yy, bz]) {
        Some(after) if passes(&after, hi) => {}
        _ => return,
    }
    out.push(Edge {
        to: [bx, y, bz],
        spot: Spot {
            kind: NodeKind::Ground,
            floor: f0,
            floor_flags: fl.flags,
            water: false,
            submerged: false,
            climb: false,
        },
        kind: MoveKind::Door {
            block: [bx, yy, bz],
        },
        cost: per_block + DOOR_TICKS,
        dig: [None; 3],
        place: None,
    });
}

/// Tunnel: walk into the neighbour at the same level after digging its body blocks.
fn dig_through<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    d: &DigCost,
    per_block: f64,
    p: [i32; 3],
    f0: f64,
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) -> bool {
    let [x, y, z] = p;
    if (f0 - f64::from(y)).abs() > 1e-6 {
        return false;
    }
    let (bx, bz) = (x + dx, z + dz);
    let fl = g.class(bx, y - 1, bz);
    if !(fl.has(flag::SUPPORT) && fl.top >= 1.0 - 1e-6 && fl.top_any <= 1.0 + 1e-6)
        || fl.has(flag::AVOID_FLOOR | flag::IRREGULAR)
    {
        return false;
    }
    let mut cost = per_block;
    let mut dig = [None; 3];
    let mut n = 0;
    for yy in [y + 1, y] {
        let c = g.class(bx, yy, bz);
        if g.unknown(bx, yy, bz) || c.has(flag::AVOID | flag::LAVA | flag::WATER) {
            return false;
        }
        if c.has(flag::SOLID) {
            match dig_cost(g, d, [bx, yy, bz]) {
                Some(k) => {
                    cost += k;
                    dig[n] = Some([bx, yy, bz]);
                    n += 1;
                }
                None => return false,
            }
        }
    }
    if n == 0 {
        return false;
    }
    let spot = Spot {
        kind: NodeKind::Ground,
        floor: f0,
        floor_flags: fl.flags,
        water: false,
        submerged: false,
        climb: false,
    };
    out.push(Edge {
        to: [bx, y, bz],
        spot,
        kind: MoveKind::Walk,
        cost,
        dig,
        place: None,
    });
    true
}

/// Dig out the full block under the feet at `p` and fall straight down onto the next full
/// floor, at most [`Config::max_fall`] below. Never into a liquid, onto a hazard or a fragile /
/// bouncy floor, or through unknown blocks; the dig itself follows [`dig_cost`] (no liquid next
/// to the block, nothing falling onto the player).
fn dig_down<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cfg: &Config,
    d: &DigCost,
    c: &Costs,
    p: [i32; 3],
    f0: f64,
    out: &mut Vec<Edge>,
) {
    let [x, y, z] = p;
    if (f0 - f64::from(y)).abs() > 1e-6 {
        return;
    }
    let below = [x, y - 1, z];
    let fl = g.class(x, y - 1, z);
    if !fl.has(flag::SUPPORT) || fl.has(flag::IRREGULAR) || fl.top < 1.0 - 1e-6 {
        return;
    }
    let Some(k) = dig_cost(g, d, below) else {
        return;
    };
    // Fall through the dug cell (feet there first) until a full floor carries the player.
    let lowest = (y - cfg.max_fall.floor() as i32).max(g.y_range().0 + 1);
    let mut yt = y - 1;
    while yt >= lowest {
        if yt < y - 1 {
            // The cell the feet fall into (the dug cell itself needs no check).
            let c0 = g.class(x, yt, z);
            if c0.has(flag::SOLID | flag::WATER | flag::LAVA | flag::AVOID | flag::CLIMB) {
                return;
            }
        }
        let cb = g.class(x, yt - 1, z);
        if cb.has(flag::WATER | flag::LAVA | flag::AVOID | flag::CLIMB) {
            return;
        }
        if cb.has(flag::SOLID) {
            if !cb.has(flag::SUPPORT)
                || cb.has(flag::IRREGULAR | flag::AVOID_FLOOR | flag::FRAGILE | flag::BOUNCY)
                || cb.top < 1.0 - 1e-6
                || cb.top_any > 1.0 + 1e-6
            {
                return;
            }
            let drop = f64::from(y - yt);
            out.push(Edge {
                to: [x, yt, z],
                spot: Spot {
                    kind: NodeKind::Ground,
                    floor: f64::from(yt),
                    floor_flags: cb.flags,
                    water: false,
                    submerged: false,
                    climb: false,
                },
                kind: MoveKind::DigDown,
                // Centring over the block, the dig, the fall and landing.
                cost: k + c.fall_ticks(drop) + 4.0,
                dig: [Some(below), None, None],
                place: None,
            });
            return;
        }
        yt -= 1;
    }
}

/// Staircase down: dig what is in the way in the neighbour column (the cell the head passes,
/// then the body's two cells one lower) and step down one block onto its floor. No fall
/// damage at any depth; every dig follows [`dig_cost`]. A [`MoveKind::Descend`] with digs.
#[allow(clippy::too_many_arguments)]
fn dig_stair<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    d: &DigCost,
    c: &Costs,
    per_block: f64,
    p: [i32; 3],
    f0: f64,
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) -> bool {
    let [x, y, z] = p;
    if (f0 - f64::from(y)).abs() > 1e-6 || y - 1 <= g.y_range().0 {
        return false;
    }
    let (bx, bz) = (x + dx, z + dz);
    let fl = g.class(bx, y - 2, bz);
    if !fl.has(flag::SUPPORT)
        || fl.has(flag::IRREGULAR | flag::AVOID_FLOOR | flag::FRAGILE | flag::BOUNCY | flag::WATER)
        || fl.top < 1.0 - 1e-6
        || fl.top_any > 1.0 + 1e-6
    {
        return false;
    }
    let mut cost = per_block + c.fall_ticks(1.0) + 2.0;
    let mut dig = [None; 3];
    let mut n = 0;
    for yy in [y + 1, y, y - 1] {
        let q = [bx, yy, bz];
        let cl = g.class(q[0], q[1], q[2]);
        if g.unknown(q[0], q[1], q[2]) || cl.has(flag::AVOID | flag::LAVA | flag::WATER) {
            return false;
        }
        if cl.has(flag::SOLID) {
            match dig_cost(g, d, q) {
                Some(k) => {
                    cost += k;
                    dig[n] = Some(q);
                    n += 1;
                }
                None => return false,
            }
        }
    }
    if n == 0 {
        return false;
    }
    out.push(Edge {
        to: [bx, y - 1, bz],
        spot: Spot {
            kind: NodeKind::Ground,
            floor: f0 - 1.0,
            floor_flags: fl.flags,
            water: false,
            submerged: false,
            climb: false,
        },
        kind: MoveKind::Descend,
        cost,
        dig,
        place: None,
    });
    true
}

/// Jump up into the neighbour one block higher after digging what is in the way.
fn dig_up<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    d: &DigCost,
    c: &Costs,
    p: [i32; 3],
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) -> bool {
    let [x, y, z] = p;
    let (bx, bz) = (x + dx, z + dz);
    let fl = g.class(bx, y, bz);
    if !(fl.has(flag::SUPPORT) && fl.top >= 1.0 - 1e-6 && fl.top_any <= 1.0 + 1e-6)
        || fl.has(flag::AVOID_FLOOR | flag::IRREGULAR)
    {
        return false;
    }
    // Needs: (x, y+2) above the origin (the jump), (bx, y+1), (bx, y+2) for the body.
    let cells = [[x, y + 2, z], [bx, y + 2, bz], [bx, y + 1, bz]];
    let mut cost = c.jump_up;
    let mut dig = [None; 3];
    let mut n = 0;
    for q in cells {
        let cl = g.class(q[0], q[1], q[2]);
        if g.unknown(q[0], q[1], q[2]) || cl.has(flag::AVOID | flag::LAVA | flag::WATER) {
            return false;
        }
        if cl.has(flag::SOLID) {
            match dig_cost(g, d, q) {
                Some(k) => {
                    cost += k;
                    dig[n] = Some(q);
                    n += 1;
                }
                None => return false,
            }
        }
    }
    if n == 0 {
        return false;
    }
    // Headroom above the dug space for the jump arc (y + 3 at the origin and target).
    let f0 = f64::from(y);
    let t_floor = f0 + 1.0;
    let arc = (f0 + HEIGHT + JUMP_APEX - (f0 + 3.0)) as f32;
    if g.class(x, y + 3, z).blocks_between(0.0, arc)
        || g.class(bx, y + 3, bz).blocks_between(0.0, arc)
    {
        return false;
    }
    let spot = Spot {
        kind: NodeKind::Ground,
        floor: t_floor,
        floor_flags: fl.flags,
        water: false,
        submerged: false,
        climb: false,
    };
    out.push(Edge {
        to: [bx, y + 1, bz],
        spot,
        kind: MoveKind::Ascend,
        cost,
        dig,
        place: None,
    });
    true
}

/// Walk over a one-deep hole after placing a block into it.
fn fill_hole<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cost: f64,
    per_block: f64,
    p: [i32; 3],
    f0: f64,
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) -> bool {
    let [x, y, z] = p;
    if (f0 - f64::from(y)).abs() > 1e-6 {
        return false;
    }
    let (bx, bz) = (x + dx, z + dz);
    let hole = g.class(bx, y - 1, bz);
    let under = g.class(bx, y - 2, bz);
    if !hole.has(flag::REPLACEABLE)
        || g.unknown(bx, y - 1, bz)
        || !(under.has(flag::SUPPORT) && under.top >= 1.0 - 1e-6 && under.top_any <= 1.0 + 1e-6)
        || under.has(flag::IRREGULAR | flag::AVOID_FLOOR)
    {
        return false;
    }
    if !clear(g, bx, bz, f0, f0 + HEIGHT) {
        return false;
    }
    let spot = Spot {
        kind: NodeKind::Ground,
        floor: f0,
        floor_flags: flag::PLACED,
        water: false,
        submerged: false,
        climb: false,
    };
    out.push(Edge {
        to: [bx, y, bz],
        spot,
        kind: MoveKind::Walk,
        cost: per_block + cost,
        dig: [None; 3],
        place: Some(Place {
            pos: [bx, y - 1, bz],
            against: [bx, y - 2, bz],
        }),
    });
    true
}

/// Extra ticks of a bridging step: turning round, sneaking back to the edge, turning again.
const BRIDGE_TICKS: f64 = 16.0;

/// Whether the floor of a step at `p` standing as `s` is a full cube whose faces can be
/// clicked (or one the path places itself).
fn full_floor<S: BlockSource + ?Sized>(g: &mut Grid<'_, S>, p: [i32; 3], s: &Spot) -> bool {
    if (s.floor - f64::from(p[1])).abs() > 1e-6 {
        return false;
    }
    if s.floor_flags & flag::PLACED != 0 {
        return true;
    }
    let fl = g.class(p[0], p[1] - 1, p[2]);
    fl.has(flag::SUPPORT)
        && !fl.has(flag::IRREGULAR | flag::THIN)
        && fl.bottom <= 1e-6
        && fl.top >= 1.0 - 1e-6
        && fl.top_any <= 1.0 + 1e-6
}

/// Bridge: walk over a gap to the neighbour at the same level after placing its floor block
/// against the side of this step's floor block (sneaking at the edge).
fn bridge<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cost: f64,
    per_block: f64,
    p: [i32; 3],
    s: &Spot,
    (dx, dz): (i32, i32),
    out: &mut Vec<Edge>,
) -> bool {
    let [x, y, z] = p;
    if s.water || !full_floor(g, p, s) {
        return false;
    }
    let (bx, bz) = (x + dx, z + dz);
    if !g.class(bx, y - 1, bz).has(flag::REPLACEABLE) || g.unknown(bx, y - 1, bz) {
        return false;
    }
    if !clear(g, bx, bz, s.floor, s.floor + HEIGHT) {
        return false;
    }
    out.push(Edge {
        to: [bx, y, bz],
        spot: Spot {
            kind: NodeKind::Ground,
            floor: s.floor,
            floor_flags: flag::PLACED,
            water: false,
            submerged: false,
            climb: false,
        },
        kind: MoveKind::Walk,
        cost: per_block + cost + BRIDGE_TICKS,
        dig: [None; 3],
        place: Some(Place {
            pos: [bx, y - 1, bz],
            against: [x, y - 1, z],
        }),
    });
    true
}

/// Tower up: jump and place a block into the feet cell, landing on it one block higher.
fn pillar<S: BlockSource + ?Sized>(
    g: &mut Grid<'_, S>,
    cost: f64,
    c: &Costs,
    p: [i32; 3],
    s: &Spot,
    out: &mut Vec<Edge>,
) {
    let [x, y, z] = p;
    if y + 1 >= g.y_range().1 - 1 || !full_floor(g, p, s) {
        return;
    }
    if !g.class(x, y, z).has(flag::REPLACEABLE) {
        return;
    }
    // Room for the body one higher and for the jump's arc above it.
    if !clear(g, x, z, s.floor + HEIGHT, s.floor + HEIGHT + JUMP_APEX) {
        return;
    }
    out.push(Edge {
        to: [x, y + 1, z],
        spot: Spot {
            kind: NodeKind::Ground,
            floor: s.floor + 1.0,
            floor_flags: flag::PLACED,
            water: false,
            submerged: false,
            climb: false,
        },
        kind: MoveKind::Pillar,
        cost: c.jump_up + cost + 4.0,
        dig: [None; 3],
        place: Some(Place {
            pos: [x, y, z],
            against: [x, y - 1, z],
        }),
    });
}

/// 1.16.5 and 26.1 climb a ladder or vine without a block behind it; the older versions need
/// one.
fn climbs_without_wall(version: Version) -> bool {
    match version {
        #[cfg(feature = "v1_16_5")]
        Version::V1_16_5 => true,
        #[cfg(feature = "v26_1")]
        Version::V26_1 => true,
        #[cfg(feature = "v26_2")]
        Version::V26_2 => true,
        #[cfg(feature = "v26_3")]
        Version::V26_3 => true,
        #[allow(unreachable_patterns)]
        _ => false,
    }
}

#[cfg(test)]
mod pack_tests {
    use super::pack;

    #[test]
    fn node_keys_are_unique_over_any_build_height() {
        let mut seen = std::collections::HashSet::new();
        for y in -2048..2048 {
            assert!(seen.insert(pack([-3, y, 5])), "y {y}");
        }
        // The old keys (0..256) are unchanged.
        assert_eq!(pack([1, 200, 2]), 1 << 34 | 2 << 8 | 200);
    }
}