ghast-client 0.5.0

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2)
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
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
//! 1.12.2: the chunk store and the vanilla-exact physics.

use ghast_protocol::{BlockPos, RawPacket};

use super::*;
use crate::common::{Abilities, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};

// ---- 1.12.2: ghast-physics --------------------------------------------------------------

/// 1.12 blocks whose client `Block.onUse` answers a right click: the 1.8 list plus the 1.9 – 1.12
/// additions (command blocks, shulker boxes, structure block).
fn activates_1_12(id: u8) -> bool {
    ACTIVATED_1_8.contains(&id) || matches!(id, 137 | 210 | 211 | 219..=234 | 255)
}

/// The 1.12 ray box of a block: the oracle's selection bounds for static shapes; for shapes that
/// follow the neighbours the union of the actual collision boxes (an approximation of vanilla's
/// per-state outline, as for 1.16.5).
fn ray_1_12(w: &ghast_world::v1_12::World, x: i32, y: i32, z: i32) -> Option<[f64; 6]> {
    let s = w.block_state(x, y, z)?;
    let sel = s.selection();
    if !sel.can_collide {
        return None;
    }
    if sel.dependency == ghast_data::ShapeDependency::None {
        let b = sel.bounds;
        return Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]);
    }
    let local: Vec<ghast_data::Aabb> = ghast_physics::v1_12::collision_boxes(w, x, y, z)
        .iter()
        .map(|b| {
            let (fx, fy, fz) = (f64::from(x), f64::from(y), f64::from(z));
            ghast_data::Aabb::new(
                b.min_x - fx,
                b.min_y - fy,
                b.min_z - fz,
                b.max_x - fx,
                b.max_y - fy,
                b.max_z - fz,
            )
        })
        .collect();
    union(&local).or_else(|| {
        let b = sel.bounds;
        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
    })
}

/// 1.12.2: the chunk store and the vanilla-exact physics.
pub(crate) struct Sim12 {
    world: ghast_world::v1_12::World,
    player: ghast_physics::v1_12::PlayerState,
    packets: ghast_physics::Packets,
    force_step_position: ForceStepPosition,
    entities: Option<ghast_entity::v1_12::Tracker>,
    /// Block changes since the last drain (position, version raw state), when collected.
    updates: BlockUpdates,
    /// The session's last join and respawn packets: a tracker started mid-session replays
    /// them to learn our entity id and dimension.
    session: SessionPackets,
    /// The world keeps block entities.
    block_entities: bool,
    /// With entity tracking: the client side of the entities that push the player or are solid
    /// for it, and the teams' collision rules.
    near: Option<Box<Near12>>,
    /// The player's scoreboard name (team rules).
    profile_name: Box<str>,
    /// Entities push the player (`Client::entity_push`).
    entity_push: bool,
    /// Movement state beyond the player: gliding.
    ext: ghast_physics::v1_12::PlayerExt,
    /// Gliding: the server's flag 7 and the firework rockets attached to us.
    glide: Box<Glide12>,
    /// The extension state can act (an elytra, gliding, rockets): the tick takes
    /// [`Sim12::step_ext`] and the rockets tick after it.
    glide_on: bool,
    /// Movement recording ([`crate::Client::record`]).
    rec: Option<crate::record::Recorder>,
    /// The boat we ride and control (`set_passengers` naming us, with entity tracking).
    ride: Option<Box<Ride12>>,
    /// The answer to a server packet that goes out at once (`vehicle_move`).
    reply: Option<Outbound>,
    /// The flags byte (entity data index 0) the server last sent for our entity.
    server_flags: Option<u8>,
    /// Our living (hand) flags, entity data index 6, when a packet set them (taken per tick).
    living_flags: Option<u8>,
    /// The absorption the server last sent for our entity (player entity data; 0 before any).
    absorption: f32,
    /// `absorption` changed since the engine last took it.
    absorption_dirty: bool,
    /// The client world's map id counter (`getIntState("map")`): empty maps used since the
    /// world was made (join, a respawn into another dimension).
    maps: std::sync::atomic::AtomicI16,
    /// Blocks pistons move (the client runs the piston itself on a block-action packet).
    pistons: ghast_physics::v1_12::Pistons,
    /// World changes of the pistons, applied right away (kept to reuse the allocation).
    piston_edits: ghast_physics::v1_12::Edits,
    /// An unmodelled piston condition in the last movement step or the packets since
    /// ([`super::WorldView::piston_uncertain`]): the player's `ticks_alive` when it was raised (it
    /// holds while that counter has not moved on, so the plain tick never touches it).
    piston_uncertain_at: Option<i32>,
    /// Client ticks so far: the world time pistons compare (it advances by one per tick).
    piston_time: i64,
    /// The per-world-tick piston budget of the entities a piston moved that the near-entity
    /// model does not hold (armor stands, bats).
    piston_carry: Vec<(i32, ghast_physics::v1_12::PistonCarry)>,
}

/// The vehicle the player rides: its entity id and its client-side state.
#[derive(Debug)]
struct Ride12 {
    id: i32,
    seat: Seat12,
}

/// The boat the client moves, or the minecart the server moves.
#[derive(Debug)]
enum Seat12 {
    Boat(ghast_physics::v1_12::Boat),
    Cart(ghast_physics::v1_12::Minecart),
}

/// What the 1.12.2 glide reads beyond the physics state, decoded once an elytra was seen in the
/// chest slot: our shared flags (the server starts and ends the glide) and the rockets attached
/// to us.
#[derive(Debug, Default)]
struct Glide12 {
    /// Our entity data, rocket spawns and entity removals are read.
    watch: bool,
    /// The packet filter must change ([`Sim::take_filter_dirty`]).
    filter_dirty: bool,
    /// Our entity id (the tick's).
    own_id: i32,
    /// Firework rockets spawned but not (yet) known as attached to us: id, spawn height.
    pending: Vec<(i32, f64)>,
    /// The rockets attached to us, in the client world's entity list order (they tick after
    /// us): id, height (the spawn height, then ours after each of its ticks).
    rockets: Vec<(i32, f64)>,
}

/// The 1.12.2 spawn-object type of a firework rocket.
const FIREWORK_ROCKET_12: i8 = 76;

impl std::fmt::Debug for Sim12 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sim12")
            .field("world", &self.world)
            .field("pos", &self.player.pos)
            .finish_non_exhaustive()
    }
}

