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
//! Following a path from a `ghast_client::Behavior`: plan, follow, replan.

use std::collections::HashSet;
use std::time::{Duration, Instant};

use ghast_client::{BlockPos, Buttons, Controls, Face, TickContext};
use ghast_physics::Keys;

use crate::Version;
use crate::control::{Controller, ControllerConfig, Progress};
use crate::goal::Goal;
use crate::physics::Observation;
use crate::plan::{Budget, Path, Pathfinder, PlanError, Search};
use crate::sim::{SimOutcome, Simulation};
use crate::world::BlockSource;

/// What the follower reads and does in one tick. Implemented for ghast-client's
/// [`TickContext`]; the tests drive the same follower with a simulated player.
pub(crate) trait Io {
    /// The world type.
    type World<'w>: BlockSource + ?Sized
    where
        Self: 'w;
    /// The world as the client knows it.
    fn world(&self) -> &Self::World<'_>;
    /// The planner's version (`None`: not supported by the planner, e.g. 26.1).
    fn version(&self) -> Option<Version>;
    /// The player.
    fn observation(&self) -> Observation;
    /// The server moved the player this tick (teleport, respawn).
    fn moved_by_server(&self) -> bool;
    /// Dead.
    fn is_dead(&self) -> bool;
    /// Aim target.
    fn set_aim(&mut self, yaw: f32, pitch: f32);
    /// The look this tick's movement uses (after turning toward the aim).
    fn planned_look(&self) -> (f32, f32);
    /// Movement keys from now on.
    fn set_keys(&mut self, keys: Keys);
    /// The left button is held.
    fn left_button(&self) -> bool;
    /// Holds or releases the left button (and the right one).
    fn set_left_button(&mut self, on: bool);
    /// The crosshair is on this block (as the server judges it).
    fn targets(&self, block: [i32; 3]) -> bool;
    /// Right-clicks the face of `against` toward `dir` (a unit offset) with the held item if
    /// the crosshair is on it; `true` when the place was sent.
    fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool;
    /// Right-clicks `block` (opens a door or gate) if the crosshair is on it; `true` when the
    /// click was sent.
    fn activate(&mut self, block: [i32; 3]) -> bool;
    /// 26.1: the live client player (attributes, effects, abilities, level).
    #[cfg(ghast_modern)]
    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
        None
    }
    /// The build height `(min_y, height)` of the player's dimension, when known.
    fn build_height(&self) -> Option<(i32, i32)> {
        #[cfg(ghast_modern)]
        if let Some(p) = self.modern_player() {
            return Some((p.level.min_y, p.level.height));
        }
        None
    }
}

/// The client's world with the dimension's build height (unknown below it).
struct Height<'a, W: ?Sized> {
    world: &'a W,
    height: Option<(i32, i32)>,
}

impl<W: BlockSource + ?Sized> BlockSource for Height<'_, W> {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        if let Some((lo, h)) = self.height
            && (y < lo || y >= lo + h)
        {
            return None;
        }
        self.world.raw_block(x, y, z)
    }

    #[inline]
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        self.world.is_column_loaded(chunk_x, chunk_z)
    }

    fn build_height(&self) -> Option<(i32, i32)> {
        self.height.or_else(|| self.world.build_height())
    }
}

/// [`Height`] over an [`Io`]'s world.
fn world_of<I: Io + ?Sized>(ctx: &I) -> Height<'_, I::World<'_>> {
    Height {
        world: ctx.world(),
        height: ctx.build_height(),
    }
}

impl Io for TickContext<'_> {
    type World<'w>
        = dyn ghast_client::WorldView + 'w
    where
        Self: 'w;

    fn world(&self) -> &Self::World<'_> {
        TickContext::world(self)
    }

    fn version(&self) -> Option<Version> {
        Version::from_game(TickContext::version(self))
    }

    fn observation(&self) -> Observation {
        let pose = *self.pose();
        Observation {
            pos: [pose.pos.x, pose.pos.y, pose.pos.z],
            vel: [pose.motion.x, pose.motion.y, pose.motion.z],
            on_ground: pose.on_ground,
            yaw: pose.yaw,
            pitch: pose.pitch,
            sprinting: pose.sprinting,
            food: self.health().food,
        }
    }

    fn moved_by_server(&self) -> bool {
        !self.events().teleports.is_empty() || self.events().respawned
    }

    fn is_dead(&self) -> bool {
        TickContext::is_dead(self)
    }

    fn set_aim(&mut self, yaw: f32, pitch: f32) {
        TickContext::set_aim(self, yaw, pitch);
    }

    fn planned_look(&self) -> (f32, f32) {
        TickContext::planned_look(self)
    }

    fn set_keys(&mut self, k: Keys) {
        self.set_controls(Controls {
            forward: k.forward,
            back: k.back,
            left: k.left,
            right: k.right,
            jump: k.jump,
            sneak: k.sneak,
            sprint: k.sprint,
        });
    }

    fn left_button(&self) -> bool {
        self.buttons().left
    }

    fn set_left_button(&mut self, on: bool) {
        self.set_buttons(Buttons {
            left: on,
            right: false,
        });
    }

    fn targets(&self, block: [i32; 3]) -> bool {
        let pos = BlockPos::new(block[0], block[1], block[2]);
        self.target().is_some_and(|t| t.pos == pos)
    }

    fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool {
        let face = match dir {
            [0, -1, 0] => Face::Down,
            [0, 0, -1] => Face::North,
            [0, 0, 1] => Face::South,
            [-1, 0, 0] => Face::West,
            [1, 0, 0] => Face::East,
            _ => Face::Up,
        };
        let against = BlockPos::new(against[0], against[1], against[2]);
        match self.target().filter(|t| t.pos == against && t.face == face) {
            Some(hit) => self.place(against, face, hit.hit),
            None => false,
        }
    }

    fn activate(&mut self, block: [i32; 3]) -> bool {
        let pos = BlockPos::new(block[0], block[1], block[2]);
        match self.target().filter(|t| t.pos == pos) {
            Some(hit) => self.place(pos, hit.face, hit.hit),
            None => false,
        }
    }
    #[cfg(ghast_modern)]
    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
        TickContext::modern_player(self)
    }
}

/// Options of the [`Follower`]. Build with [`FollowConfig::default`] and the `with_*`
/// methods.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FollowConfig {
    /// The controller's options.
    pub controller: ControllerConfig,
    /// Replans after a stuck / off-path move or a blocked partial path before giving up.
    /// Default 8. Teleports replan without counting.
    pub max_replans: u32,
    /// Simulate each plan in `ghast-physics` before moving and plan around moves the
    /// simulation fails (see [`Pathfinder::plan_verified`]). Default on.
    pub verify: bool,
    /// Planning work per game tick: the search expands at most `budget.nodes` nodes and
    /// planning plus verification stop after `budget.time`. Default 2000 nodes and 5 ms
    /// (about 4 ms of A* on a desktop core), so a long plan spreads over several ticks
    /// while the player stands still.
    pub budget: Budget,
    /// Most simulated ticks of the verification per game tick (also bounded by
    /// `budget.time`). Default 400.
    pub verify_ticks: u32,
    /// Movement only: the follower leaves the aim to the behaviour (a fight keeps looking at
    /// its target) and steers with the keys relative to the look the behaviour's aim gives
    /// this tick. Default off. See [`FollowConfig::with_movement_only`].
    pub movement_only: bool,
}

impl Default for FollowConfig {
    fn default() -> Self {
        FollowConfig {
            controller: ControllerConfig::default(),
            max_replans: 8,
            verify: true,
            budget: Budget::nodes(2000).with_time(Duration::from_millis(5)),
            verify_ticks: 400,
            movement_only: false,
        }
    }
}

impl FollowConfig {
    /// The controller's options.
    #[must_use]
    pub fn with_controller(mut self, c: ControllerConfig) -> Self {
        self.controller = c;
        self
    }

    /// Replan budget.
    #[must_use]
    pub fn with_max_replans(mut self, n: u32) -> Self {
        self.max_replans = n;
        self
    }

    /// Movement only (strafe-relative steering): the follower never sets the aim on plain moves
    /// (walks, diagonals, step-ups, drops, swims); it plans the keys for the look it wants and
    /// presses the one of the eight key directions (forward / back × left / right) closest to
    /// that move for the look the behaviour's aim gives this tick
    /// ([`TickContext::planned_look`], so tick the follower after `set_aim`): the direction
    /// whose next ticks, simulated, end closest to where the planned keys would go and keep
    /// to the floor. The sprint key stays down only with forward. Moves that need the look — digging, placing, doors, gap
    /// jumps, ladders, pillars — still aim while they last ([`Follower::aiming`] tells). Eight
    /// directions are coarser than a turned look (up to 22.5° off), so corners and ledges are
    /// walked less exactly than with the aim; [`Follower::waypoint`] gives the point to steer
    /// to for a behaviour that drives the keys itself.
    #[must_use]
    pub fn with_movement_only(mut self, on: bool) -> Self {
        self.movement_only = on;
        self
    }