/// The dimension a 1.12.2 login (`login_id`) or respawn packet names.
fn dimension_of(raw: Option<&RawPacket>, login_id: i32) -> Option<i32> {
    let raw = raw?;
    // login: entity id (int), game mode (byte), dimension (int); respawn: dimension first
    let at = if raw.id == login_id { 5 } else { 0 };
    let b = raw.body.get(at..at + 4)?;
    Some(i32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}

impl Sim12 {
    /// The dimension of the session's last join or respawn (`None`: none seen).
    fn dimension(&self) -> Option<i32> {
        dimension_of(
            self.session
                .respawn
                .as_ref()
                .or(self.session.login.as_ref()),
            ghast_protocol::v1_12_2::play::clientbound::id::LOGIN,
        )
    }

    /// Test hook: sets one block.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_set_block(
        &mut self,
        x: i32,
        y: i32,
        z: i32,
        st: ghast_data::v1_12::BlockState,
    ) {
        self.world.set_block_state(x, y, z, st);
    }

    /// Test hook: the player state (from an oracle record).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_set_player(&mut self, p: ghast_physics::v1_12::PlayerState) {
        self.player = p;
        self.piston_uncertain_at = None;
        // The oracle's player is in its chunk's entity list from the setup on.
        if let Some(n) = self.near.as_deref_mut()
            && p.added_to_chunk
        {
            n.list_seq += 1;
            n.me = Some((section_of(p.pos), n.list_seq));
        }
    }

    /// Test hook: the client position and box of a tracked entity that pushes or collides.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_near_box(&self, id: i32) -> Option<([f64; 3], ghast_physics::math::Aabb)> {
        let n = self.near.as_deref()?;
        let &k = n.index.get(&id)?;
        let c = &n.list[k as usize];
        Some((c.at, c.bb))
    }

    /// Test hook: the chunk store.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_world(&self) -> &ghast_world::v1_12::World {
        &self.world
    }

    /// Test hook: the player state.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_player(&self) -> &ghast_physics::v1_12::PlayerState {
        &self.player
    }

    /// Test hook: the player's scoreboard name (team rules).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_set_profile_name(&mut self, name: &str) {
        self.profile_name = name.into();
    }

    /// Test hook: our flags and rockets are read from now on (as after a jump press in the air
    /// with an elytra on).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_watch_glide(&mut self) {
        self.glide.watch = true;
        self.glide.own_id = 1;
    }

    /// Test hook: the bits of our shared flags byte movement reads.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_shared_flags_1_12(&self) -> u8 {
        self.ext.shared_flags(&self.player)
    }

    pub(crate) fn new() -> Self {
        Sim12 {
            world: ghast_world::v1_12::World::new(config()),
            player: fresh_player_1_12(),
            packets: ghast_physics::Packets::new(),
            force_step_position: ForceStepPosition::Off,
            entities: None,
            updates: BlockUpdates::default(),
            session: SessionPackets::default(),
            block_entities: false,
            near: None,
            profile_name: "".into(),
            entity_push: true,
            ext: ghast_physics::v1_12::PlayerExt::new(),
            glide: Box::default(),
            glide_on: false,
            rec: None,
            ride: None,
            reply: None,
            server_flags: None,
            living_flags: None,
            absorption: 0.0,
            absorption_dirty: false,
            maps: std::sync::atomic::AtomicI16::new(0),
            pistons: ghast_physics::v1_12::Pistons::new(),
            piston_edits: ghast_physics::v1_12::Edits::new(),
            piston_uncertain_at: None,
            piston_time: 0,
            piston_carry: Vec::new(),
        }
    }

    /// `block_action`: a piston's extend / retract runs the client's piston (the 1.12 client
    /// lets the block at the position handle it).
    fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let p: cb::BlockAction = raw.decode_as()?;
        self.piston_edits.clear();
        self.pistons.block_event(
            &self.world,
            [p.location.x, p.location.y, p.location.z],
            (p.block_id & 4095) as u8,
            p.byte1,
            p.byte2,
            &mut self.piston_edits,
        );
        self.apply_piston_edits();
        Ok(())
    }

    /// The player's tick while blocks move (kept out of the plain tick's code): the extended
    /// tick's state and the entity boxes it collides with, then the moving blocks. Entity pushes
    /// and rocket boosts are not applied in these ticks.
    #[cold]
    #[inline(never)]
    fn step_pistons(&mut self, pose: &Pose, controls: Controls, using_item: bool) {
        if let Some(r) = &mut self.rec {
            r.note_once("moving pistons not representable");
        }
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            using_item,
        };
        let solids: &[ghast_physics::math::Aabb] =
            match (self.near.as_deref_mut(), self.entities.as_ref()) {
                (Some(n), Some(t)) if !n.idle() => {
                    n.solids(t, &self.world, &self.player);
                    &n.solids
                }
                _ => &[],
            };
        // The player's half: the moving blocks tick after every entity
        // ([`Sim12::tick_piston_phase`], from `tick_entities`).
        ghast_physics::v1_12::tick_player_among_pistons(
            &mut self.player,
            &mut self.ext,
            &input,
            &self.world,
            &ghast_physics::v1_12::Options::default(),
            solids,
            &self.pistons,
            &mut self.packets,
        );
    }

    /// The block-entity half of the client tick (`World.tickEntities` after every entity): the
    /// moving blocks advance and push the player and the other entities the client follows
    /// (it moves its copies itself; they interpolate on toward the server's positions), whose
    /// piston moves collide with the solid entities as they are at that moment.
    #[cold]
    #[inline(never)]
    fn tick_piston_phase(&mut self, pose: &mut Pose) {
        use ghast_physics::v1_12 as phys;
        if self.ride.is_some() {
            self.tick_piston_blocks();
            return;
        }
        // (search order, where it is kept, entity)
        type Other = ((i32, i32, i32, u64, u8), Kept, phys::PistonEntity);
        let mut others: Vec<Other> = Vec::new();
        let mut ghosts: Vec<ghast_physics::math::Aabb> = Vec::new();
        let mut player_key = None;
        let mut unmodelled = false;
        if let (Some(n), Some(t)) = (self.near.as_deref(), self.entities.as_ref()) {
            // The destroyed boats still in their chunks' lists.
            ghosts.extend(n.ghosts.iter().filter(|g| !g.cart).map(|g| g.bb));
            player_key = n.me.map(|(s, q)| (s[0], s[2], s[1], q, 0));
            for (k, c) in n.list.iter().enumerate() {
                let Some(e) = t.get(c.id) else { continue };
                if !Near12::present(t, &self.world, c) {
                    // Riders and carriers are not followed here.
                    unmodelled |= e.vehicle().is_some() && self.pistons.touches(&c.bb);
                    continue;
                }
                let name = match c.class {
                    Class12::Player => "player",
                    Class12::Boat => "boat",
                    Class12::Cart => "minecart",
                    _ => match e.entity_type() {
                        t @ ghast_entity::EntityType::LegacyMob(_) => {
                            ghast_entity::v1_12::info(t).map_or("", |i| i.name)
                        }
                        _ => "",
                    },
                };
                let living = !matches!(c.class, Class12::Boat | Class12::Cart);
                let alive = ghast_entity::v1_12::health(e).is_none_or(|h| h > 0.0);
                let spectator = c.class == Class12::Player && t.tab_game_mode(&e.uuid()) == Some(3);
                let pe = phys::PistonEntity {
                    bb: c.bb,
                    pos: c.at,
                    on_ground: c.on_ground,
                    in_web: c.in_web,
                    step_height: phys::step_height(name, living),
                    moved: !spectator,
                    collidable: matches!(c.class, Class12::Boat)
                        || (c.class == Class12::Shulker && alive),
                    pushable: !spectator
                        && phys::blocks_boat(
                            name,
                            living,
                            alive,
                            phys::entity_climbing(&self.world, c.at, c.bb.min_y),
                            !e.passengers().is_empty(),
                        ),
                    hits_pushable: phys::hits_pushable(name),
                    section: c.section,
                    carry: c.carry,
                };
                others.push((
                    (c.section[0], c.section[2], c.section[1], c.list_seq, 0),
                    Kept::Near(k),
                    pe,
                ));
            }
            // The entities a piston moves on the client that the near-entity model does not
            // hold: armor stands and bats (players, mobs, boats, minecarts and shulkers are
            // there); the solid objects it moves too (TNT, end crystals, falling blocks,
            // fireballs) are not followed.
            for e in t.iter() {
                use ghast_entity::EntityType as T;
                let name = match e.entity_type() {
                    T::LegacyObject(78) => "armor_stand",
                    ty @ T::LegacyMob(_)
                        if ghast_entity::v1_12::info(ty).is_some_and(|i| i.name == "bat") =>
                    {
                        "bat"
                    }
                    T::LegacyObject(50 | 51 | 63 | 70) => {
                        if let Some(b) = e.drawn_bounding_box() {
                            let bb =
                                ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
                            unmodelled |= self.pistons.touches(&bb);
                        }
                        continue;
                    }
                    _ => continue,
                };
                let (Some(b), Some(o)) = (e.drawn_bounding_box(), e.search_order()) else {
                    continue;
                };
                let bb = ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
                if e.vehicle().is_some() || !e.passengers().is_empty() {
                    unmodelled |= self.pistons.touches(&bb);
                    continue;
                }
                let section = [o.0, o.2, o.1];
                // Its place in its section's list among the near-entity model's entries: after
                // those that entered the list before it.
                let after = n
                    .list
                    .iter()
                    .filter(|c| {
                        c.section == section
                            && t.get(c.id)
                                .and_then(ghast_entity::Entity::search_order)
                                .is_some_and(|q| q.3 < o.3)
                    })
                    .map(|c| c.list_seq)
                    .max()
                    .unwrap_or(0);
                let carry = self
                    .piston_carry
                    .iter()
                    .find(|c| c.0 == e.id())
                    .map_or_else(Default::default, |c| c.1);
                let pe = phys::PistonEntity {
                    bb,
                    pos: e.drawn_position(),
                    on_ground: e.drawn_on_ground(),
                    in_web: e.drawn_in_web(),
                    step_height: phys::step_height(name, true),
                    moved: true,
                    collidable: false,
                    pushable: false,
                    hits_pushable: false,
                    section,
                    carry,
                };
                others.push((
                    (section[0], section[2], section[1], after, 1),
                    Kept::Extra(e.id()),
                    pe,
                ));
            }
        }
        others.sort_by_key(|c| c.0);
        let rank = player_key.map_or(others.len(), |o| others.iter().filter(|c| c.0 < o).count());
        let mut list: Vec<phys::PistonEntity> = others.iter().map(|c| c.2).collect();
        let f = |v: f64| (v.floor() as i32) >> 4;
        let p = self.player.pos;
        let place = phys::PlayerPlace {
            rank,
            section: [f(p[0]), f(p[1]).clamp(0, 15), f(p[2])],
        };
        self.piston_edits.clear();
        self.pistons.tick_after_entities_among(
            &mut self.player,
            &mut self.ext,
            &self.world,
            &ghosts,
            &mut list,
            place,
            self.piston_time,
            &mut self.piston_edits,
        );
        self.apply_piston_edits();
        // The client's own moves of its entity copies, which the crosshair picks there too.
        if let Some(n) = self.near.as_deref_mut() {
            for ((_, kept, before), after) in others.iter().zip(&list) {
                let k = match *kept {
                    Kept::Near(k) => k,
                    Kept::Extra(id) => {
                        if after.carry != before.carry {
                            match self.piston_carry.iter_mut().find(|c| c.0 == id) {
                                Some(c) => c.1 = after.carry,
                                None => self.piston_carry.push((id, after.carry)),
                            }
                        }
                        if after != before
                            && let Some(t) = self.entities.as_mut()
                        {
                            let b = after.bb;
                            t.client_pushed(
                                id,
                                after.pos,
                                [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                                after.on_ground,
                                after.in_web,
                            );
                        }
                        continue;
                    }
                };
                let c = &mut n.list[k];
                c.on_ground = after.on_ground;
                c.in_web = after.in_web;
                c.carry = after.carry;
                if after.bb != before.bb || after.pos != before.pos {
                    c.bb = after.bb;
                    c.at = after.pos;
                    if c.class == Class12::Shulker && c.attached {
                        // Its tick puts it back on its attached block.
                        c.pushed = true;
                    } else {
                        c.pos = after.pos;
                    }
                }
                if (after.bb != before.bb
                    || after.pos != before.pos
                    || after.on_ground != before.on_ground
                    || after.in_web != before.in_web)
                    && let Some(t) = self.entities.as_mut()
                {
                    let b = after.bb;
                    t.client_pushed(
                        c.id,
                        after.pos,
                        [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                        after.on_ground,
                        after.in_web,
                    );
                }
            }
        }
        if unmodelled {
            self.piston_uncertain_at = Some(self.player.ticks_alive);
        }
        sync_pose_12(pose, &self.player);
    }

    /// The moving blocks' tick while the player rides (they do not push it here).
    #[cold]
    #[inline(never)]
    fn tick_piston_blocks(&mut self) {
        self.piston_edits.clear();
        self.pistons
            .tick_blocks(&self.world, self.piston_time, &mut self.piston_edits);
        self.apply_piston_edits();
    }

    /// Writes the pistons' world changes into the chunk store.
    fn apply_piston_edits(&mut self) {
        for &([x, y, z], s) in &self.piston_edits {
            if self.world.set_block_state(x, y, z, s) {
                self.updates
                    .push(BlockPos::new(x, y, z), u32::from(s.raw()));
            }
        }
    }

    /// After a packet changed blocks: a moving block whose block is no longer a moving-piston
    /// block is gone.
    #[inline]
    fn prune_pistons(&mut self) {
        if !self.pistons.is_empty() {
            self.prune_pistons_slow();
        }
    }

    #[cold]
    #[inline(never)]
    fn prune_pistons_slow(&mut self) {
        let w = &self.world;
        self.pistons.retain(|m| {
            w.block_state(m.pos[0], m.pos[1], m.pos[2])
                .is_some_and(|s| s.block().id() == ghast_physics::v1_12::MOVING_PISTON)
        });
    }

    /// A sim with options (Grim compatibility, entities, world contents, movement recording).
    pub(crate) fn with(opts: &SimOptions) -> Self {
        let mut s = Self::new();
        s.force_step_position = opts.force_step_position;
        s.entities = opts.entities.map(ghast_entity::v1_12::Tracker::new);
        s.near = s.entities.is_some().then(Box::default);
        if let Some(n) = &opts.profile_name {
            s.profile_name = n.as_str().into();
        }
        if let Some(c) = opts.world {
            s.world = ghast_world::v1_12::World::new(c);
            s.block_entities = c.block_entities;
        }
        if opts.shared_chunks.is_some() {
            log::debug!("shared chunks are not used on 1.12.2; every section stays owned");
        }
        if let Some(p) = opts.record.as_deref() {
            match crate::record::Recorder::create(p) {
                Ok(r) => s.rec = Some(r),
                Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
            }
        }
        s
    }
}

impl Sim12 {
    /// Recomputes [`Sim12::glide_on`].
    fn update_glide(&mut self) {
        self.glide_on = !self.ext.is_inert() || !self.glide.rockets.is_empty();
    }

    /// The tick with the extension state (gliding, rockets): out of line, so the plain tick
    /// stays as it was.
    #[cold]
    #[inline(never)]
    fn step_ext(&mut self, pose: &Pose, controls: Controls, using_item: bool) {
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            using_item,
        };
        let solids: &[ghast_physics::math::Aabb] =
            match (self.near.as_deref_mut(), self.entities.as_ref()) {
                (Some(n), Some(t)) if !n.idle() => {
                    n.solids(t, &self.world, &self.player);
                    &n.solids
                }
                _ => &[],
            };
        ghast_physics::v1_12::tick_ext(
            &mut self.player,
            &mut self.ext,
            &input,
            &self.world,
            &ghast_physics::v1_12::Options::default(),
            solids,
            &mut self.packets,
        );
    }

    /// The attached rockets' ticks after ours (in the world's entity list after the entities
    /// spawned before them; the pushes of other entities come first here).
    #[cold]
    #[inline(never)]
    fn tick_rockets(&mut self, pose: &mut Pose) {
        for r in &mut self.glide.rockets {
            ghast_physics::v1_12::rocket_boost(&mut self.player, &self.ext);
            // Entity.baseTick: below y = -64 the rocket is removed, after this tick.
            if r.1 < -64.0 {
                r.0 = i32::MIN;
            }
            r.1 = self.player.pos[1];
        }
        self.glide.rockets.retain(|r| r.0 != i32::MIN);
        self.update_glide();
        let p = &self.player;
        pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
    }

    /// A rocket spawn, removal or entity data, or our own entity data: decoded only when it
    /// can concern us.
    #[cold]
    #[inline(never)]
    fn glide_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::defs::p340::types::EntityMetadataValue as V;
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let g = &mut self.glide;
        match raw.id {
            cb::id::SPAWN_ENTITY => {
                let p: cb::SpawnEntity = raw.decode_as()?;
                g.pending.retain(|r| r.0 != p.entity_id);
                g.rockets.retain(|r| r.0 != p.entity_id);
                if p.r#type == FIREWORK_ROCKET_12 {
                    if g.pending.len() >= 32 {
                        g.pending.remove(0);
                    }
                    g.pending.push((p.entity_id, p.y));
                }
            }
            cb::id::ENTITY_DESTROY => {
                let p: cb::EntityDestroy = raw.decode_as()?;
                for id in &p.entity_ids {
                    g.pending.retain(|r| r.0 != *id);
                    g.rockets.retain(|r| r.0 != *id);
                }
            }
            cb::id::ENTITY_METADATA => {
                let mut r = ghast_protocol::Reader::new(&raw.body);
                let id = r.read_varint()?;
                let own = id == g.own_id;
                let pending = g.pending.iter().position(|r| r.0 == id);
                if !own && pending.is_none() {
                    return Ok(());
                }
                let p: cb::EntityMetadata = raw.decode_as()?;
                for e in &p.metadata {
                    match (e.key, &e.value) {
                        // The shared flags: sprinting, fall flying (sneaking is the input's:
                        // `ClientPlayerEntity.isSneaking`).
                        (0, V::Byte(b)) if own => {
                            self.server_flags = Some(*b as u8);
                            self.ext.apply_shared_flags(&mut self.player, *b as u8);
                            if let Some(r) = &mut self.rec {
                                r.note("own entity flags not representable");
                            }
                        }
                        // LivingEntity's hand flags: the server's view of our item use.
                        (6, V::Byte(b)) if own => self.living_flags = Some(*b as u8),
                        // PlayerEntity's absorption amount (its first entry: 11).
                        (11, V::Float(a)) if own => {
                            self.absorption = *a;
                            self.absorption_dirty = true;
                        }
                        // A rocket's shooter (an entity id, 0 for none).
                        (7, V::VarInt(v)) if !own => {
                            if let Some(k) = pending {
                                let (rid, y) = g.pending.remove(k);
                                if *v == g.own_id {
                                    g.rockets.push((rid, y));
                                    log::debug!("firework rocket {rid} attached to us");
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
        self.update_glide();
        Ok(())
    }

    /// The player's tick next to tracked entities: with the boxes of the boats and shulkers
    /// around it. Out of line, so the tick without entities stays the plain one.
    #[cold]
    #[inline(never)]
    fn step_near(&mut self, pose: &Pose, controls: Controls, using_item: bool) {
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            using_item,
        };
        let (Some(n), Some(t)) = (self.near.as_deref_mut(), self.entities.as_ref()) else {
            return;
        };
        n.solids(t, &self.world, &self.player);
        ghast_physics::v1_12::tick_in(
            &mut self.player,
            &input,
            &self.world,
            &ghast_physics::v1_12::Options::default(),
            &n.solids,
            &mut self.packets,
        );
    }

    /// A tick in the boat we control (`ghast_physics::v1_12::tick_boat`), at the boat's place
    /// in the client world's entity list: the tracked entities before it step first (their
    /// interpolation, the lily pads their boats break), then the boat collides with the
    /// entities around it as they are then and the passenger with the boats and shulkers.
    /// Their pushes on the passenger are not applied (its motion is zeroed before its next
    /// tick, they change no packet).
    #[cold]
    #[inline(never)]
    fn step_ride(&mut self, pose: &Pose, controls: Controls) {
        let Some(r) = self.ride.as_deref_mut() else {
            return;
        };
        let id = r.id;
        let Seat12::Boat(boat) = &mut r.seat else {
            return;
        };
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            // The passenger tick has no item slowdown.
            using_item: false,
        };
        let (solids, boat_solids): (&[_], &[_]) =
            match (self.near.as_deref_mut(), self.entities.as_ref()) {
                (Some(n), Some(t)) => {
                    if let Some(&k) = n.index.get(&id) {
                        let seq = n.list[k as usize].seq;
                        n.tick(t, &self.world, &self.player.bb, false, "", 0..seq);
                        for &[x, y, z] in &n.lily_pads {
                            self.world
                                .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
                        }
                    }
                    n.solids(t, &self.world, &self.player);
                    // As far as the boat can move this tick (its velocity grows by at most
                    // the paddle and the flow push before the move).
                    let b = &*boat;
                    let reach = |v: f64| v.abs() + 3.0;
                    n.boat_solids(
                        t,
                        &self.world,
                        &b.bb,
                        [reach(b.vel[0]), reach(b.vel[1]), reach(b.vel[2])],
                    );
                    (&n.solids, &n.boat_solids)
                }
                _ => (&[], &[]),
            };
        let still = ghast_physics::v1_12::tick_boat(
            &mut self.player,
            &mut self.ext,
            boat,
            solids,
            boat_solids,
            &input,
            &self.world,
            &mut self.packets,
        );
        for &[x, y, z] in boat.broken_lily_pads() {
            self.world
                .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
        }
        let (pos, bb) = (boat.pos, boat.bb);
        if let Some(n) = self.near.as_deref_mut()
            && let Some(c) = n.get_mut(id)
        {
            // The entry follows the client's boat (its interpolation stays where it was).
            c.follow(pos, bb);
        }
        if !still {
            log::debug!("boat {id} fell out of the world");
            self.leave_boat();
        }
    }

    /// A tick in the minecart we sit in (`ghast_physics::v1_12::tick_minecart`), at the cart's
    /// place in the client world's entity list (the entities before it step first).
    #[cold]
    #[inline(never)]
    fn step_cart(&mut self, pose: &Pose, controls: Controls) {
        let Some(r) = self.ride.as_deref_mut() else {
            return;
        };
        let id = r.id;
        let Seat12::Cart(cart) = &mut r.seat else {
            return;
        };
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            // The passenger tick has no item slowdown.
            using_item: false,
        };
        let solids: &[_] = match (self.near.as_deref_mut(), self.entities.as_ref()) {
            (Some(n), Some(t)) => {
                if let Some(&k) = n.index.get(&id) {
                    let seq = n.list[k as usize].seq;
                    n.tick(t, &self.world, &self.player.bb, false, "", 0..seq);
                    for &[x, y, z] in &n.lily_pads {
                        self.world
                            .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
                    }
                }
                n.solids(t, &self.world, &self.player);
                &n.solids
            }
            _ => &[],
        };
        ghast_physics::v1_12::tick_minecart(
            &mut self.player,
            &mut self.ext,
            cart,
            solids,
            &input,
            &self.world,
            &mut self.packets,
        );
        let (pos, bb) = (cart.pos, cart.bb);
        if let Some(n) = self.near.as_deref_mut()
            && let Some(c) = n.get_mut(id)
        {
            c.follow(pos, bb);
        }
    }

    /// The server's moves of the minecart we sit in (`onEntityPosition` / `onEntityUpdate`; the
    /// entity list follows it, see [`Near12::ridden`]).
    #[cold]
    #[inline(never)]
    fn cart_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let Some(Ride12 {
            id,
            seat: Seat12::Cart(c),
        }) = self.ride.as_deref_mut()
        else {
            return Ok(());
        };
        let id = *id;
        match raw.id {
            cb::id::ENTITY_TELEPORT => {
                let p: cb::EntityTeleport = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch);
                }
            }
            cb::id::REL_ENTITY_MOVE => {
                let p: cb::RelEntityMove = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([p.d_x, p.d_y, p.d_z], None);
                }
            }
            cb::id::ENTITY_MOVE_LOOK => {
                let p: cb::EntityMoveLook = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)));
                }
            }
            cb::id::ENTITY_LOOK => {
                let p: cb::EntityLook = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([0; 3], Some((p.yaw, p.pitch)));
                }
            }
            cb::id::ENTITY => {
                let p: cb::Entity = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([0; 3], None);
                }
            }
            cb::id::ENTITY_DESTROY => {
                let p: cb::EntityDestroy = raw.decode_as()?;
                if p.entity_ids.contains(&id) {
                    log::debug!("minecart {id} destroyed");
                    self.leave_boat();
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// The player is off the boat it drove: the boat stays where it is on the client.
    fn leave_boat(&mut self) {
        self.ride = None;
        if let Some(n) = self.near.as_deref_mut() {
            n.ridden = None;
        }
    }

    /// Our entity id: the tracker's, else the join packet's.
    fn own_id(&self) -> i32 {
        self.entities
            .as_ref()
            .and_then(|t| t.self_id())
            .unwrap_or(self.glide.own_id)
    }

    /// `set_passengers` (boarding / leaving a boat) and `vehicle_move` (the server's correction
    /// of the boat we control: `onVehicleMove` applies it and answers with the boat's position at
    /// once).
    #[cold]
    #[inline(never)]
    fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        if raw.id == cb::id::VEHICLE_MOVE {
            if let Some(Ride12 {
                id: rid,
                seat: Seat12::Boat(boat),
            }) = self.ride.as_deref_mut()
            {
                let rid = *rid;
                let p: cb::VehicleMove = raw.decode_as()?;
                if let ghast_physics::Packet::MoveVehicle {
                    pos,
                    yaw,
                    pitch,
                    on_ground,
                } = boat.server_move([p.x, p.y, p.z], p.yaw, p.pitch)
                {
                    self.reply = Some(Outbound::VehicleMove {
                        pos: Vec3::new(pos[0], pos[1], pos[2]),
                        yaw,
                        pitch,
                        on_ground,
                    });
                }
                let (id, pos, bb) = (rid, boat.pos, boat.bb);
                if let Some(n) = self.near.as_deref_mut()
                    && let Some(c) = n.get_mut(id)
                {
                    c.follow(pos, bb);
                }
            }
            return Ok(());
        }
        let p: cb::SetPassengers = raw.decode_as()?;
        let on = p.passengers.contains(&self.own_id());
        let riding_it = self.ride.as_ref().is_some_and(|r| r.id == p.entity_id);
        if on && !riding_it {
            // A minecart: at its client position (the server's when it is not followed), with
            // the server's position of it for the relative moves.
            let cart = self.entities.as_ref().and_then(|t| {
                let e = t.get(p.entity_id)?;
                if e.entity_type() != ghast_entity::EntityType::LegacyObject(10) {
                    return None;
                }
                let pos = self
                    .near
                    .as_deref()
                    .and_then(|n| n.index.get(&p.entity_id).map(|&k| n.list[k as usize].pos))
                    .unwrap_or(e.position());
                let mut c = ghast_physics::v1_12::Minecart::new(pos, e.yaw(), e.pitch());
                c.tracked = e.position().map(|v| (v * 4096.0).floor() as i64);
                Some(c)
            });
            if let Some(cart) = cart {
                log::debug!("in minecart {}", p.entity_id);
                self.ride = Some(Box::new(Ride12 {
                    id: p.entity_id,
                    seat: Seat12::Cart(cart),
                }));
                if let Some(n) = self.near.as_deref_mut() {
                    n.ridden = Some(p.entity_id);
                }
                return Ok(());
            }
            // startRiding a boat the client knows: at its client position, with the rotation the
            // server last sent. Other vehicles are not simulated (the walking tick goes on).
            let boat = self.entities.as_ref().and_then(|t| {
                let e = t.get(p.entity_id)?;
                if e.entity_type() != ghast_entity::EntityType::LegacyObject(1) {
                    return None;
                }
                let pos = self
                    .near
                    .as_deref()
                    .and_then(|n| n.index.get(&p.entity_id).map(|&k| n.list[k as usize].pos))
                    .unwrap_or(e.position());
                Some(ghast_physics::v1_12::Boat::new(pos, e.yaw(), 0.0))
            });
            match boat {
                Some(boat) => {
                    log::debug!("riding boat {}", p.entity_id);
                    self.ride = Some(Box::new(Ride12 {
                        id: p.entity_id,
                        seat: Seat12::Boat(boat),
                    }));
                    if let Some(n) = self.near.as_deref_mut() {
                        n.ridden = Some(p.entity_id);
                    }
                }
                None => log::debug!(
                    "riding {} (not simulated: no entity tracking or not a boat)",
                    p.entity_id
                ),
            }
        } else if !on && riding_it {
            log::debug!("left boat {}", p.entity_id);
            self.leave_boat();
        }
        Ok(())
    }

    /// `World.tickEntities` after the player: the entities interpolate, the boats break lily
    /// pads, then they push the player. In a boat we control, only the entities after the boat
    /// in the entity list (the ones before it ticked before it, [`Sim12::step_ride`]).
    #[cold]
    #[inline(never)]
    fn tick_near(&mut self, pose: &mut Pose) {
        let (Some(n), Some(t)) = (self.near.as_deref_mut(), self.entities.as_ref()) else {
            return;
        };
        // The destroyed boats have left their chunks' entity lists.
        n.ghosts.clear();
        if n.list.is_empty() {
            return;
        }
        let seqs = match n.ridden.and_then(|id| n.index.get(&id)) {
            Some(&k) => n.list[k as usize].seq + 1..u64::MAX,
            None => 0..u64::MAX,
        };
        let p = &mut self.player;
        // `updateEntityWithOptionalForce` of the player: a new chunk entity list after its tick.
        if p.added_to_chunk {
            let sec = section_of(p.pos);
            if n.me.is_none_or(|m| m.0 != sec) {
                n.list_seq += 1;
                n.me = Some((sec, n.list_seq));
            }
        }
        // Only a ticking player is in its chunk's entity list, where the pushers find it; the
        // bot riding a vehicle the client does not move or carrying something is not pushed
        // (not modelled). In the boat we control, the entities after the boat push the
        // passenger: its next tick in the boat zeroes that motion, a walking one (the server
        // took it off in between) starts with it.
        let riding_ours = n.ridden.is_some();
        let pushing = self.entity_push
            && p.added_to_chunk
            && !p.removed
            && !t.me().is_some_and(|m| {
                (m.vehicle().is_some() && !riding_ours) || !m.passengers().is_empty()
            });
        n.tick(t, &self.world, &p.bb, pushing, &self.profile_name, seqs);
        let mut changed = false;
        for (_, pusher) in &n.pushers {
            changed |= ghast_physics::v1_12::push_by(p, &self.world, pusher);
        }
        if changed {
            pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
        }
        // A boat's tick breaks the lily pads it touches in the client's world.
        for &[x, y, z] in &n.lily_pads {
            self.world
                .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
        }
    }
}

/// A fresh 1.12 client player: not yet in a chunk (the first tick with its column loaded adds
/// it, the next one moves it), as vanilla.
fn fresh_player_1_12() -> ghast_physics::v1_12::PlayerState {
    let mut p = ghast_physics::v1_12::PlayerState::new([0.0; 3], 0.0, 0.0);
    p.added_to_chunk = false;
    p
}

impl WorldView for Sim12 {
    fn collisions(&self) -> (bool, bool) {
        (
            self.player.horizontal_collision,
            self.player.vertical_collision,
        )
    }

    fn piston_uncertain(&self) -> bool {
        self.piston_uncertain_at == Some(self.player.ticks_alive)
    }

    fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
        self.world.column(chunk_x, chunk_z)
    }

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

    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        self.world.block_state(x, y, z).map(|s| u32::from(s.raw()))
    }

    fn entities(&self) -> Option<&ghast_entity::Entities> {
        self.entities.as_deref()
    }

    fn loaded_columns(&self) -> usize {
        self.world.columns().len()
    }

    fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery> {
        let s = self.world.block_state(x, y, z)?;
        let b = s.block();
        let info = b.info();
        Some(BlockQuery {
            exact: Some(crate::hands::ExactDig::V1_12),
            air: b.material().kind == ghast_data::v1_12::MaterialKind::Air,
            water: matches!(b.id(), 8 | 9),
            block: u16::from(b.id()),
            hardness: info.hardness.unwrap_or(-1.0),
            dig_material: info.material,
            harvest_tools: info.harvest_tools,
            selection: ray_1_12(&self.world, x, y, z),
            stairs: None,
            activates: activates_1_12(b.id()),
        })
    }

    fn crosshair(
        &self,
        eyes: Vec3,
        (yaw, pitch): (f32, f32),
        _look: Vec3,
        reach: f64,
    ) -> Option<crate::BlockHit> {
        // The oracle-verified 1.12 pick (ghast_physics::pick::v1_12: vanilla's ray shapes,
        // Entity.rayTrace with the float look vector).
        use ghast_physics::pick::v1_12 as pick;
        let eye = [eyes.x, eyes.y, eyes.z];
        let hit = pick::pick(&self.world, eye, pick::look_vector(yaw, pitch), reach)?;
        block_hit(&hit, eye)
    }
}