    /// Simulated verification of plans on or off.
    #[must_use]
    pub fn with_verify(mut self, on: bool) -> Self {
        self.verify = on;
        self
    }

    /// Planning work per game tick ([`Budget::UNLIMITED`]: plan in one tick).
    #[must_use]
    pub fn with_budget(mut self, budget: Budget) -> Self {
        self.budget = budget;
        self
    }

    /// Simulated verification ticks per game tick.
    #[must_use]
    pub fn with_verify_ticks(mut self, ticks: u32) -> Self {
        self.verify_ticks = ticks.max(1);
        self
    }
}

/// Why following failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FollowError {
    /// Planning failed.
    Plan(PlanError),
    /// The replan budget ([`FollowConfig::max_replans`]) is used up.
    GaveUp,
    /// The planner does not support this game version (26.1) or its feature is off.
    UnsupportedVersion,
}

impl std::fmt::Display for FollowError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FollowError::Plan(e) => write!(f, "planning failed: {e}"),
            FollowError::GaveUp => f.write_str("gave up after too many replans"),
            FollowError::UnsupportedVersion => {
                f.write_str("the path finder does not support this game version")
            }
        }
    }
}

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

/// What the [`Follower`] is doing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FollowStatus {
    /// No goal.
    Idle,
    /// Walking (or digging / placing) toward the goal.
    Moving,
    /// The goal is reached; keys released.
    Arrived,
    /// Following failed; keys released.
    Failed(FollowError),
}

/// Plans and follows a path from a behaviour's tick: call [`Follower::tick`] once per tick from
/// `Behavior::tick`. It sets the aim, the movement keys and (for digs) the left button
/// through the [`TickContext`], so the client's rules hold: rotation in whole mouse counts,
/// actions before the tick's single movement packet, digs / places only with the sent
/// crosshair on the block.
///
/// It replans after a teleport, when the controller gets stuck or leaves the path (that move
/// is avoided from then on), and at the end of a partial path (goal beyond loaded terrain).
/// Digging and placing follow [`crate::Config::dig`] / [`crate::Config::place`]; for places
/// the behaviour keeps a block in the hand.
///
/// ```no_run
/// use ghast_client::{Behavior, TickContext};
/// use ghast_pathfinder::{Config, FollowConfig, FollowStatus, Follower, Goal, Pathfinder};
///
/// struct GoThere(Follower);
///
/// impl Behavior for GoThere {
///     fn tick(&mut self, ctx: &mut TickContext<'_>) {
///         match self.0.tick(ctx) {
///             FollowStatus::Arrived => ctx.disconnect("arrived"),
///             FollowStatus::Failed(e) => ctx.disconnect(format!("failed: {e}")),
///             _ => {}
///         }
///     }
/// }
///
/// let mut f = Follower::new(Pathfinder::new(Config::default()), FollowConfig::default());
/// f.goto(Goal::Block([20, 64, 5]));
/// let mut behaviour = GoThere(f);
/// ```
#[derive(Clone, Debug)]
pub struct Follower {
    pf: Pathfinder,
    cfg: FollowConfig,
    goal: Option<Goal>,
    ctrl: Option<Controller>,
    status: FollowStatus,
    replans: u32,
    banned: HashSet<([i32; 3], [i32; 3])>,
    /// Closest a partial path has come to the goal so far (no progress beyond it = blocked).
    partial_best: f64,
    /// The path being followed is partial and final: no path to the goal exists through the
    /// loaded terrain (the search was exhausted), it ends as close to the goal as possible.
    unreachable: bool,
    /// Ticks to wait after a place was sent.
    place_wait: u32,
    digging: bool,
    plans: u64,
    /// A plan in progress (spread over ticks).
    planning: Option<Planning>,
    /// Ticks the current (or last) plan took.
    plan_ticks: u32,
    /// Whether the goal lay in loaded terrain when the current plan started.
    goal_loaded: Option<bool>,
    /// The last tick set the aim.
    aimed: bool,
}

/// A plan in progress: the search, then the simulated check.
#[derive(Clone, Debug)]
enum Planning {
    Search {
        search: Box<Search>,
        /// Moves the verification failed (on top of [`Follower::banned`]).
        bans: HashSet<([i32; 3], [i32; 3])>,
        attempt: u32,
        /// The previous attempt's path (followed if a later search fails) and whether its
        /// search was exhausted.
        last: Option<(Path, bool)>,
    },
    Verify {
        sim: Box<Simulation>,
        bans: HashSet<([i32; 3], [i32; 3])>,
        attempt: u32,
        /// The search of the path was exhausted.
        exhausted: bool,
    },
}

/// A search with the live player's movement limits when the client has one (26.1).
fn with_player<I: Io + ?Sized>(ctx: &I, search: Search) -> Search {
    #[cfg(ghast_modern)]
    if let Some(p) = ctx.modern_player() {
        return search.with_modern_player(p);
    }
    let _ = ctx;
    search
}

/// The verification of `path` with the live player when the client has one (26.1).
fn new_sim<I: Io + ?Sized>(ctx: &I, path: &Path, cfg: &ControllerConfig) -> Simulation {
    #[cfg(ghast_modern)]
    if let Some(p) = ctx.modern_player() {
        return Simulation::with_modern_player(path, cfg, p);
    }
    let _ = ctx;
    Simulation::new(path, cfg)
}

/// Plans per goal and replan: the first one and two repairs after failed simulations.
const VERIFY_ATTEMPTS: u32 = 3;

/// Whether the goal's place lies in loaded terrain (goals without one: no).
fn goal_loaded<W: BlockSource + ?Sized>(goal: &Goal, world: &W) -> bool {
    match goal {
        Goal::Block(p) | Goal::Near { pos: p, .. } => world.is_column_loaded(p[0] >> 4, p[2] >> 4),
        Goal::Xz { x, z } => world.is_column_loaded(x >> 4, z >> 4),
        Goal::Y(_) => false,
        Goal::AnyOf(gs) => !gs.is_empty() && gs.iter().all(|g| goal_loaded(g, world)),
    }
}

impl Follower {
    /// A follower without a goal.
    #[must_use]
    pub fn new(pathfinder: Pathfinder, cfg: FollowConfig) -> Self {
        Follower {
            pf: pathfinder,
            cfg,
            goal: None,
            ctrl: None,
            status: FollowStatus::Idle,
            replans: 0,
            banned: HashSet::new(),
            partial_best: f64::INFINITY,
            unreachable: false,
            place_wait: 0,
            digging: false,
            plans: 0,
            planning: None,
            plan_ticks: 0,
            goal_loaded: None,
            aimed: false,
        }
    }

    /// Sets a new goal (planned on the next [`Follower::tick`]).
    pub fn goto(&mut self, goal: Goal) {
        self.goal = Some(goal);
        self.ctrl = None;
        self.planning = None;
        self.status = FollowStatus::Moving;
        self.replans = 0;
        self.banned.clear();
        self.partial_best = f64::INFINITY;
        self.unreachable = false;
    }

    /// Drops the goal and releases the keys and buttons (in this tick).
    pub fn stop(&mut self, ctx: &mut TickContext<'_>) {
        self.goal = None;
        self.ctrl = None;
        self.planning = None;
        self.status = FollowStatus::Idle;
        self.release(ctx);
    }

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

    /// The current state.
    #[must_use]
    pub fn status(&self) -> FollowStatus {
        self.status
    }

    /// The path being followed.
    #[must_use]
    pub fn path(&self) -> Option<&crate::Path> {
        self.ctrl.as_ref().map(Controller::path)
    }

    /// The point the follower walks to now (the next step's block centre at its feet height),
    /// `None` without a path being followed.
    #[must_use]
    pub fn waypoint(&self) -> Option<[f64; 3]> {
        self.ctrl.as_ref().and_then(Controller::waypoint)
    }

    /// The move (`from`, `to` feet blocks) being followed.
    #[must_use]
    pub fn current_move(&self) -> Option<([i32; 3], [i32; 3])> {
        self.ctrl.as_ref().and_then(Controller::current_move)
    }

    /// Whether the last [`Follower::tick`] set the aim (always, unless
    /// [`FollowConfig::with_movement_only`] is on and the move did not need the look).
    #[must_use]
    pub fn aiming(&self) -> bool {
        self.aimed
    }

    /// Plans made since the follower was created (for logs and tests).
    #[must_use]
    pub fn plans(&self) -> u64 {
        self.plans
    }

    /// A plan is in progress: the player stands still (keys released, no turning) and the
    /// client keeps sending its normal movement packet every tick.
    #[must_use]
    pub fn is_planning(&self) -> bool {
        self.planning.is_some()
    }