impl Sim for Sim12 {
    fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
        // The oracle-verified GameRenderer.updateTargetedEntity: block ray at the game
        // mode's reach, then the entity ray.
        use ghast_physics::pick::v1_12 as pick;
        let eye = [q.eyes.x, q.eyes.y, q.eyes.z];
        let look = pick::look_vector(q.rotation.0, q.rotation.1);
        if q.entities.is_empty() {
            // pick_target without entities is its block pick (`target` returns it as is).
            let reach = if q.creative {
                pick::CREATIVE_REACH
            } else {
                pick::REACH
            };
            return Crosshair::Block(
                pick::pick(&self.world, eye, look, reach).and_then(|h| block_hit(&h, eye)),
            );
        }
        let t = pick::pick_target(&self.world, eye, look, q.creative, &q.player_bb, q.entities);
        legacy_crosshair(t, eye)
    }

    fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        {
            use ghast_protocol::v1_12_2::play::clientbound::id;
            if raw.id == id::LOGIN
                || (raw.id == id::RESPAWN && dimension_of(Some(raw), id::LOGIN) != self.dimension())
            {
                // a new client world
                *self.maps.get_mut() = 0;
            }
            self.session.note(raw, id::LOGIN, id::RESPAWN);
            // Our entity data always (the shared flags); rocket spawns and removals while
            // gliding can happen.
            if raw.id == id::ENTITY_METADATA
                || (self.glide.watch && matches!(raw.id, id::SPAWN_ENTITY | id::ENTITY_DESTROY))
            {
                self.glide_packet(raw)?;
            }
        }
        if let Some(t) = &mut self.entities
            && t.wants(raw.id)
        {
            t.apply(raw)?;
            if let Some(n) = &mut self.near {
                n.packet(t, raw);
            }
        }
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        if matches!(raw.id, cb::id::SET_PASSENGERS | cb::id::VEHICLE_MOVE) {
            return self.vehicle_packet(raw);
        }
        if matches!(
            raw.id,
            cb::id::ENTITY_TELEPORT
                | cb::id::REL_ENTITY_MOVE
                | cb::id::ENTITY_MOVE_LOOK
                | cb::id::ENTITY_LOOK
                | cb::id::ENTITY
                | cb::id::ENTITY_DESTROY
        ) && matches!(
            self.ride.as_deref(),
            Some(Ride12 {
                seat: Seat12::Cart(_),
                ..
            })
        ) {
            self.cart_packet(raw)?;
        }
        if raw.id == cb::id::TEAMS {
            if let Some(n) = &mut self.near
                && !n
                    .teams
                    .apply(&raw.body, super::teams::TeamLayout::Legacy1_12)
            {
                log::debug!("bad teams packet ({} B)", raw.body.len());
            }
            return Ok(());
        }
        if let Some(n) = &mut self.near
            && matches!(
                raw.id,
                cb::id::MAP_CHUNK
                    | cb::id::BLOCK_CHANGE
                    | cb::id::MULTI_BLOCK_CHANGE
                    | cb::id::LOGIN
                    | cb::id::RESPAWN
            )
        {
            n.world_version = n.world_version.wrapping_add(1);
        }
        let w = &mut self.world;
        match raw.id {
            cb::id::UPDATE_TIME => {
                // The client world's time (world age), which the piston move limit compares.
                let p: cb::UpdateTime = raw.decode_as()?;
                self.piston_time = p.age;
            }
            cb::id::LOGIN => {
                self.ride = None;
                self.pistons.clear();
                self.piston_time = 0;
                let p: cb::Login = raw.decode_as()?;
                // Our entity id (our entity data names us by it).
                self.glide.own_id = p.entity_id;
                w.apply_login(&p);
            }
            cb::id::RESPAWN => {
                self.ride = None;
                self.pistons.clear();
                w.apply_respawn(&raw.decode_as()?);
            }
            cb::id::MAP_CHUNK => {
                let p: cb::MapChunk = raw.decode_as()?;
                // A full chunk replaces the column and its block entities.
                if p.ground_up && !self.pistons.is_empty() {
                    self.pistons.chunk_replaced(p.x, p.z);
                }
                w.apply_map_chunk(&p)?;
            }
            cb::id::UNLOAD_CHUNK => {
                let p: cb::UnloadChunk = raw.decode_as()?;
                if !self.pistons.is_empty() {
                    self.pistons.chunk_replaced(p.chunk_x, p.chunk_z);
                }
                w.apply_unload_chunk(&p);
            }
            cb::id::BLOCK_CHANGE => {
                let p: cb::BlockChange = raw.decode_as()?;
                self.updates.push(p.location, p.r#type as u32);
                w.apply_block_change(&p);
                self.prune_pistons();
            }
            cb::id::BLOCK_ACTION => return self.block_action(raw),
            cb::id::MULTI_BLOCK_CHANGE => {
                let p: cb::MultiBlockChange = raw.decode_as()?;
                for r in &p.records {
                    let x = p.chunk_x * 16 + i32::from(r.horizontal_pos >> 4);
                    let z = p.chunk_z * 16 + i32::from(r.horizontal_pos & 15);
                    self.updates
                        .push(BlockPos::new(x, i32::from(r.y), z), r.block_id as u32);
                }
                w.apply_multi_block_change(&p);
                self.prune_pistons();
            }
            cb::id::EXPLOSION => {
                w.apply_explosion(&raw.decode_as()?);
                self.prune_pistons();
            }
            cb::id::WORLD_BORDER => {
                w.apply_world_border(&raw.decode_as()?);
            }
            cb::id::TILE_ENTITY_DATA if self.block_entities => {
                w.apply_tile_entity_data(&raw.decode_as()?);
            }
            _ => {}
        }
        Ok(())
    }

    fn reset_player(&mut self) {
        let abilities = self.player.abilities;
        let food = self.player.food_level;
        self.player = fresh_player_1_12();
        self.piston_uncertain_at = None;
        self.pistons.reset_player();
        self.player.abilities = abilities;
        self.player.food_level = food;
        // A new client player: not gliding, no rockets, not riding.
        self.leave_boat();
        self.ext.fall_flying = false;
        self.glide.rockets.clear();
        self.glide.pending.clear();
        self.update_glide();
        self.server_flags = None;
        self.absorption_dirty |= self.absorption != 0.0;
        self.absorption = 0.0;
    }

    fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
        // The engine keeps the look (its rotation may have moved it since the last tick).
        self.player.yaw = pose.yaw;
        self.player.pitch = pose.pitch;
        let _reply =
            self.player
                .apply_teleport([t.x, t.y, t.z], t.yaw, t.pitch, rel_flags(t.flags));
        if let Some(r) = &mut self.rec {
            let p = &self.player;
            r.teleport(
                [t.x, t.y, t.z],
                t.yaw,
                t.pitch,
                t.flags,
                t.teleport_id,
                p.pos,
                p.yaw,
                p.pitch,
            );
        }
        sync_pose_12(pose, &self.player);
    }

    fn abilities(&mut self, a: Abilities) {
        let a = physics_abilities(a);
        if let Some(r) = &mut self.rec {
            r.abilities(&a);
        }
        self.player.apply_abilities(a);
    }

    fn food(&mut self, food: i32) {
        self.player.food_level = food;
    }

    fn velocity(&mut self, v: Vec3, add: bool) {
        if let Some(r) = &mut self.rec {
            if add {
                r.note("explosion push not representable");
            } else {
                r.velocity([
                    (v.x * 8000.0).round() as i32,
                    (v.y * 8000.0).round() as i32,
                    (v.z * 8000.0).round() as i32,
                ]);
            }
        }
        let p = &mut self.player;
        if add {
            p.vel[0] += v.x;
            p.vel[1] += v.y;
            p.vel[2] += v.z;
        } else {
            p.vel = [v.x, v.y, v.z];
        }
    }

    fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
        if let Some(r) = &mut self.rec {
            r.speed_attribute(base, modifiers);
        }
        self.player.apply_speed_attribute(base, modifiers);
    }

    fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>) {
        if let Some(r) = &mut self.rec {
            r.effects(effects);
        }
        let e = &mut self.player.effects;
        e.jump_boost = effects.get(&8).map(|a| i32::from(*a));
        e.blindness = effects.contains_key(&15);
        e.levitation = effects.get(&25).map(|a| i32::from(*a));
    }

    fn boots(&mut self, depth_strider: u8, _soul_speed: u8) {
        // Soul speed does not exist in 1.12.
        self.player.depth_strider = depth_strider;
    }

    fn spectator(&mut self, on: bool) {
        self.player.spectator = on;
    }

    fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>) {
        let a = &mut self.player.abilities;
        if a.flying == flying || (flying && !a.allow_flying) {
            return;
        }
        a.flying = flying;
        let a = *a;
        out.push(Outbound::Abilities {
            flags: abilities_flags(&a),
            flying_speed: a.fly_speed,
            walking_speed: a.walk_speed,
        });
    }

    fn collect_block_updates(&mut self, on: bool) {
        self.updates.on = on;
        if !on {
            self.updates.list.clear();
        }
    }

    fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize {
        out.append(&mut self.updates.list);
        std::mem::take(&mut self.updates.dropped)
    }

    fn world_packet_ids(&self) -> Vec<i32> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let mut ids: Vec<i32> = self.world.packet_ids().collect();
        // Riding: boarding and the server's boat corrections. Our entity data: the shared
        // flags (sprinting, fall flying).
        ids.extend([
            cb::id::SET_PASSENGERS,
            cb::id::VEHICLE_MOVE,
            cb::id::ENTITY_METADATA,
            // Pistons: the client moves the blocks itself.
            cb::id::BLOCK_ACTION,
        ]);
        if self.glide.watch {
            // Gliding: the rockets the server attaches to us.
            ids.extend([cb::id::SPAWN_ENTITY, cb::id::ENTITY_DESTROY]);
        }
        ids
    }

    fn take_filter_dirty(&mut self) -> bool {
        std::mem::take(&mut self.glide.filter_dirty)
    }

    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_own_id(&mut self, id: i32) {
        self.glide.own_id = id;
    }

    fn eye_height(&self) -> Option<f64> {
        // PlayerEntity.getEyeHeight: sneaking (or 1.65 high) 1.62 - 0.08, gliding (or 0.6
        // high) 0.4.
        let p = &self.player;
        let f: f32 = if p.sneaking() || p.height == 1.65 {
            1.62 - 0.08
        } else if self.ext.fall_flying || p.height == 0.6 {
            0.4
        } else {
            1.62
        };
        Some(f64::from(f))
    }

    fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
        use ghast_entity::EntityType as T;
        // 1.12.2 `damage` on the client: `OtherClientPlayerEntity` always, boats and minecarts
        // (`world.isClient` → true), the end crystal, the ghast fireball (an attacker given),
        // the shulker bullet. LivingEntity is false on the client; paintings / item frames
        // are skipped by `handleAttack`; small / dragon fireballs and wither skulls are never
        // damaged.
        match e.entity_type() {
            T::Player => true,
            T::LegacyObject(t) => matches!(t, 1 | 10 | 51 | 63 | 67),
            _ => false,
        }
    }

    fn attack_slow(&mut self, _target: i32, _yaw: f32, knockback: i32, sprint_bonus: bool) {
        let p = &mut self.player;
        if super::attack_knockback_applies(knockback, p.sprinting, sprint_bonus) {
            p.vel[0] *= 0.6;
            p.vel[2] *= 0.6;
            p.set_sprinting(false);
            if let Some(r) = &mut self.rec {
                r.note("attack slow-down not representable");
            }
        }
    }

    fn server_flags(&self) -> Option<u8> {
        self.server_flags
    }

    #[inline]
    fn take_absorption(&mut self) -> Option<f32> {
        std::mem::take(&mut self.absorption_dirty).then_some(self.absorption)
    }

    #[inline]
    fn take_living_flags(&mut self) -> Option<u8> {
        self.living_flags.take()
    }

    fn velocity_now(&self) -> Vec3 {
        let v = self.player.vel;
        Vec3::new(v[0], v[1], v[2])
    }

    fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
        // HorseScreenHandler: the saddle slot asks canBeSaddled (every mount but llamas), the
        // armor slot isArmor (horse armor for horses, carpets for llamas): the type decides.
        use ghast_inventory::{MountArmor, MountRules};
        let e = self.entities.as_ref()?.get(entity_id)?;
        Some(match ghast_entity::v1_12::info(e.entity_type())?.name {
            "horse" => MountRules::new(true, MountArmor::HorseArmor),
            "donkey" | "mule" | "zombie_horse" | "skeleton_horse" => {
                MountRules::new(true, MountArmor::None)
            }
            "llama" => MountRules::new(false, MountArmor::Carpet),
            _ => return None,
        })
    }

    fn take_reply(&mut self) -> Option<Outbound> {
        self.reply.take()
    }

    fn vehicle(&self) -> Option<crate::common::Vehicle> {
        let r = self.ride.as_deref()?;
        let b = match &r.seat {
            Seat12::Boat(b) => b,
            Seat12::Cart(c) => {
                return Some(crate::common::Vehicle {
                    entity_id: r.id,
                    pos: Vec3::new(c.pos[0], c.pos[1], c.pos[2]),
                    yaw: c.yaw,
                    pitch: c.pitch,
                    on_ground: false,
                    controlled: false,
                });
            }
        };
        Some(crate::common::Vehicle {
            entity_id: r.id,
            pos: Vec3::new(b.pos[0], b.pos[1], b.pos[2]),
            yaw: b.yaw,
            pitch: b.pitch,
            on_ground: b.on_ground,
            controlled: true,
        })
    }

    #[inline(always)]
    fn modern_inputs(&self) -> bool {
        // The elytra is read on jump presses in the air (the request needs that).
        !self.player.on_ground
    }

    fn pre_tick(&mut self, inv: &ghast_inventory::Inventory, t: &crate::sim::PreTick) -> bool {
        if t.controls.jump {
            // ElytraItem.isUsable: damage below 431 (elytra, item 443).
            self.ext.elytra = inv.armor(1).is_some_and(|s| {
                s.id() == 443 && s.damage_value(ghast_inventory::Version::V1_12) < 432 - 1
            });
            if self.ext.elytra && !self.glide.watch {
                self.glide.watch = true;
                self.glide.filter_dirty = true;
            }
            self.update_glide();
        }
        true
    }

    fn gliding(&self) -> bool {
        self.ext.fall_flying
    }

    fn entity_config(&self) -> Option<ghast_entity::Config> {
        self.entities.as_ref().map(|t| t.config())
    }

    fn set_entities(&mut self, config: Option<ghast_entity::Config>) {
        if self.entity_config() == config {
            return;
        }
        self.entities = config.map(|c| {
            let mut t = ghast_entity::v1_12::Tracker::new(c);
            self.session.replay(|r| {
                if let Err(e) = t.apply(r) {
                    log::debug!("entity tracker: session packet 0x{:02x}: {e}", r.id);
                }
            });
            t
        });
        // The tracker starts empty (entities spawned before are known once the server resends
        // them), and teams sent before are not known (all pushes allowed).
        self.near = self.entities.is_some().then(Box::default);
    }

    fn entity_packet_ids(&self) -> Vec<i32> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        self.entities
            .as_ref()
            .map(|t| t.packet_ids().chain([cb::id::TEAMS]).collect())
            .unwrap_or_default()
    }

    fn tick_entities(&mut self, pose: &mut Pose) {
        if self.near.is_some() {
            self.tick_near(pose);
        }
        if self.glide_on && !self.glide.rockets.is_empty() {
            self.tick_rockets(pose);
        }
        // The other entities' interpolation steps (what the next tick's pick sees).
        if let Some(t) = &mut self.entities {
            t.tick_client();
        }
        // The block entities tick last; then ClientWorld.tick advances the world time.
        if !self.pistons.is_empty() {
            self.tick_piston_phase(pose);
        }
        self.piston_time = self.piston_time.wrapping_add(1);
    }

    fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
        self.entities.as_mut().map(|t| t.store_mut())
    }

    fn set_entity_push(&mut self, on: bool) {
        self.entity_push = on;
    }

    fn predict_air(&mut self, x: i32, y: i32, z: i32) {
        self.world
            .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
    }

    fn place_rules(
        &self,
        q: &crate::sim::predict::PlaceQuery<'_>,
    ) -> crate::sim::predict::PlaceRules {
        crate::sim::place112::rules(&self.world, &self.player.bb, q)
    }

    fn air_use(&self, q: &crate::sim::predict::AirQuery<'_>) -> crate::sim::predict::AirAnswer {
        let p = &self.player;
        crate::sim::use112::air_use(
            &crate::sim::use112::Ctx {
                world: &self.world,
                bb: p.bb,
                climbing: ghast_physics::v1_12::is_climbing(p, &self.world),
                fall_flying: self.ext.fall_flying,
                nether: self.dimension() == Some(-1),
                entities: self.entities.as_deref(),
                own_id: self.own_id(),
                maps: &self.maps,
            },
            q,
        )
    }

    fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
        for &(p, raw) in blocks {
            let s = ghast_data::v1_12::BlockState::from_raw_vanilla(raw as u16);
            log::debug!("item use set {} at {p:?}", s.block().name());
            self.world.set_block_state(p.x, p.y, p.z, s);
        }
    }

    fn place_sent(&mut self, p: &crate::sim::predict::PlaceSent<'_>) -> bool {
        // 1.12.2: the oracle-proven rules (`ghast_data::v1_12::place`), for the hand that
        // placed; what they do not decide is the server's block update
        let player = self.player.bb;
        let used = crate::sim::place112::sent(&mut self.world, &player, p);
        log::debug!("place at {:?}: item used {used}", p.pos);
        used
    }

    fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
        use ghast_data::v1_12::{Block, BlockState};
        // Anvils and slab items (stone, wooden, red sandstone, purpur): not decided.
        const UNDECIDED: &[u16] = &[44, 126, 145, 182, 205];
        let w = &self.world;
        let unit = ghast_data::Aabb {
            min_x: 0.0,
            min_y: 0.0,
            min_z: 0.0,
            max_x: 1.0,
            max_y: 1.0,
            max_z: 1.0,
        };
        crate::sim::predict::legacy_place_suppressed(
            pos,
            face,
            held,
            UNDECIDED,
            |q| w.block_state(q.x, q.y, q.z).map(BlockState::raw),
            |id| {
                u8::try_from(id)
                    .ok()
                    .and_then(Block::from_id)
                    .is_some_and(|b| b.material().replaceable)
            },
            |id| {
                let Some(b) = u8::try_from(id).ok().and_then(Block::from_id) else {
                    return false;
                };
                b.shape_dependency() == ghast_data::ShapeDependency::None
                    && (0..16u8).all(|m| {
                        let s = BlockState::new(b, m);
                        !s.is_registered() || s.shape() == [unit]
                    })
            },
            &self.player.bb,
            // World.hasEntityIn (spectators left out by getEntitiesIn): the entities whose
            // client position the sim keeps (with entity tracking). Not decided: the others
            // (minecarts, armor stands, bats, parrots, TNT, falling blocks, riders).
            |cube| match (self.near.as_deref(), self.entities.as_ref()) {
                (Some(n), Some(t)) => n.blocks_building(t, &self.world, cube),
                _ => false,
            },
        )
    }

    #[cfg(test)]
    fn set_player_pos(&mut self, p: Vec3) {
        self.player.set_position(p.x, p.y, p.z);
    }

    fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
        held_item_facts(DataSet::V1_12, id, count, efficiency)
    }

    fn step(
        &mut self,
        pose: &mut Pose,
        controls: Controls,
        using_item: bool,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    ) {
        self.packets.clear();
        if let Some(r) = &mut self.rec {
            // From the first tick the player really ticks: until its column is there it is not
            // added to the world (no move, no packet), which the replay's setup cannot express.
            if !r.started() && self.player.added_to_chunk {
                r.start_1_12(&self.player);
            }
            let w = &self.world;
            r.observe(self.player.pos, |x, y, z| {
                w.is_column_loaded(x >> 4, z >> 4)
                    .then(|| w.block_state(x, y, z).map_or(0, |s| u32::from(s.raw())))
            });
            if self.ride.is_some() {
                r.note_once("riding not representable");
            } else if self.glide_on {
                r.note_once("gliding not representable");
            } else if self.near.as_deref().is_some_and(|n| !n.idle()) {
                r.note_once("entity pushes and collisions not representable");
            }
        }
        let riding = self.ride.is_some();
        if !riding && !self.pistons.is_empty() {
            self.step_pistons(pose, controls, using_item);
        } else if riding {
            if matches!(
                self.ride.as_deref(),
                Some(Ride12 {
                    seat: Seat12::Cart(_),
                    ..
                })
            ) {
                self.step_cart(pose, controls);
            } else {
                self.step_ride(pose, controls);
            }
        } else if self.glide_on {
            self.step_ext(pose, controls, using_item);
        } else if self.near.as_deref().is_some_and(|n| !n.idle()) {
            self.step_near(pose, controls, using_item);
        } else {
            let input = ghast_physics::TickInput {
                keys: keys(controls),
                yaw: pose.yaw,
                pitch: pose.pitch,
                using_item,
            };
            ghast_physics::v1_12::tick(&mut self.player, &input, &self.world, &mut self.packets);
        }
        if self.force_step_position != ForceStepPosition::Off && !riding {
            let p = &mut self.player;
            let cur = [p.pos[0], p.bb.min_y, p.pos[2]];
            force_position(
                &mut self.packets,
                cur,
                &mut p.sent.pos,
                &mut p.sent.ticks_since_pos,
                self.force_step_position,
            );
        }
        if let Some(r) = &mut self.rec {
            let input = ghast_physics::TickInput {
                keys: keys(controls),
                yaw: pose.yaw,
                pitch: pose.pitch,
                using_item,
            };
            r.tick(
                &input,
                &crate::record::state_1_12(&self.player),
                &self.packets,
            );
        }
        push_packets(&self.packets, entity_id, out);
        sync_pose_12(pose, &self.player);
        // A moving world border advances with the client's clock.
        self.world.advance_time(50);
    }
}

fn sync_pose_12(pose: &mut Pose, p: &ghast_physics::v1_12::PlayerState) {
    pose.pos = Vec3::new(p.pos[0], p.bb.min_y, p.pos[2]);
    pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
    pose.yaw = p.yaw;
    pose.pitch = p.pitch;
    pose.on_ground = p.on_ground;
    pose.flying = p.abilities.flying;
    pose.sneaking = p.sneaking();
    pose.sprinting = p.sprinting;
}

// ---- 1.12.2: entities pushing the player, entities it collides with --------------------------

/// What a tracked entity does to the 1.12 player on the client.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Class12 {
    /// A living entity: `tickCramming` pushes the player; interpolates over 3 ticks.
    Living,
    /// Another player: pushes like a living entity unless it is a spectator.
    Player,
    /// A boat: pushes from its tick, solid for the player; interpolates over 10 ticks.
    Boat,
    /// A shulker: pushes like a living entity, solid while alive; never interpolates (the
    /// client snaps it to its attached block).
    Shulker,
    /// A minecart (every kind): only blocks a boat the player rides; interpolates over 5 ticks.
    Cart,
    /// A parrot: only blocks a boat the player rides; interpolates over 3 ticks.
    Parrot,
}

impl Class12 {
    /// Only matters for a boat the player rides (not pushing, not solid for the player).
    fn boat_only(self) -> bool {
        matches!(self, Class12::Cart | Class12::Parrot)
    }
}