    /// Ticks the current (or the last) plan took, verification included (1 = planned within
    /// the tick it started).
    #[must_use]
    pub fn plan_ticks(&self) -> u32 {
        self.plan_ticks
    }

    /// The planner.
    #[must_use]
    pub fn pathfinder(&self) -> &Pathfinder {
        &self.pf
    }

    fn release<I: Io + ?Sized>(&mut self, ctx: &mut I) {
        ctx.set_keys(Keys::NONE);
        if self.digging || ctx.left_button() {
            ctx.set_left_button(false);
        }
        self.digging = false;
    }

    fn fail<I: Io + ?Sized>(&mut self, ctx: &mut I, e: FollowError) -> FollowStatus {
        self.ctrl = None;
        self.planning = None;
        self.status = FollowStatus::Failed(e);
        self.release(ctx);
        self.status
    }

    /// Starts a plan from the player's feet block.
    fn start_plan<I: Io + ?Sized>(&mut self, ctx: &I, version: Version) {
        let goal = self.goal.clone().expect("planning without a goal");
        let start = Pathfinder::start_block(ctx.observation().pos);
        self.plans += 1;
        self.plan_ticks = 0;
        self.planning = Some(Planning::Search {
            search: Box::new(with_player(
                ctx,
                self.pf.search(version, start, goal, self.banned.clone()),
            )),
            bans: HashSet::new(),
            attempt: 0,
            last: None,
        });
    }

    /// This tick's share of the plan in progress: the controller once the path is ready.
    fn work<I: Io + ?Sized>(&mut self, ctx: &I) -> Result<Option<Controller>, PlanError> {
        self.plan_ticks += 1;
        let t0 = Instant::now();
        let left = |budget: Option<Duration>| budget.map(|b| b.saturating_sub(t0.elapsed()));
        loop {
            if let Some(max) = self.cfg.budget.time
                && t0.elapsed() >= max
            {
                return Ok(None);
            }
            let Some(phase) = self.planning.take() else {
                return Ok(None);
            };
            match phase {
                Planning::Search {
                    mut search,
                    bans,
                    attempt,
                    last,
                } => {
                    let budget = Budget {
                        nodes: self.cfg.budget.nodes,
                        time: left(self.cfg.budget.time),
                    };
                    match search.step(&world_of(ctx), budget) {
                        None => {
                            self.planning = Some(Planning::Search {
                                search,
                                bans,
                                attempt,
                                last,
                            });
                            return Ok(None);
                        }
                        Some(Err(e)) => match last {
                            // A repair failed: follow the previous path after all.
                            Some((p, ex)) => return Ok(Some(self.ready(p, ex))),
                            None => return Err(e),
                        },
                        Some(Ok(path)) => {
                            let exhausted = search.exhausted();
                            if !self.cfg.verify {
                                return Ok(Some(self.ready(path, exhausted)));
                            }
                            let sim = new_sim(ctx, &path, &self.cfg.controller);
                            self.planning = Some(Planning::Verify {
                                sim: Box::new(sim),
                                bans,
                                attempt,
                                exhausted,
                            });
                        }
                    }
                }
                Planning::Verify {
                    mut sim,
                    mut bans,
                    attempt,
                    exhausted,
                } => {
                    let Some((outcome, reached)) = sim
                        .step(
                            &world_of(ctx),
                            self.cfg.verify_ticks,
                            left(self.cfg.budget.time),
                        )
                        .map(|r| (r.outcome, r.reached))
                    else {
                        self.planning = Some(Planning::Verify {
                            sim,
                            bans,
                            attempt,
                            exhausted,
                        });
                        return Ok(None);
                    };
                    let path = sim.path();
                    if outcome == SimOutcome::Arrived {
                        let path = path.clone();
                        return Ok(Some(self.ready(path, exhausted)));
                    }
                    // Plan around the move the simulation failed.
                    let k = (reached + 1).min(path.steps.len() - 1);
                    let m = (path.steps[k.saturating_sub(1)].pos, path.steps[k].pos);
                    log::debug!("pathfinder: simulation {outcome:?} on move {m:?}");
                    if k == 0 || attempt + 1 >= VERIFY_ATTEMPTS || !bans.insert(m) {
                        let path = path.clone();
                        return Ok(Some(self.ready(path, exhausted)));
                    }
                    let goal = self.goal.clone().expect("planning without a goal");
                    let mut all = self.banned.clone();
                    all.extend(bans.iter().copied());
                    let search = with_player(
                        ctx,
                        self.pf.search(path.version, path.steps[0].pos, goal, all),
                    );
                    self.planning = Some(Planning::Search {
                        search: Box::new(search),
                        bans,
                        attempt: attempt + 1,
                        last: Some((path.clone(), exhausted)),
                    });
                }
            }
        }
    }

    fn ready(&mut self, path: Path, exhausted: bool) -> Controller {
        // An exhausted search knows every block reachable through the loaded terrain: if the
        // goal lies in loaded terrain too, its partial path is as close as one gets.
        self.unreachable = path.partial && exhausted && self.goal_loaded.unwrap_or(false);
        log::debug!(
            "pathfinder: {} steps, cost {:.0} ticks, {} nodes{}, planned in {} ticks",
            path.steps.len(),
            path.cost,
            path.expanded,
            if self.unreachable {
                ", partial (goal unreachable)"
            } else if path.partial {
                ", partial"
            } else {
                ""
            },
            self.plan_ticks
        );
        self.planning = None;
        Controller::new(path, self.cfg.controller.clone())
    }

    /// One tick: plans when needed, then aims and sets the keys (and digs / places). Returns
    /// the status after this tick.
    pub fn tick(&mut self, ctx: &mut TickContext<'_>) -> FollowStatus {
        self.step(ctx)
    }

    /// [`Follower::tick`] over any [`Io`].
    pub(crate) fn step<I: Io + ?Sized>(&mut self, ctx: &mut I) -> FollowStatus {
        if self.goal.is_none() || !matches!(self.status, FollowStatus::Moving) {
            return self.status;
        }
        if ctx.moved_by_server() {
            self.ctrl = None;
            self.planning = None;
        }
        if ctx.is_dead() {
            self.release(ctx);
            return self.status;
        }
        if self.ctrl.is_none() {
            if self.planning.is_none() {
                let Some(version) = ctx.version() else {
                    return self.fail(ctx, FollowError::UnsupportedVersion);
                };
                self.goal_loaded = self.goal.as_ref().map(|g| goal_loaded(g, ctx.world()));
                self.start_plan(ctx, version);
            }
            match self.work(ctx) {
                Ok(Some(c)) => self.ctrl = Some(c),
                Ok(None) => {
                    // Still planning: stand still; the movement packet goes out as usual.
                    self.release(ctx);
                    return self.status;
                }
                Err(e) => return self.fail(ctx, FollowError::Plan(e)),
            }
        }
        let obs = ctx.observation();
        let ctrl = self.ctrl.as_mut().expect("planned above");
        #[cfg(ghast_modern)]
        if let Some(p) = ctx.modern_player() {
            ctrl.set_modern_player(p);
        }
        let (yaw, pitch) = ctrl.aim(&obs, &world_of(ctx));
        let done = matches!(
            ctrl.progress(),
            Progress::Arrived | Progress::Stuck | Progress::OffPath
        );
        let steer = self.cfg.movement_only && !ctrl.needs_look();
        self.aimed = !done && !steer;
        if self.aimed {
            ctx.set_aim(yaw, pitch);
        }
        let look = ctx.planned_look();
        let cmd = if steer {
            // The keys for the wanted look, pressed relative to the behaviour's look.
            let mut cmd = ctrl.keys(&obs, (yaw, look.1), &world_of(ctx));
            cmd.keys = ctrl.steer_keys(&obs, cmd.keys, look, &world_of(ctx));
            cmd
        } else {
            ctrl.keys(&obs, look, &world_of(ctx))
        };
        match ctrl.progress() {
            Progress::Arrived => {
                let path = ctrl.path();
                if !path.partial {
                    self.release(ctx);
                    self.status = FollowStatus::Arrived;
                    return self.status;
                }
                if self.unreachable {
                    // As close as it gets: no path exists through the loaded terrain.
                    return self.fail(ctx, FollowError::Plan(PlanError::NoPath));
                }
                // The end of a partial path: plan the rest from here. Count it against the
                // replan budget unless it got closer to the goal than any partial path before.
                let goal = self.goal.as_ref().expect("following without a goal");
                let d = path
                    .steps
                    .last()
                    .map_or(f64::INFINITY, |s| goal.distance(s.pos));
                if d < self.partial_best - 0.5 {
                    self.partial_best = d;
                } else {
                    self.replans += 1;
                }
                self.ctrl = None;
                self.release(ctx);
                if self.replans > self.cfg.max_replans {
                    return self.fail(ctx, FollowError::GaveUp);
                }
                return self.status;
            }
            Progress::Stuck | Progress::OffPath => {
                if let Some(m) = ctrl.current_move() {
                    log::debug!(
                        "pathfinder: {:?} on move {m:?}, replanning",
                        ctrl.progress()
                    );
                    self.banned.insert(m);
                }
                self.ctrl = None;
                self.replans += 1;
                self.release(ctx);
                if self.replans > self.cfg.max_replans {
                    return self.fail(ctx, FollowError::GaveUp);
                }
                return self.status;
            }
            Progress::Moving | Progress::Working => {}
        }
        ctx.set_keys(cmd.keys);
        if let Some(d) = cmd.dig {
            let on = ctx.targets(d);
            ctx.set_left_button(on);
            self.digging = true;
        } else if self.digging {
            ctx.set_left_button(false);
            self.digging = false;
        }
        if let Some(p) = cmd.place {
            if self.place_wait > 0 {
                self.place_wait -= 1;
            } else if ctx.place_against(p.against, p.face()) {
                self.place_wait = 10;
            }
        } else if let Some(b) = cmd.interact {
            // A second click would close the door again: wait for the server's answer.
            if self.place_wait > 0 {
                self.place_wait -= 1;
            } else if ctx.activate(b) {
                self.place_wait = 20;
            }
        } else {
            self.place_wait = 0;
        }
        self.status
    }
}