/// The 1.12 class of a tracked entity, `None` when it neither pushes nor collides nor blocks a
/// boat: bats, armor stands, the ender dragon, items, projectiles, …
fn class_12(e: &ghast_entity::Entity) -> Option<Class12> {
    use ghast_entity::EntityType as T;
    match e.entity_type() {
        T::Player => Some(Class12::Player),
        // Spawn-object type 1.
        T::LegacyObject(1) => Some(Class12::Boat),
        T::LegacyObject(10) => Some(Class12::Cart),
        t @ T::LegacyMob(_) => match ghast_entity::v1_12::info(t)?.name {
            "shulker" => Some(Class12::Shulker),
            "parrot" => Some(Class12::Parrot),
            "bat" | "armor_stand" | "ender_dragon" => None,
            _ => Some(Class12::Living),
        },
        _ => None,
    }
}

/// How far from the player boats break lily pads in the client's world here (vanilla: every
/// ticking boat; the server breaks them as well and sends the change).
const LILY_PAD_REACH: f64 = 16.0;

/// The client side of one entity that pushes the player or is solid for it.
#[derive(Clone, Debug)]
struct Client12 {
    id: i32,
    /// Order in the client's entity list (spawn order).
    seq: u64,
    class: Class12,
    /// Client position (`x`, `y`, `z` after the interpolation steps so far; a shulker's is
    /// the server's, see [`Client12::placed`]).
    pos: [f64; 3],
    /// Interpolation target and remaining steps (`serverX`… / `bodyTrackingIncrements`, the
    /// boat's own fields).
    target: [f64; 3],
    steps: u8,
    /// Size (from the tracker at spawn and after each metadata packet).
    dims: ghast_data::EntityDimensions,
    /// Position and box as the client has them now (from `pos`).
    at: [f64; 3],
    bb: ghast_physics::math::Aabb,
    /// A player's profile name from its tab-list entry at spawn (`OtherClientPlayerEntity`
    /// keeps that profile: its scoreboard name for the team rules).
    name: Option<Box<str>>,
    /// A boat: the box and world version of its last lily pad scan (a boat that has not moved
    /// in an unchanged world breaks nothing new).
    scanned: Option<(ghast_physics::math::Aabb, u32)>,
    /// `onGround` of the client copy: the last move packet's, or where a piston's push left it.
    on_ground: bool,
    /// `isInWeb`, the piston budget of the current world tick (the client's own moves).
    in_web: bool,
    carry: ghast_physics::v1_12::PistonCarry,
    /// The chunk entity list it is filed in (chunk x, section y, chunk z) and its place there
    /// (`World.getEntitiesIn` order).
    section: [i32; 3],
    list_seq: u64,
    /// A piston moved it since its last tick (a shulker sits back on its block at its tick,
    /// after its own pushes).
    pushed: bool,
    /// A shulker with an attached block (entity data 13): its tick puts it back there.
    attached: bool,
}