#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) mod tests {
    //! The follower driven tick by tick in the physics (a simulated client): mazes, unreachable
    //! goals, gap jumps.

    use std::time::{Duration, Instant};

    use ghast_physics::Keys;

    use super::{FollowConfig, FollowError, FollowStatus, Follower, Io};
    use crate::physics::{Observation, P12, P16, P18, P26, P262, Physics, SourceView};
    use crate::plan::{Config, Pathfinder, PlanError};
    use crate::sim::Turner;
    use crate::world::BlockSource;
    use crate::{Goal, Version};

    /// The world as the simulated client sees it: the test's world plus the blocks the player
    /// dug, placed or clicked (doors).
    pub(crate) struct Overlay<'w, W> {
        base: &'w W,
        set: std::collections::HashMap<[i32; 3], u32>,
    }

    impl<W: BlockSource> BlockSource for Overlay<'_, W> {
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            match self.set.get(&[x, y, z]) {
                Some(&r) => Some(r),
                None => self.base.raw_block(x, y, z),
            }
        }

        fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
            self.base.is_column_loaded(cx, cz)
        }

        fn build_height(&self) -> Option<(i32, i32)> {
            self.base.build_height()
        }
    }

    /// A simulated client: the player in `ghast-physics`, turning in whole mouse counts. Digs,
    /// places and clicks go through a crosshair ray from the pose of the previous tick (the
    /// one the server has), within 4.5 blocks, like the real client: a dig breaks the block
    /// after `5 + 30 × hardness` ticks, a place or a door click takes effect two ticks after it
    /// was sent (the server's answer).
    pub(crate) struct SimIo<'w, P: Physics, W: BlockSource> {
        pub(crate) world: Overlay<'w, W>,
        pub(crate) state: P::State,
        turner: Turner,
        aim: (f32, f32),
        keys: Keys,
        left: bool,
        digging: Option<([i32; 3], u32)>,
        /// Block changes on their way from the server: (ticks left, position, raw).
        pending: Vec<(u32, [i32; 3], u32)>,
        /// Places and clicks sent.
        pub(crate) places: u32,
        /// Places asked for while the new block's cell overlapped the player's box (a
        /// client's placed-block prediction would not apply; vanilla refuses them).
        pub(crate) overlapping: u32,
        pub(crate) clicks: u32,
    }

    impl<'w, P: Physics, W: BlockSource> SimIo<'w, P, W> {
        pub(crate) fn new(world: &'w W, feet: [f64; 3]) -> Self {
            let mut state = P::new_state(feet, 0.0, 0.0);
            let view = SourceView::<P, W>::new(world);
            for _ in 0..3 {
                P::tick(&mut state, Keys::NONE, 0.0, 0.0, &view);
            }
            SimIo {
                world: Overlay {
                    base: world,
                    set: std::collections::HashMap::new(),
                },
                state,
                turner: Turner::default(),
                aim: (0.0, 0.0),
                keys: Keys::NONE,
                left: false,
                digging: None,
                pending: Vec::new(),
                places: 0,
                overlapping: 0,
                clicks: 0,
            }
        }

        /// Runs this tick's movement with what the follower asked for.
        pub(crate) fn advance(&mut self) {
            // The digging hand first (the server judges it with the pose sent last tick).
            let target = self.ray().map(|(b, _)| b);
            match (self.left, target) {
                (true, Some(b)) => {
                    let n = match self.digging {
                        Some((d, n)) if d == b => n + 1,
                        _ => 1,
                    };
                    let hard = self.class(b).hardness.max(0.0);
                    if n >= 5 + (f64::from(hard) * 30.0) as u32 {
                        self.world.set.insert(b, 0);
                        self.digging = None;
                    } else {
                        self.digging = Some((b, n));
                    }
                }
                _ => self.digging = None,
            }
            for p in &mut self.pending {
                p.0 -= 1;
            }
            let (due, rest): (Vec<_>, Vec<_>) = self.pending.drain(..).partition(|p| p.0 == 0);
            self.pending = rest;
            for (_, pos, raw) in due {
                self.world.set.insert(pos, raw);
            }
            let o = P::observe(&self.state);
            let look = self.turner.step(o.yaw, o.pitch, self.aim);
            let view = SourceView::<P, Overlay<'w, W>>::new(&self.world);
            P::tick(&mut self.state, self.keys, look.0, look.1, &view);
        }

        pub(crate) fn feet(&self) -> [f64; 3] {
            P::observe(&self.state).pos
        }

        pub(crate) fn class(&self, p: [i32; 3]) -> crate::class::Class {
            let t = crate::class::table(P::VERSION);
            self.world
                .raw_block(p[0], p[1], p[2])
                .map_or(crate::class::Class::UNKNOWN, |r| {
                    t.classes[t.index(r) as usize]
                })
        }

        /// The block the crosshair is on and the face it enters (as a unit offset), from the
        /// pose the server has; cells with any collision box count as whole cubes.
        pub(crate) fn ray(&self) -> Option<([i32; 3], [i32; 3])> {
            let o = P::observe(&self.state);
            let (yaw, pitch) = (
                f64::from(o.yaw).to_radians(),
                f64::from(o.pitch).to_radians(),
            );
            let d = [
                -yaw.sin() * pitch.cos(),
                -pitch.sin(),
                yaw.cos() * pitch.cos(),
            ];
            let e = [o.pos[0], o.pos[1] + 1.62, o.pos[2]];
            let mut c = [
                e[0].floor() as i32,
                e[1].floor() as i32,
                e[2].floor() as i32,
            ];
            let step = d.map(|v| if v > 0.0 { 1 } else { -1 });
            let mut tmax = [0.0f64; 3];
            let mut tdelta = [0.0f64; 3];
            for i in 0..3 {
                if d[i].abs() < 1e-12 {
                    tmax[i] = f64::INFINITY;
                    tdelta[i] = f64::INFINITY;
                } else {
                    let next = if d[i] > 0.0 {
                        f64::from(c[i]) + 1.0
                    } else {
                        f64::from(c[i])
                    };
                    tmax[i] = (next - e[i]) / d[i];
                    tdelta[i] = 1.0 / d[i].abs();
                }
            }
            loop {
                let i = (0..3).min_by(|&a, &b| tmax[a].total_cmp(&tmax[b])).unwrap();
                if tmax[i] > 4.5 {
                    return None;
                }
                c[i] += step[i];
                tmax[i] += tdelta[i];
                let k = self.class(c);
                if k.has(crate::class::flag::SOLID) {
                    let mut face = [0; 3];
                    face[i] = -step[i];
                    return Some((c, face));
                }
            }
        }

        /// Whether a block at `p` would overlap the player's box.
        fn overlaps_player(&self, p: [i32; 3]) -> bool {
            let o = P::observe(&self.state).pos;
            let (x, y, z) = (f64::from(p[0]), f64::from(p[1]), f64::from(p[2]));
            o[0] + 0.3 > x
                && o[0] - 0.3 < x + 1.0
                && o[1] + 1.8 > y
                && o[1] < y + 1.0
                && o[2] + 0.3 > z
                && o[2] - 0.3 < z + 1.0
        }
    }

    impl<'w, P: Physics, W: BlockSource> Io for SimIo<'w, P, W> {
        type World<'a>
            = Overlay<'w, W>
        where
            Self: 'a;

        fn world(&self) -> &Overlay<'w, W> {
            &self.world
        }

        fn version(&self) -> Option<Version> {
            Some(P::VERSION)
        }

        fn observation(&self) -> Observation {
            let mut o = P::observe(&self.state);
            o.food = 20;
            o
        }

        fn moved_by_server(&self) -> bool {
            false
        }

        fn is_dead(&self) -> bool {
            false
        }

        fn set_aim(&mut self, yaw: f32, pitch: f32) {
            self.aim = (yaw, pitch);
        }

        fn planned_look(&self) -> (f32, f32) {
            let o = P::observe(&self.state);
            let mut t = self.turner;
            t.step(o.yaw, o.pitch, self.aim)
        }

        fn set_keys(&mut self, keys: Keys) {
            self.keys = keys;
        }

        fn left_button(&self) -> bool {
            self.left
        }

        fn set_left_button(&mut self, on: bool) {
            self.left = on;
        }

        fn targets(&self, block: [i32; 3]) -> bool {
            self.ray().is_some_and(|(b, _)| b == block)
        }

        fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool {
            if self.ray() != Some((against, dir)) {
                return false;
            }
            let pos = [
                against[0] + dir[0],
                against[1] + dir[1],
                against[2] + dir[2],
            ];
            if self.overlaps_player(pos) {
                self.overlapping += 1;
                return false;
            }
            if !self.class(pos).has(crate::class::flag::REPLACEABLE) {
                return false;
            }
            self.places += 1;
            self.pending
                .push((2, pos, crate::sim::stone_raw(P::VERSION)));
            true
        }

        fn activate(&mut self, block: [i32; 3]) -> bool {
            if self.ray().map(|(b, _)| b) != Some(block) {
                return false;
            }
            self.clicks += 1;
            if let Some(changes) = crate::door::toggle(P::VERSION, &self.world, block) {
                for (p, raw) in changes {
                    self.pending.push((2, p, raw));
                }
            }
            true
        }

        fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
            P::as_modern(&self.state)
        }
    }

    /// How a drive went.
    #[derive(Debug)]
    pub(crate) struct Drive {
        pub(crate) status: FollowStatus,
        pub(crate) ticks: u32,
        /// Ticks the follower stood still planning.
        pub(crate) planning_ticks: u32,
        /// The longest follower tick (wall clock).
        pub(crate) worst_tick: Duration,
        pub(crate) plans: u64,
        pub(crate) end: [f64; 3],
    }

    /// Drives `follower` to `goal` from standing at `feet`, at most `max` ticks.
    pub(crate) fn drive<P: Physics, W: BlockSource>(
        world: &W,
        feet: [f64; 3],
        mut follower: Follower,
        goal: Goal,
        max: u32,
    ) -> Drive {
        let mut io = SimIo::<P, W>::new(world, feet);
        follower.goto(goal);
        let mut d = Drive {
            status: FollowStatus::Moving,
            ticks: 0,
            planning_ticks: 0,
            worst_tick: Duration::ZERO,
            plans: 0,
            end: feet,
        };
        while d.ticks < max {
            let t0 = Instant::now();
            d.status = follower.step(&mut io);
            // The first tick of a process also measures the move costs once.
            if d.ticks > 0 {
                d.worst_tick = d.worst_tick.max(t0.elapsed());
            }
            if follower.is_planning() {
                d.planning_ticks += 1;
            }
            d.ticks += 1;
            if d.status != FollowStatus::Moving {
                break;
            }
            io.advance();
        }
        d.plans = follower.plans();
        d.end = io.feet();
        d
    }

    const STONE18: u16 = 1 << 4;

    fn rng(s: &mut u64) -> u64 {
        *s ^= *s << 13;
        *s ^= *s >> 7;
        *s ^= *s << 17;
        *s
    }

    /// A perfect maze (recursive backtracker) of `n` × `n` cells with `h`-high stone walls on
    /// a stone floor at y = 63; grid (2n + 1)², corner (ox, oz). Cell (i, j) has its feet
    /// block at (ox + 2i + 1, 64, oz + 2j + 1). Entrances: west of cell (0, 0), east of
    /// cell (n - 1, n - 1).
    pub(crate) fn maze<B: Copy>(
        w: &mut ghast_physics::MemoryWorld<B>,
        (ox, oz): (i32, i32),
        n: i32,
        h: i32,
        seed: u64,
    ) {
        let size = 2 * n + 1;
        w.fill_raw(
            [ox, 64, oz],
            [ox + size - 1, 63 + h, oz + size - 1],
            STONE18,
        );
        let carve = |w: &mut ghast_physics::MemoryWorld<B>, gx: i32, gz: i32| {
            w.fill_raw([ox + gx, 64, oz + gz], [ox + gx, 63 + h, oz + gz], 0);
        };
        let mut s = seed | 1;
        let mut seen = vec![false; (n * n) as usize];
        let mut stack = vec![(0, 0)];
        seen[0] = true;
        carve(w, 1, 1);
        while let Some(&(cx, cz)) = stack.last() {
            let nb: Vec<(i32, i32)> = [(1, 0), (-1, 0), (0, 1), (0, -1)]
                .iter()
                .map(|(dx, dz)| (cx + dx, cz + dz))
                .filter(|&(x, z)| x >= 0 && z >= 0 && x < n && z < n && !seen[(z * n + x) as usize])
                .collect();
            if nb.is_empty() {
                stack.pop();
                continue;
            }
            let (nx, nz) = nb[(rng(&mut s) % nb.len() as u64) as usize];
            seen[(nz * n + nx) as usize] = true;
            carve(w, 2 * nx + 1, 2 * nz + 1);
            carve(w, cx + nx + 1, cz + nz + 1);
            stack.push((nx, nz));
        }
        carve(w, 0, 1);
        carve(w, size - 1, size - 2);
    }

    /// A flat stone world over chunks -r..=r.
    pub(crate) fn flat(r: i32) -> ghast_physics::v1_8::MemoryWorld {
        flat_in(ghast_physics::v1_8::memory_world(), r)
    }

    /// [`flat`] in a world of any version with 1.8 raw ids (1.8 and 1.12).
    pub(crate) fn flat_in<B: Copy>(
        mut w: ghast_physics::MemoryWorld<B>,
        r: i32,
    ) -> ghast_physics::MemoryWorld<B> {
        w.load_chunks(-r, -r, r, r);
        w.fill_raw(
            [-16 * r, 63, -16 * r],
            [16 * r + 15, 63, 16 * r + 15],
            STONE18,
        );
        w
    }

    fn follower() -> Follower {
        Follower::new(Pathfinder::new(Config::default()), FollowConfig::default())
    }

    /// Movement only: the behaviour looks a fixed way (a fight's target) the whole time, the
    /// follower never touches the aim and still walks the maze with strafe-relative keys.
    #[test]
    fn movement_only_walks_a_maze_with_the_behaviours_look() {
        for (n, seed) in [(7, 3u64), (15, 5)] {
            let mut w = flat(6);
            maze(&mut w, (-n, -n), n, 2, seed);
            let c = if n % 2 == 1 { 0 } else { 1 };
            let goal = Goal::Near {
                pos: [c, 64, c],
                radius: 1.0,
            };
            let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
            for look in [37.0f32, -120.0, 180.0] {
                let mut f = Follower::new(
                    Pathfinder::new(Config::default()),
                    FollowConfig::default().with_movement_only(true),
                );
                f.goto(goal.clone());
                let mut io = SimIo::<P18, _>::new(&w, from);
                let mut status = FollowStatus::Moving;
                let mut ticks = 0;
                while ticks < 20_000 {
                    io.set_aim(look, 0.0);
                    status = f.step(&mut io);
                    if status != FollowStatus::Moving {
                        break;
                    }
                    assert!(!f.aiming(), "a plain walk aimed");
                    io.advance();
                    ticks += 1;
                }
                eprintln!(
                    "maze {n} look {look}: {status:?} in {ticks} ticks, {} plans",
                    f.plans()
                );
                assert_eq!(status, FollowStatus::Arrived, "maze {n} look {look}");
                assert!(goal.is_reached(Pathfinder::start_block(io.feet())));
            }
        }
    }

    /// Mazes of 15, 31 and 63 blocks: the bot starts outside, the goal is the centre cell,
    /// whose way through the maze is many times the straight distance.
    #[test]
    fn mazes_are_solved() {
        for (n, seed) in [(7, 3u64), (15, 5), (31, 7)] {
            let mut w = flat(6);
            maze(&mut w, (-n, -n), n, 2, seed);
            let centre = [
                if n % 2 == 1 { 0 } else { 1 },
                64,
                if n % 2 == 1 { 0 } else { 1 },
            ];
            let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
            let d = drive::<P18, _>(
                &w,
                from,
                follower(),
                Goal::Near {
                    pos: centre,
                    radius: 1.0,
                },
                20_000,
            );
            eprintln!("maze {}: {d:?}", 2 * n + 1);
            assert_eq!(d.status, FollowStatus::Arrived, "maze {}", 2 * n + 1);
            let end = Pathfinder::start_block(d.end);
            assert!(
                Goal::Near {
                    pos: centre,
                    radius: 1.0
                }
                .is_reached(end)
            );
        }
    }

    /// Unreachable goals end cleanly: the bot walks to the reachable block closest to the
    /// goal, then fails with `NoPath`, after a single search (no second full search from the
    /// closest block).
    #[test]
    fn unreachable_goals_end_after_one_search() {
        // A goal in the air (a flying player) and a goal sealed inside a maze.
        let w = flat(4);
        let d = drive::<P18, _>(
            &w,
            [-20.5, 64.0, 3.5],
            follower(),
            Goal::Near {
                pos: [10, 70, -4],
                radius: 2.0,
            },
            3000,
        );
        assert_eq!(
            d.status,
            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
            "{d:?}"
        );
        assert_eq!(d.plans, 1, "{d:?}");
        let end = Pathfinder::start_block(d.end);
        assert!((end[0] - 10).abs() <= 1 && (end[2] + 4).abs() <= 1, "{d:?}");
        let mut w = flat(4);
        maze(&mut w, (-15, -15), 15, 2, 11);
        w.fill_raw([-2, 64, -2], [2, 65, 2], STONE18);
        w.fill_raw([0, 64, 0], [0, 65, 0], 0);
        let d = drive::<P18, _>(
            &w,
            [-18.5, 64.0, 18.5],
            follower(),
            Goal::Block([0, 64, 0]),
            20_000,
        );
        assert_eq!(
            d.status,
            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
            "{d:?}"
        );
        assert_eq!(d.plans, 1, "{d:?}");
    }

    /// A node budget far below what the maze needs: partial paths into dead ends must not make
    /// the bot wander (and search) forever.
    #[test]
    fn capped_searches_give_up() {
        let mut w = flat(4);
        maze(&mut w, (-31, -31), 31, 2, 13);
        let f = Follower::new(
            Pathfinder::new(Config::default().with_max_nodes(1500)),
            FollowConfig::default(),
        );
        let d = drive::<P18, _>(&w, [-34.5, 64.0, -29.5], f, Goal::Block([0, 64, 0]), 40_000);
        eprintln!("{d:?}");
        assert_ne!(d.status, FollowStatus::Moving, "still wandering: {d:?}");
        assert!(d.plans <= 20, "{d:?}");
    }

    /// The per-tick work stays in the budget on the biggest maze. The wall-clock check runs
    /// only with `GHAST_TIMING` set, in release builds (debug builds are ~10 times slower,
    /// and a loaded machine stretches any tick).
    #[test]
    fn per_tick_budget_on_a_big_maze() {
        let mut w = flat(10);
        maze(&mut w, (-63, -63), 63, 2, 17);
        let budget = FollowConfig::default().budget;
        let d = drive::<P18, _>(
            &w,
            [-67.5, 64.0, 67.5],
            follower(),
            Goal::Near {
                pos: [1, 64, 1],
                radius: 1.0,
            },
            40_000,
        );
        eprintln!("maze 127, view distance 10: {d:?}");
        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
        if !cfg!(debug_assertions) && std::env::var_os("GHAST_TIMING").is_some() {
            let max = budget.time.unwrap() + Duration::from_millis(3);
            assert!(d.worst_tick <= max, "{d:?}");
        }
        let _ = P16::VERSION;
    }

    /// The parkour corridor of `lab/pathfinder-course.sh` (superflat: grass y 3, feet y 4),
    /// east and back west, driven by the follower.
    #[test]
    fn the_lab_parkour_corridor() {
        let w = corridor(ghast_physics::v1_8::memory_world());
        run_corridor::<P18, _>(&w);
        let w = corridor(ghast_physics::v1_12::memory_world());
        run_corridor::<P12, _>(&w);
    }

    /// The 1.12 rules through mazes and an unreachable goal as well.
    #[test]
    fn mazes_on_1_12() {
        let n = 15;
        let mut w = flat_in(ghast_physics::v1_12::memory_world(), 6);
        maze(&mut w, (-n, -n), n, 2, 5);
        let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
        let goal = Goal::Near {
            pos: [1, 64, 1],
            radius: 1.0,
        };
        let d = drive::<P12, _>(&w, from, follower(), goal, 20_000);
        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
        let air = Goal::Near {
            pos: [1, 70, 1],
            radius: 2.0,
        };
        let d = drive::<P12, _>(&w, from, follower(), air, 20_000);
        assert_eq!(
            d.status,
            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
            "{d:?}"
        );
        assert_eq!(d.plans, 1, "{d:?}");
    }

    fn corridor<B: Copy>(mut w: ghast_physics::MemoryWorld<B>) -> ghast_physics::MemoryWorld<B> {
        w.load_chunks(0, -2, 9, 2);
        w.fill_raw([0, 0, -32], [159, 0, 47], 7 << 4);
        w.fill_raw([0, 1, -32], [159, 2, 47], 3 << 4);
        w.fill_raw([0, 3, -32], [159, 3, 47], 2 << 4);
        for z in [-2, 2] {
            w.fill_raw([60, 1, z], [123, 7, z], STONE18);
        }
        w.fill_raw([123, 4, -2], [123, 7, 2], STONE18);
        let trench = |w: &mut ghast_physics::MemoryWorld<B>, a: i32, b: i32| {
            w.fill_raw([a, 1, -1], [b, 3, 1], 0);
        };
        trench(&mut w, 66, 66);
        trench(&mut w, 71, 72);
        trench(&mut w, 77, 79);
        trench(&mut w, 84, 84);
        w.fill_raw([85, 4, -1], [89, 4, 1], STONE18);
        trench(&mut w, 90, 91);
        trench(&mut w, 96, 111);
        for (x, top) in [(98, 3), (100, 3), (104, 3), (107, 4), (109, 3)] {
            w.fill_raw([x, 1, 0], [x, top, 0], STONE18);
        }
        w
    }

    /// A 26.1 block's state id.
    fn id26(spec: &str) -> u16 {
        ghast_data::v26_1::BlockState::parse(spec)
            .unwrap_or_else(|| panic!("{spec}"))
            .id()
    }

    /// The lab corridor in a 26.1 world (same layout, 26.1 ids).
    fn corridor_26() -> ghast_physics::modern::MemoryWorld26 {
        let mut w = ghast_physics::modern::memory_world_26_1();
        let stone = id26("stone");
        w.load_chunks(0, -2, 9, 2);
        w.fill_raw([0, 0, -32], [159, 0, 47], id26("bedrock"));
        w.fill_raw([0, 1, -32], [159, 2, 47], id26("dirt"));
        w.fill_raw([0, 3, -32], [159, 3, 47], id26("grass_block"));
        for z in [-2, 2] {
            w.fill_raw([60, 1, z], [123, 7, z], stone);
        }
        w.fill_raw([123, 4, -2], [123, 7, 2], stone);
        let trench = |w: &mut ghast_physics::modern::MemoryWorld26, a: i32, b: i32| {
            w.fill_raw([a, 1, -1], [b, 3, 1], 0);
        };
        trench(&mut w, 66, 66);
        trench(&mut w, 71, 72);
        trench(&mut w, 77, 79);
        trench(&mut w, 84, 84);
        w.fill_raw([85, 4, -1], [89, 4, 1], stone);
        trench(&mut w, 90, 91);
        trench(&mut w, 96, 111);
        for (x, top) in [(98, 3), (100, 3), (104, 3), (107, 4), (109, 3)] {
            w.fill_raw([x, 1, 0], [x, top, 0], stone);
        }
        w
    }

    /// The parkour corridor driven by the follower on 26.1.
    #[test]
    fn the_lab_parkour_corridor_26_1() {
        run_corridor::<P26, _>(&corridor_26());
    }

    /// 26.1: a maze (in negative Y, under the overworld's old floor) and an unreachable goal.
    #[test]
    fn mazes_on_26_1() {
        let n = 15;
        let (y, stone) = (-40, id26("stone"));
        let mut w = ghast_physics::modern::memory_world_26_1();
        w.load_chunks(-6, -6, 6, 6);
        w.fill_raw([-96, y - 1, -96], [111, y - 1, 111], stone);
        let size = 2 * n + 1;
        let (ox, oz) = (-n, -n);
        w.fill_raw([ox, y, oz], [ox + size - 1, y + 1, oz + size - 1], stone);
        let mut s = 5u64 | 1;
        let mut seen = vec![false; (n * n) as usize];
        let mut stack = vec![(0, 0)];
        seen[0] = true;
        let carve = |w: &mut ghast_physics::modern::MemoryWorld26, gx: i32, gz: i32| {
            w.fill_raw([ox + gx, y, oz + gz], [ox + gx, y + 1, oz + gz], 0);
        };
        carve(&mut w, 1, 1);
        while let Some(&(cx, cz)) = stack.last() {
            let nb: Vec<(i32, i32)> = [(1, 0), (-1, 0), (0, 1), (0, -1)]
                .iter()
                .map(|(dx, dz)| (cx + dx, cz + dz))
                .filter(|&(x, z)| x >= 0 && z >= 0 && x < n && z < n && !seen[(z * n + x) as usize])
                .collect();
            if nb.is_empty() {
                stack.pop();
                continue;
            }
            let (nx, nz) = nb[(rng(&mut s) % nb.len() as u64) as usize];
            seen[(nz * n + nx) as usize] = true;
            carve(&mut w, 2 * nx + 1, 2 * nz + 1);
            carve(&mut w, cx + nx + 1, cz + nz + 1);
            stack.push((nx, nz));
        }
        carve(&mut w, 0, 1);
        carve(&mut w, size - 1, size - 2);
        let from = [
            f64::from(-n - 4) + 0.5,
            f64::from(y),
            f64::from(n + 4) + 0.5,
        ];
        let goal = Goal::Near {
            pos: [1, y, 1],
            radius: 1.0,
        };
        let d = drive::<P26, _>(&w, from, follower(), goal, 20_000);
        eprintln!("26.1 maze 31: {d:?}");
        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
        let air = Goal::Near {
            pos: [1, y + 6, 1],
            radius: 2.0,
        };
        let d = drive::<P26, _>(&w, from, follower(), air, 20_000);
        assert_eq!(
            d.status,
            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
            "{d:?}"
        );
        assert_eq!(d.plans, 1, "{d:?}");
    }

    /// The live attributes drive the look-ahead and the verification: with jump strength 0
    /// (a server attribute) a one-block step cannot be climbed, and the follower plans around
    /// it instead of jumping in place forever.
    #[test]
    fn live_attributes_26_1() {
        use ghast_physics::modern::AttributeKind;
        let stone = id26("stone");
        let mut w = ghast_physics::modern::memory_world_26_1();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-32, 63, -32], [31, 63, 31], stone);
        // A wall one block high across the way, with a gap at z = 6.
        w.fill_raw([4, 64, -32], [4, 64, 31], stone);
        w.set_raw(4, 64, 6, 0);
        let goal = Goal::Block([8, 64, 0]);
        // Default attributes: straight over the step.
        let d = drive::<P26, _>(&w, [0.5, 64.0, 0.5], follower(), goal.clone(), 2000);
        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
        // No jumping: around through the gap.
        let mut io = SimIo::<P26, _>::new(&w, [0.5, 64.0, 0.5]);
        io.state
            .apply_attribute(AttributeKind::JumpStrength, 0.0, &[]);
        let mut f = follower();
        f.goto(goal);
        let mut through_gap = false;
        let mut status = FollowStatus::Moving;
        for _ in 0..3000 {
            status = f.step(&mut io);
            if status != FollowStatus::Moving {
                break;
            }
            io.advance();
            let p = io.feet();
            through_gap |= p[0].floor() as i32 == 4 && p[2].floor() as i32 == 6;
        }
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert!(through_gap, "the step was not avoided");
        // Planned around at plan time (the move set follows the attributes), not by repairs.
        assert_eq!(f.plans(), 1, "replanned");
    }

    /// Digging straight down through dirt (the probe's `dig_down_6`), driven by the follower
    /// in a client that digs through its crosshair: six digs, each aimed a tick before it
    /// starts, and a goal level six blocks down.
    #[test]
    fn dig_down_6_follower() {
        let cfg = Config::default().with_dig(Some(crate::DigCost {
            base: 8.0,
            ticks_per_hardness: 30.0,
            max_hardness: 1.0,
        }));
        let mut w = flat(2);
        w.fill_raw([-3, 64, -3], [3, 69, 3], 3 << 4);
        let f = Follower::new(Pathfinder::new(cfg.clone()), FollowConfig::default());
        let mut io = SimIo::<P18, _>::new(&w, [0.5, 70.0, 0.5]);
        let status = run(&mut io, f, Goal::Block([0, 64, 0]), 2000);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(Pathfinder::start_block(io.feet()), [0, 64, 0]);
        // 26.2 (the version the probe runs).
        let mut w = ghast_physics::modern::memory_world_26_2();
        w.load_chunks(-1, -1, 1, 1);
        w.fill_raw([-8, 63, -8], [8, 63, 8], id262("stone"));
        w.fill_raw([-3, 64, -3], [3, 69, 3], id262("dirt"));
        let f = Follower::new(Pathfinder::new(cfg), FollowConfig::default());
        let mut io = SimIo::<P262, _>::new(&w, [0.5, 70.0, 0.5]);
        let status = run(&mut io, f, Goal::Y(64), 2000);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(Pathfinder::start_block(io.feet())[1], 64);
    }

    /// Through a closed oak door (the probe's `door_closed`) and an open one, driven by the
    /// follower in a client that clicks through its crosshair; the approach comes in at an
    /// angle, so the walk lines up with the door's free side on its own.
    #[test]
    fn doors_follower() {
        for open in [false, true] {
            for hinge in ["left", "right"] {
                let mut w = ghast_physics::modern::memory_world_26_2();
                w.load_chunks(-2, -2, 2, 2);
                w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
                w.fill_raw([3, 64, -32], [3, 66, 31], id262("stone"));
                for (y, half) in [(64, "lower"), (65, "upper")] {
                    w.set_raw(
                        3,
                        y,
                        0,
                        id262(&format!(
                            "oak_door[facing=east,half={half},hinge={hinge},open={open}]"
                        )),
                    );
                }
                let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, -3.5]);
                let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
                assert_eq!(
                    status,
                    FollowStatus::Arrived,
                    "open {open} {hinge}: {:?}",
                    io.feet()
                );
                assert_eq!(io.clicks, u32::from(!open), "open {open} {hinge}");
            }
        }
        // 1.8.9: the door's state is split over both halves.
        let mut w = flat(2);
        w.fill_raw([3, 64, -32], [3, 66, 31], STONE18);
        w.set_raw(3, 64, 0, 64 << 4); // lower half: facing east, closed
        w.set_raw(3, 65, 0, 64 << 4 | 8); // upper half: left hinge
        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, -3.5]);
        let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(io.clicks, 1);
    }

    /// Bridging over a three-wide gap and towering up three blocks (the probe's
    /// `bridge_gap_3` and `tower_up_3`), driven by the follower in a client that places only
    /// where its crosshair, from the pose the server has, is on the clicked face and the new
    /// block clears the player.
    #[test]
    fn bridge_and_tower_follower() {
        let cfg = Config::default().with_place(Some(20.0)).with_parkour(false);
        let follower = || Follower::new(Pathfinder::new(cfg.clone()), FollowConfig::default());
        // 26.2
        let stone = id262("stone");
        let mut w = ghast_physics::modern::memory_world_26_2();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-8, 63, -8], [1, 63, 8], stone);
        w.fill_raw([5, 63, -8], [12, 63, 8], stone);
        let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, 0.5]);
        let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 2000);
        assert_eq!(
            status,
            FollowStatus::Arrived,
            "bridge 26.2: {:?}",
            io.feet()
        );
        assert_eq!(io.places, 3, "bridge 26.2");
        assert_eq!(
            io.overlapping, 0,
            "bridge 26.2: a place overlapped the player"
        );
        let mut w = ghast_physics::modern::memory_world_26_2();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-8, 63, -8], [8, 63, 8], stone);
        let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, 0.5]);
        let status = run(&mut io, follower(), Goal::Block([0, 67, 0]), 2000);
        assert_eq!(status, FollowStatus::Arrived, "tower 26.2: {:?}", io.feet());
        assert_eq!(io.places, 3, "tower 26.2");
        assert_eq!(
            io.overlapping, 0,
            "tower 26.2: a place overlapped the player"
        );
        // 1.8.9
        let mut w = ghast_physics::v1_8::memory_world();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-8, 63, -8], [1, 63, 8], STONE18);
        w.fill_raw([5, 63, -8], [12, 63, 8], STONE18);
        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, 0.5]);
        let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 2000);
        assert_eq!(status, FollowStatus::Arrived, "bridge 1.8: {:?}", io.feet());
        let w = flat(2);
        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, 0.5]);
        let status = run(&mut io, follower(), Goal::Block([0, 67, 0]), 2000);
        assert_eq!(status, FollowStatus::Arrived, "tower 1.8: {:?}", io.feet());
        assert_eq!(
            io.overlapping, 0,
            "tower 1.8: a place overlapped the player"
        );
    }

    /// A staircase down through dirt to a goal ten lower and ten away, on 26.2, driven by the
    /// follower in a client that digs through its crosshair.
    #[test]
    fn staircase_follower() {
        let cfg = Config::default().with_dig(Some(crate::DigCost {
            base: 8.0,
            ticks_per_hardness: 30.0,
            max_hardness: 1.0,
        }));
        let mut w = ghast_physics::modern::memory_world_26_2();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
        w.fill_raw([-32, 64, -32], [31, 80, 31], id262("dirt"));
        w.fill_raw([0, 74, 0], [0, 75, 0], 0);
        let f = Follower::new(Pathfinder::new(cfg), FollowConfig::default());
        let mut io = SimIo::<P262, _>::new(&w, [0.5, 74.0, 0.5]);
        let status = run(&mut io, f, Goal::Block([10, 64, 0]), 6000);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
    }

    /// A closed oak trapdoor at head height in a two-high opening, clicked open through the
    /// crosshair (26.2 and 1.8.9).
    #[test]
    fn trapdoor_follower() {
        let mut w = ghast_physics::modern::memory_world_26_2();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
        w.fill_raw([3, 64, -32], [3, 66, 31], id262("stone"));
        w.set_raw(3, 64, 0, 0);
        w.set_raw(
            3,
            65,
            0,
            id262("oak_trapdoor[facing=north,half=bottom,open=false]"),
        );
        let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, -2.5]);
        let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(io.clicks, 1);
        let mut w = flat(2);
        w.fill_raw([3, 64, -32], [3, 66, 31], STONE18);
        w.set_raw(3, 64, 0, 0);
        w.set_raw(3, 65, 0, 96 << 4); // trapdoor, facing north, bottom half, closed
        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, -2.5]);
        let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(io.clicks, 1);
    }

    /// A 26.2 block's state id.
    pub(crate) fn id262(spec: &str) -> u16 {
        ghast_data::v26_2::BlockState::parse(spec)
            .unwrap_or_else(|| panic!("{spec}"))
            .id()
    }

    /// Drives a follower in `io` to `goal` for at most `max` ticks.
    pub(crate) fn run<P: Physics, W: BlockSource>(
        io: &mut SimIo<'_, P, W>,
        mut f: Follower,
        goal: Goal,
        max: u32,
    ) -> FollowStatus {
        f.goto(goal);
        let mut status = FollowStatus::Moving;
        for _ in 0..max {
            status = f.step(io);
            if status != FollowStatus::Moving {
                break;
            }
            io.advance();
        }
        status
    }

    fn run_corridor<P: Physics, W: BlockSource>(w: &W) {
        let d = drive::<P, _>(
            w,
            [62.5, 4.0, 0.5],
            follower(),
            Goal::Xz { x: 119, z: 0 },
            4000,
        );
        eprintln!("{:?} east: {d:?}", P::VERSION);
        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
        let d = drive::<P, _>(w, d.end, follower(), Goal::Xz { x: 62, z: 0 }, 4000);
        eprintln!("{:?} west: {d:?}", P::VERSION);
        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
    }
}