/// A shulker's attached block (1.12 entity data 13, an optional block position) is set.
fn shulker_attached(e: &ghast_entity::Entity) -> bool {
    matches!(
        e.metadata().get(13),
        Some(ghast_entity::MetaValue::OptBlockPos(Some(_)))
    )
}

impl Client12 {
    /// Recomputes [`Client12::at`] / [`Client12::bb`] from the position.
    fn placed(&mut self) {
        if self.class == Class12::Shulker {
            // ShulkerEntity.tick snaps it to its attached block (the server keeps that block
            // under the position it sends): the unit cube there.
            let [x, y, z] = self.pos;
            let (x, y, z) = (x.floor() + 0.5, y.floor(), z.floor() + 0.5);
            self.at = [x, y, z];
            self.bb =
                ghast_physics::math::Aabb::new(x - 0.5, y, z - 0.5, x + 0.5, y + 1.0, z + 0.5);
        } else {
            self.at = self.pos;
            self.bb = self
                .dims
                .bounding_box(self.pos[0], self.pos[1], self.pos[2]);
        }
    }

    /// The boat the client moves: its position and box as the move left them (the box is
    /// not the one its position would give).
    fn follow(&mut self, pos: [f64; 3], bb: ghast_physics::math::Aabb) {
        self.pos = pos;
        self.at = pos;
        self.bb = bb;
    }

    /// `updateTrackedPositionAndAngles` with the client's step count: 10 for boats, 3 else.
    /// A shulker ignores it; the client snaps it to its attached block, which the server keeps
    /// under the position it sends (so it follows that position here).
    fn interpolate_to(&mut self, target: [f64; 3]) {
        match self.class {
            Class12::Shulker => {
                self.pos = target;
                self.target = target;
                self.placed();
            }
            Class12::Boat => {
                self.target = target;
                self.steps = 10;
            }
            Class12::Living | Class12::Player | Class12::Parrot => {
                self.target = target;
                self.steps = 3;
            }
            // AbstractMinecartEntity.updateTrackedPositionAndAngles: the packet's 3 steps + 2.
            Class12::Cart => {
                self.target = target;
                self.steps = 5;
            }
        }
    }

    /// One interpolation step of the entity's client tick.
    #[inline]
    fn step(&mut self) {
        let pushed = std::mem::take(&mut self.pushed);
        if (pushed && self.class == Class12::Shulker && self.attached)
            || (self.class == Class12::Cart && self.steps == 0)
        {
            // ShulkerEntity.tick: back on its attached block; a minecart's client tick sets
            // its position (the box follows it) when it does not interpolate.
            self.placed();
        }
        if self.steps > 0 {
            let n = f64::from(self.steps);
            for k in 0..3 {
                self.pos[k] += (self.target[k] - self.pos[k]) / n;
            }
            self.steps -= 1;
            self.placed();
        }
    }
}

/// `true` when box `b` is farther than `r` from the box `p`.
#[inline]
fn far(b: &ghast_physics::math::Aabb, p: &ghast_physics::math::Aabb, r: [f64; 3]) -> bool {
    b.max_x < p.min_x - r[0]
        || b.min_x > p.max_x + r[0]
        || b.max_y < p.min_y - r[1]
        || b.min_y > p.max_y + r[1]
        || b.max_z < p.min_z - r[2]
        || b.min_z > p.max_z + r[2]
}

/// 1.12 entities around the player as the client moves them: positions after the client's
/// interpolation (the tracker keeps the server's), pushes after the player's tick
/// (`World.tickEntities`: entities spawned after the player tick after it) and the boxes it
/// collides with (`World.doesBoxCollide`). Riding (the bot or the other entity) is not
/// modelled: such entities neither push nor collide here.
#[derive(Debug, Default)]
pub(crate) struct Near12 {
    /// Every tracked entity that pushes or collides (dense; `index` finds one by id).
    list: Vec<Client12>,
    index: std::collections::HashMap<i32, u32>,
    seq: u64,
    /// Boats in `list`.
    boats: usize,
    /// Entries in `list` that only matter for a ridden boat ([`Class12::boat_only`]).
    boat_only: usize,
    /// Boats and minecarts destroyed since the player's last tick: vanilla's world keeps them in
    /// their chunk's entity list until its entity loop reaches them, after the player moved.
    ghosts: Vec<Ghost12>,
    /// The boat the player rides and the client moves ([`Sim12`]'s): its entry follows the
    /// client's boat, the server's moves of it are ignored (`onEntityPosition` /
    /// `onEntityUpdate` skip an entity the client controls) and it is left out of the boxes.
    pub(super) ridden: Option<i32>,
    /// Scratch: the boxes the ridden boat collides with.
    boat_solids: Vec<ghast_physics::math::Aabb>,
    /// Scratch: this tick's solid boxes, pushers and broken lily pads.
    solids: Vec<ghast_physics::math::Aabb>,
    pushers: Vec<(u64, ghast_physics::v1_12::Pusher)>,
    lily_pads: Vec<[i32; 3]>,
    /// Bumped by every block packet (lily pads may have appeared).
    pub(super) world_version: u32,
    /// The teams' collision rules (`teams` packets).
    pub(super) teams: super::teams::Teams,
    /// Insertions into chunk entity lists so far (orders the lists).
    list_seq: u64,
    /// The local player's chunk entity list and place in it (`None` before its first tick
    /// in a loaded column).
    pub(super) me: Option<([i32; 3], u64)>,
}

/// Where an entity of the piston phase is kept: the near-entity model's list, or only the
/// tracker (by id).
#[derive(Clone, Copy, Debug)]
enum Kept {
    Near(usize),
    Extra(i32),
}

/// The chunk entity list of a position: chunk x, section y (0..16), chunk z.
fn section_of(p: [f64; 3]) -> [i32; 3] {
    let f = |v: f64| (v.floor() as i32) >> 4;
    [f(p[0]), f(p[1]).clamp(0, 15), f(p[2])]
}

/// A destroyed boat or minecart still in its chunk's entity list (see [`Near12::ghosts`]).
#[derive(Clone, Copy, Debug)]
struct Ghost12 {
    /// Its place in the entity list (it leaves the chunk when the loop reaches it).
    seq: u64,
    bb: ghast_physics::math::Aabb,
    /// A minecart (blocks a ridden boat only), else a boat.
    cart: bool,
}

/// The first VarInt of a body (the entity id of spawn and move packets).
fn first_varint(body: &[u8]) -> Option<i32> {
    let mut v: u32 = 0;
    for (k, &b) in body.iter().take(5).enumerate() {
        v |= u32::from(b & 0x7f) << (7 * k);
        if b & 0x80 == 0 {
            return Some(v as i32);
        }
    }
    None
}

impl Near12 {
    /// Nothing that pushes the walking player or is solid for it.
    fn idle(&self) -> bool {
        self.list.len() == self.boat_only && self.ghosts.iter().all(|g| g.cart)
    }

    fn get_mut(&mut self, id: i32) -> Option<&mut Client12> {
        let &k = self.index.get(&id)?;
        self.list.get_mut(k as usize)
    }