/// 26.3: the follower through the blocks new in 26.3, in the simulated client of
/// [`tests`] (clicks, digs and places through the crosshair of the pose the server has).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_3"
))]
mod tests_26_3 {
    use super::tests::{SimIo, run};
    use super::{FollowConfig, FollowStatus, Follower};
    use crate::Goal;
    use crate::physics::P263;
    use crate::plan::{Config, Pathfinder};

    fn id(spec: &str) -> u16 {
        ghast_data::v26_3::BlockState::parse(spec)
            .unwrap_or_else(|| panic!("{spec}"))
            .id()
    }

    fn follower() -> Follower {
        Follower::new(Pathfinder::new(Config::default()), FollowConfig::default())
    }

    /// Stone floor at y = 63 and a stone wall at x = 3 (y 64..=66) with an opening at z = 0.
    fn walled() -> ghast_physics::modern::MemoryWorld263 {
        let mut w = ghast_physics::modern::memory_world_26_3();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
        w.fill_raw([3, 64, -32], [3, 66, 31], id("stone"));
        w.fill_raw([3, 64, 0], [3, 65, 0], 0);
        w
    }

    /// A closed and an open poplar door, both hinges.
    #[test]
    fn poplar_door() {
        for open in [false, true] {
            for hinge in ["left", "right"] {
                let mut w = walled();
                for (y, half) in [(64, "lower"), (65, "upper")] {
                    w.set_raw(
                        3,
                        y,
                        0,
                        id(&format!(
                            "poplar_door[facing=east,half={half},hinge={hinge},open={open}]"
                        )),
                    );
                }
                let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -3.5]);
                let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
                assert_eq!(
                    status,
                    FollowStatus::Arrived,
                    "open {open} {hinge}: {:?}",
                    io.feet()
                );
                assert_eq!(io.clicks, u32::from(!open), "open {open} {hinge}");
            }
        }
    }

    /// A closed poplar fence gate in a poplar fence (1.5 high: no jumping over it).
    #[test]
    fn poplar_fence_gate() {
        let mut w = ghast_physics::modern::memory_world_26_3();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
        w.fill_raw(
            [3, 64, -32],
            [3, 64, 31],
            id("poplar_fence[east=false,north=true,south=true,waterlogged=false,west=false]"),
        );
        w.set_raw(
            3,
            64,
            0,
            id("poplar_fence_gate[facing=east,in_wall=false,open=false,powered=false]"),
        );
        let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -2.5]);
        let status = run(&mut io, follower(), Goal::Block([7, 64, 1]), 1500);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(io.clicks, 1);
    }

    /// A closed poplar trapdoor at head height in a two-high opening.
    #[test]
    fn poplar_trapdoor() {
        let mut w = walled();
        w.set_raw(
            3,
            65,
            0,
            id("poplar_trapdoor[facing=north,half=bottom,open=false,powered=false,waterlogged=false]"),
        );
        let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -2.5]);
        let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
        assert_eq!(io.clicks, 1);
    }

    /// Up a staircase of half steps (concrete slabs, bottom and double) and the matching
    /// concrete stairs, to a goal three blocks higher.
    #[test]
    fn concrete_slab_staircase() {
        let bottom = id("white_concrete_slab[type=bottom,waterlogged=false]");
        let double = id("white_concrete_slab[type=double,waterlogged=false]");
        let stairs =
            id("red_concrete_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]");
        for (name, step) in [("slabs", None), ("stairs", Some(stairs))] {
            let mut w = ghast_physics::modern::memory_world_26_3();
            w.load_chunks(-2, -2, 2, 2);
            w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
            // x = 2k + 2: a half step at height k, x = 2k + 3: a full block (k = 0, 1, 2).
            for k in 0..3 {
                let x = 2 * k + 2;
                w.fill_raw([x, 64, -1], [x + 1, 63 + k, 1], double);
                w.fill_raw([x, 64 + k, -1], [x, 64 + k, 1], step.unwrap_or(bottom));
                w.fill_raw([x + 1, 64 + k, -1], [x + 1, 64 + k, 1], double);
            }
            w.fill_raw([8, 64, -1], [10, 66, 1], double);
            let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
            let status = run(&mut io, follower(), Goal::Block([9, 67, 0]), 2000);
            assert_eq!(status, FollowStatus::Arrived, "{name}: {:?}", io.feet());
        }
    }

    /// Shelf mushrooms (ledges at y 0.375..0.6875 that bounce 0.75): the planner does not
    /// stand on a partial block that floats above its cell's bottom (`moves::spot`), so a
    /// mushroom is an obstacle: walked around in the open, and no plan when it is the only
    /// step onto a platform 1.5 high (a bottom slab in its place is climbed, see the check).
    #[test]
    fn shelf_mushroom_is_an_obstacle() {
        let mut w = ghast_physics::modern::memory_world_26_3();
        w.load_chunks(-2, -2, 2, 2);
        w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
        w.fill_raw(
            [3, 64, -1],
            [3, 64, 1],
            id("shelf_mushroom[age=1,facing=west]"),
        );
        let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
        let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 1500);
        assert_eq!(status, FollowStatus::Arrived, "around: {:?}", io.feet());

        for (step, arrives) in [
            ("shelf_mushroom[age=1,facing=west]", false),
            ("smooth_stone_slab[type=bottom,waterlogged=false]", true),
        ] {
            let mut w = ghast_physics::modern::memory_world_26_3();
            w.load_chunks(-2, -2, 2, 2);
            w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
            w.fill_raw([4, 64, -32], [10, 64, 31], id("stone"));
            w.fill_raw(
                [4, 65, -32],
                [10, 65, 31],
                id("smooth_stone_slab[type=bottom,waterlogged=false]"),
            );
            w.set_raw(3, 64, 0, id(step));
            let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
            let status = run(&mut io, follower(), Goal::Block([6, 65, 0]), 2000);
            assert_eq!(
                status == FollowStatus::Arrived,
                arrives,
                "{step}: {status:?} {:?}",
                io.feet()
            );
        }
    }
}