    /// Follows one entity packet the tracker has just applied.
    fn packet(&mut self, t: &ghast_entity::v1_12::Tracker, raw: &RawPacket) {
        use ghast_protocol::v1_12_2::play::clientbound::id;
        match raw.id {
            id::LOGIN | id::RESPAWN => {
                self.list.clear();
                self.index.clear();
                self.boats = 0;
                self.boat_only = 0;
                self.ghosts.clear();
                self.ridden = None;
                self.me = None;
                if raw.id == id::LOGIN {
                    // A new play phase: a new client scoreboard.
                    self.teams.clear();
                }
            }
            id::SPAWN_ENTITY | id::SPAWN_ENTITY_LIVING | id::NAMED_ENTITY_SPAWN => {
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                // ClientWorld.addEntity: an entity with the same id leaves the world first.
                self.remove(eid);
                if let Some(e) = t.get(eid)
                    && let Some(class) = class_12(e)
                    && let Some(dims) = e.dimensions()
                {
                    self.seq += 1;
                    self.boats += usize::from(class == Class12::Boat);
                    self.boat_only += usize::from(class.boat_only());
                    let pos = e.position();
                    let mut c = Client12 {
                        id: eid,
                        seq: self.seq,
                        class,
                        pos,
                        target: pos,
                        steps: 0,
                        dims,
                        at: pos,
                        bb: ghast_physics::math::Aabb::FULL,
                        name: t.player_name(eid).map(Into::into),
                        scanned: None,
                        on_ground: false,
                        in_web: false,
                        carry: Default::default(),
                        // `World.spawnEntity`: into its chunk's list at once.
                        section: section_of(pos),
                        list_seq: {
                            self.list_seq += 1;
                            self.list_seq
                        },
                        pushed: false,
                        attached: class == Class12::Shulker && shulker_attached(e),
                    };
                    c.placed();
                    self.index.insert(eid, self.list.len() as u32);
                    self.list.push(c);
                }
            }
            id::ENTITY_TELEPORT => {
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                if self.ridden == Some(eid) {
                    return;
                }
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid)) {
                    c.on_ground = e.on_ground();
                    let d = e.position();
                    // onEntityPosition: a teleport within 1/32 (1/64 vertically) of the client
                    // position keeps it and ends the interpolation.
                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
                    let tiny = !((c.pos[0] - d[0]).abs() >= 0.03125)
                        && !((c.pos[1] - d[1]).abs() >= 0.015625)
                        && !((c.pos[2] - d[2]).abs() >= 0.03125);
                    if tiny && c.class != Class12::Shulker {
                        c.target = c.pos;
                        c.steps = 0;
                    } else {
                        c.interpolate_to(d);
                    }
                }
            }
            id::REL_ENTITY_MOVE | id::ENTITY_MOVE_LOOK | id::ENTITY_LOOK | id::ENTITY => {
                // onEntityUpdate: towards the tracked position (1/4096 grid on every axis).
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                if self.ridden == Some(eid) {
                    return;
                }
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid)) {
                    c.on_ground = e.on_ground();
                    c.interpolate_to(e.position());
                }
            }
            id::ENTITY_METADATA => {
                // Size variants (babies, slime sizes) follow the metadata.
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid))
                    && c.class == Class12::Shulker
                {
                    c.attached = shulker_attached(e);
                }
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid))
                    && let Some(d) = e.dimensions()
                    && d != c.dims
                {
                    c.dims = d;
                    c.placed();
                }
            }
            id::ENTITY_DESTROY => {
                let mut r = ghast_protocol::Reader::new(&raw.body);
                let Ok(n) = r.read_varint() else { return };
                for _ in 0..n.max(0) {
                    let Ok(eid) = r.read_varint() else { return };
                    self.remove(eid);
                }
            }
            _ => {}
        }
    }

    fn remove(&mut self, eid: i32) {
        let Some(k) = self.index.remove(&eid) else {
            return;
        };
        let c = self.list.swap_remove(k as usize);
        if let Some(moved) = self.list.get(k as usize) {
            self.index.insert(moved.id, k);
        }
        if c.class == Class12::Boat {
            self.boats -= 1;
        }
        self.boat_only -= usize::from(c.class.boat_only());
        if matches!(c.class, Class12::Boat | Class12::Cart) {
            self.ghosts.push(Ghost12 {
                seq: c.seq,
                bb: c.bb,
                cart: c.class == Class12::Cart,
            });
        }
    }

    /// The entity takes part (its column is loaded, it rides nothing and carries nothing).
    fn present(
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        c: &Client12,
    ) -> bool {
        let Some(e) = t.get(c.id) else { return false };
        e.vehicle().is_none()
            && e.passengers().is_empty()
            && world.is_column_loaded((c.at[0].floor() as i32) >> 4, (c.at[2].floor() as i32) >> 4)
    }

    /// `World.hasEntityIn(box)` over these entities: one of them (not riding, not a spectator
    /// player) overlaps `cube` at its client position (`Box.intersects`).
    fn blocks_building(
        &self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        cube: &ghast_physics::math::Aabb,
    ) -> bool {
        self.list.iter().any(|c| {
            !c.class.boat_only()
                && crate::sim::predict::boxes_intersect(&c.bb, cube)
                && Self::present(t, world, c)
                && !(c.class == Class12::Player
                    && t.get(c.id)
                        .is_some_and(|e| t.tab_game_mode(&e.uuid()) == Some(3)))
        })
    }

    /// This tick's boxes the player collides with: boats and live shulkers within reach of any
    /// move of the tick, and the boats destroyed since the last tick. In the boat the client
    /// moves ([`Near12::ridden`], the passenger's tick at the boat's place in the entity list):
    /// the same without that boat, and only the destroyed boats after it in the list.
    fn solids(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        p: &ghast_physics::v1_12::PlayerState,
    ) {
        self.solids.clear();
        let own = self
            .ridden
            .and_then(|id| self.index.get(&id).map(|&k| (id, k)));
        let after = own.map_or(0, |(_, k)| self.list[k as usize].seq);
        let riding = own.is_none() && t.me().is_some_and(|m| m.vehicle().is_some());
        let reach = |v: f64| v.abs() + 3.0;
        let r = [reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2])];
        for c in &self.list {
            if !matches!(c.class, Class12::Boat | Class12::Shulker)
                || own.is_some_and(|(id, _)| id == c.id)
                || far(&c.bb, &p.bb, r)
                || riding
                || !Self::present(t, world, c)
            {
                continue;
            }
            // ShulkerEntity.getBox: only while alive.
            if c.class == Class12::Shulker
                && !t
                    .get(c.id)
                    .and_then(ghast_entity::v1_12::health)
                    .is_none_or(|h| h > 0.0)
            {
                continue;
            }
            self.solids.push(c.bb);
        }
        self.solids.extend(
            self.ghosts
                .iter()
                .filter(|g| !g.cart && g.seq > after)
                .map(|g| g.bb),
        );
    }

    /// The boxes the ridden boat collides with when it ticks (`World.doesBoxCollide` for the
    /// boat, `v1_12::blocks_boat`): the entities within reach of its move (`bb` grown by
    /// `reach`) whose column is loaded, at their client positions (the ones before the boat in
    /// the entity list have stepped this tick), and the destroyed boats and minecarts after it
    /// in the list. Left out: the boat itself, entities riding it with the player, spectator
    /// players, and entities that ride something (their seat is not followed here).
    fn boat_solids(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        bb: &ghast_physics::math::Aabb,
        reach: [f64; 3],
    ) {
        self.boat_solids.clear();
        let Some(own) = self.ridden else { return };
        let after = self
            .index
            .get(&own)
            .map_or(0, |&k| self.list[k as usize].seq);
        for c in &self.list {
            if c.id == own || far(&c.bb, bb, reach) {
                continue;
            }
            let Some(e) = t.get(c.id) else { continue };
            if e.vehicle().is_some()
                || !world
                    .is_column_loaded((c.at[0].floor() as i32) >> 4, (c.at[2].floor() as i32) >> 4)
            {
                continue;
            }
            let alive = || ghast_entity::v1_12::health(e).is_none_or(|h| h > 0.0);
            let blocks = match c.class {
                Class12::Boat => true,
                Class12::Cart => true,
                Class12::Parrot => true,
                Class12::Shulker => alive(),
                Class12::Player => {
                    t.tab_game_mode(&e.uuid()) != Some(3)
                        && alive()
                        && !ghast_physics::v1_12::entity_climbing(world, c.at, c.bb.min_y)
                }
                Class12::Living => {
                    let name = ghast_entity::v1_12::info(e.entity_type()).map_or("", |i| i.name);
                    ghast_physics::v1_12::blocks_boat(
                        name,
                        true,
                        alive(),
                        ghast_physics::v1_12::entity_climbing(world, c.at, c.bb.min_y),
                        !e.passengers().is_empty(),
                    )
                }
            };
            if blocks {
                self.boat_solids.push(c.bb);
            }
        }
        self.boat_solids.extend(
            self.ghosts
                .iter()
                .filter(|g| g.seq > after && !far(&g.bb, bb, reach))
                .map(|g| g.bb),
        );
    }

    /// The entities' client ticks after the player's: one interpolation step each, the lily
    /// pads the boats near the player break (`lily_pads_broken_by_boat`; farther ones are left
    /// to the server), and the entities whose tick pushes the player, in tick order, into
    /// `pushers` (when `pushing`).
    fn tick(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        p: &ghast_physics::math::Aabb,
        pushing: bool,
        profile_name: &str,
        seqs: std::ops::Range<u64>,
    ) {
        use ghast_physics::v1_12::{PushKind, Pusher};
        self.pushers.clear();
        self.lily_pads.clear();
        let version = self.world_version;
        let ridden = self.ridden;
        let mut list_seq = self.list_seq;
        for c in &mut self.list {
            // The boat the client moves ticks with the player (the sim's).
            if !seqs.contains(&c.seq) || ridden == Some(c.id) {
                continue;
            }
            // A shulker a piston moved pushes from there before it sits back.
            let pre = (c.pushed && c.class == Class12::Shulker).then_some((c.at, c.bb));
            c.step();
            // `updateEntityWithOptionalForce`: a new chunk entity list after its tick.
            let sec = section_of(c.at);
            if sec != c.section {
                list_seq += 1;
                c.section = sec;
                c.list_seq = list_seq;
            }
            if c.class == Class12::Boat
                && c.scanned != Some((c.bb, version))
                && !far(&c.bb, p, [LILY_PAD_REACH; 3])
                && Self::present(t, world, c)
            {
                ghast_physics::v1_12::lily_pads_broken_by_boat(world, &c.bb, &mut self.lily_pads);
                c.scanned = Some((c.bb, version));
            }
            // Boats reach 0.2 farther; nothing else can touch the player.
            if !pushing
                || c.class.boat_only()
                || far(&pre.map_or(c.bb, |x| x.1), p, [0.25; 3])
                || !Self::present(t, world, c)
            {
                continue;
            }
            let Some(e) = t.get(c.id) else { continue };
            // A spectator player has noClip (set in its tick) and pushes nothing.
            if c.class == Class12::Player && t.tab_game_mode(&e.uuid()) == Some(3) {
                continue;
            }
            // EntityPredicate.method_13025: the pusher's and the player's team rules.
            if self.teams.any_rule() {
                let mut buf = [0u8; 36];
                let name: &str = match &c.name {
                    Some(n) => n,
                    None => e.uuid().hyphenated().encode_lower(&mut buf),
                };
                if !self.teams.may_push(name, profile_name) {
                    continue;
                }
            }
            let kind = if c.class == Class12::Boat {
                PushKind::Boat
            } else {
                PushKind::Living
            };
            let (at, bb) = pre.unwrap_or((c.at, c.bb));
            self.pushers.push((c.seq, Pusher::new(at, bb, kind)));
        }
        self.list_seq = list_seq;
        self.pushers.sort_unstable_by_key(|x| x.0);
    }
}