ghast-physics 0.5.6

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), verified bit for bit against the real game
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
//! Pistons on the 1.16.5 client: the blocks a piston moves, their collision shapes while they
//! travel, and how they move the player.
//!
//! The client runs the piston itself on a block-event packet (the block at the position handles
//! it; types 0 extend, 1 retract, 2 the server's fast retract that pulls nothing): the 1.16 block
//! choice (slime and honey are sticky, but not to each other), the moved blocks become
//! moving-piston blocks with a [`MovingBlock`], ticked after the player. Every tick a block
//! advances by 0.5 and moves each entity its shape sweeps by the overlap (plus 0.01, at most the
//! step) with the piston move type (at most 0.51 per axis per world tick, no sneak edge guard); a
//! slime block also sets the velocity, a honey block moved sideways drags what stands on it, a
//! retracting head pulls back what it overlapped. A finished block stays a moving block for 5
//! more client ticks before it is placed. While it moves its collision shape is the moved shape
//! offset by the progress (re-simplified into boxes, like vanilla's shape union), and the entity a
//! piston pushes ignores blocks moving its way.
//!
//! The client runs the 1.13+ shape updates of its writes too (`piston_updates`): connecting
//! neighbours (fences, panes, walls, stairs, fence gates, snowy grass, chests, mushroom blocks,
//! attached stems, campfires, chorus plants, concrete powder) recompute their state, a
//! finished move places the moved block's post-processed state; kinds of blocks the model does
//! not cover are reported by [`Pistons::take_unmodelled`].
//!
//! [`Pistons`] holds the moving blocks in vanilla's ticking order; world changes are returned as
//! [`Edits`] (apply them in order). [`tick_with_pistons`] replaces the player tick while any
//! block moves.

use ghast_data::v1_16_5::{Block, BlockState, Property};

use super::blocks::ShapeCtx;
use super::blocks::{Shape, collision_shape};
use super::collide::{BorderShape, Collider, WithMoving};
use super::fluid::V3;
use super::piston_shapes::SOURCE_SHAPES;
use super::piston_updates::{UpdateView, face_covers, neighbor_update, side};
use super::player::{PlayerState, PlayerStepCtx, piston_move, tick_with_moving};
use super::{PlayerExt, Surroundings};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::voxel::{Points, VoxelShape};
use crate::world::{BlockView, WorldBorder};

/// A direction id: 0 down, 1 up, 2 north, 3 south, 4 west, 5 east.
pub type Facing = u8;

const PUSH_LIMIT: usize = 12;
/// Client ticks a finished block keeps moving before it is placed.
const CLIENT_HOLD: u8 = 5;
/// `World.setBlockState`'s default maximum update depth.
const MAX_DEPTH: u32 = 512;

/// Block offset of a direction id.
#[inline]
#[must_use]
pub const fn offset(f: Facing) -> [i32; 3] {
    match f {
        0 => [0, -1, 0],
        1 => [0, 1, 0],
        2 => [0, 0, -1],
        3 => [0, 0, 1],
        4 => [-1, 0, 0],
        _ => [1, 0, 0],
    }
}

#[inline]
const fn opposite(f: Facing) -> Facing {
    f ^ 1
}

#[inline]
const fn axis(f: Facing) -> u8 {
    f >> 1
}

#[inline]
const fn axis_index(f: Facing) -> usize {
    [1, 2, 0][(f >> 1) as usize]
}

#[inline]
fn step(p: [i32; 3], f: Facing, n: i32) -> [i32; 3] {
    let o = offset(f);
    [p[0] + o[0] * n, p[1] + o[1] * n, p[2] + o[2] * n]
}

const FACING_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];

/// `true` for a block whose state follows its neighbours through shape updates
/// (`getStateForNeighborUpdate` changing a property: fences, panes, iron bars, walls, stairs,
/// fence gates in walls, snowy grass, chests, vines, redstone wire, rails, ...), or turns into
/// air without support (carpets, snow layers).
#[deprecated(
    since = "0.4.9",
    note = "the client's shape updates are modelled; see `Pistons::take_unmodelled`"
)]
#[must_use]
pub fn follows_neighbours(b: Block) -> bool {
    const SHAPED: [&str; 10] = [
        "north", "east", "south", "west", "up", "down", "shape", "in_wall", "snowy", "type",
    ];
    // Blocks that turn into air without support (`canPlaceAt` in their neighbour update).
    let name = b.name();
    name.ends_with("_carpet")
        || name == "snow"
        || name.ends_with("rail")
        || b.properties().any(|d| {
            let n = d.property.name();
            SHAPED.contains(&n) && (n != "type" || d.values.contains(&"left"))
        })
}

/// `true` when applying `edits` on top of `world` would make the client run shape updates
/// this model does not: a placed block that follows its neighbours, or a write next to one
/// (vanilla `setBlockState` flag 3 updates the neighbours' shapes on the client too, and a
/// finished move places `Block.postProcessState` of the pushed state). The client's world may
/// then hold other states than this model's until the server's block updates arrive.
///
/// Since 0.4.9 the edits a block event or tick returns include the client's shape updates; what
/// the model does not cover is reported by [`Pistons::take_unmodelled`].
#[deprecated(
    since = "0.4.9",
    note = "the edits include the client's shape updates; use `Pistons::take_unmodelled`"
)]
#[allow(deprecated)]
#[must_use]
pub fn edits_need_shape_updates<W: BlockView<State = BlockState>>(
    world: &W,
    edits: &[([i32; 3], BlockState)],
) -> bool {
    let v = Layered { w: world, edits };
    edits.iter().any(|&(p, s)| {
        follows_neighbours(s.block())
            || (0..6).any(|f| {
                let q = step(p, f, 1);
                follows_neighbours(v.block(q[0], q[1], q[2]).block())
            })
    })
}

fn prop(name: &str) -> Property {
    Property::from_name(name).expect("1.16.5 property")
}

fn facing_of(s: BlockState) -> Option<Facing> {
    let v = s.get(prop("facing"))?;
    FACING_NAMES
        .iter()
        .position(|n| *n == v)
        .map(|i| i as Facing)
}

fn with(s: BlockState, p: &str, v: &str) -> BlockState {
    s.with(prop(p), v).expect("1.16.5 state property")
}

fn is_piston(b: Block) -> bool {
    b == Block::PISTON || b == Block::STICKY_PISTON
}

fn is_sticky_block(b: Block) -> bool {
    b == Block::SLIME_BLOCK || b == Block::HONEY_BLOCK
}

fn stuck(a: Block, b: Block) -> bool {
    if (a == Block::HONEY_BLOCK && b == Block::SLIME_BLOCK)
        || (a == Block::SLIME_BLOCK && b == Block::HONEY_BLOCK)
    {
        return false;
    }
    is_sticky_block(a) || is_sticky_block(b)
}

/// The piston behaviour of a block (oracle `piston_facts.jsonl.gz`, the same for all states).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Behaviour {
    Normal,
    Destroy,
    Block,
    PushOnly,
}

fn behaviour(id: u16) -> Behaviour {
    match id {
        19..=24
        | 26..=27
        | 59..=64
        | 75..=90
        | 94..=99
        | 119..=133
        | 141..=144
        | 148
        | 152
        | 161..=162
        | 171..=179
        | 181..=184
        | 187
        | 189
        | 192
        | 198..=199
        | 202..=205
        | 244..=249
        | 254
        | 258
        | 265
        | 267
        | 271..=272
        | 281..=325
        | 330..=332
        | 410..=415
        | 485..=489
        | 491..=492
        | 497
        | 507
        | 509..=525
        | 574..=575
        | 577
        | 593..=597
        | 603..=607
        | 613..=618
        | 621..=623
        | 626
        | 666
        | 677..=679
        | 682
        | 688
        | 690..=691
        | 697
        | 699..=703
        | 708..=709
        | 718..=721
        | 738..=741
        | 757..=758 => Behaviour::Destroy,
        93 | 100..=101 | 118 | 201 | 262 | 326..=328 | 378 | 499 | 673 | 742 => Behaviour::Block,
        526..=541 => Behaviour::PushOnly,
        _ => Behaviour::Normal,
    }
}

fn unbreakable(id: u16) -> bool {
    matches!(
        id,
        25 | 118 | 201 | 262..=263 | 277 | 378 | 499..=501 | 726..=727
    )
}

fn has_block_entity(id: u16) -> bool {
    matches!(
        id,
        70 | 75..=90
            | 118
            | 145
            | 147
            | 154..=160
            | 165..=170
            | 190
            | 259..=260
            | 262
            | 270
            | 277..=278
            | 314..=325
            | 329
            | 332..=333
            | 336
            | 342
            | 416..=447
            | 499..=501
            | 509..=525
            | 620
            | 668..=670
            | 674
            | 677
            | 680..=681
            | 722..=727
            | 730..=731
    )
}

/// One moving block (vanilla's piston block entity at a moving-piston block).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MovingBlock {
    /// Where the block entity is (the moving block's destination).
    pub pos: [i32; 3],
    /// The block that is moving; it is placed at `pos` when the move ends.
    pub pushed: BlockState,
    /// The piston's facing.
    pub facing: Facing,
    /// Moving away from the piston.
    pub extending: bool,
    /// The piston's own part: the head going out, or the base of a retracting piston.
    pub source: bool,
    /// Progress `0..=1` after the last tick.
    pub progress: f32,
    /// Progress before the last tick.
    pub last_progress: f32,
    /// Client ticks the finished block has waited (it is placed after 5).
    pub hold: u8,
    removed: bool,
}

impl MovingBlock {
    fn moves(&self) -> Facing {
        if self.extending {
            self.facing
        } else {
            opposite(self.facing)
        }
    }

    fn shift(&self, p: f32) -> f32 {
        if self.extending { p - 1.0 } else { 1.0 - p }
    }

    /// `getHeadBlockState`: what pushes (a retracting base pushes with its head).
    fn head_state(&self) -> BlockState {
        if !self.extending && self.source && is_piston(self.pushed.block()) {
            let f = facing_of(self.pushed).unwrap_or(self.facing);
            let mut h = with(
                Block::PISTON_HEAD.default_state(),
                "facing",
                FACING_NAMES[f as usize],
            );
            h = with(
                h,
                "short",
                if self.progress > 0.25 {
                    "true"
                } else {
                    "false"
                },
            );
            if self.pushed.block() == Block::STICKY_PISTON {
                h = with(h, "type", "sticky");
            }
            h
        } else {
            self.pushed
        }
    }
}

/// World changes in the order the client makes them: `(position, new state)`.
pub type Edits = Vec<([i32; 3], BlockState)>;

/// The moving blocks of a client world, in vanilla's ticking order, and the player's piston
/// move budget of the current world tick.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Pistons {
    blocks: Vec<MovingBlock>,
    delta: [f64; 3],
    delta_time: i64,
    unmodelled: bool,
}

impl Pistons {
    /// No moving blocks.
    #[must_use]
    pub const fn new() -> Pistons {
        Pistons {
            blocks: Vec::new(),
            delta: [0.0; 3],
            delta_time: 0,
            unmodelled: false,
        }
    }

    /// `true` when nothing moves (the plain tick applies).
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.blocks.is_empty()
    }

    /// `true` (once: the call clears it) when a block event or moving-block tick since the last
    /// call made the client run a shape update this model does not cover (a neighbour that is
    /// redstone wire, a vine, fire, bamboo, ...; see the module docs): the client's
    /// world may then hold other states than this model's until the server's block updates
    /// arrive.
    pub fn take_unmodelled(&mut self) -> bool {
        std::mem::take(&mut self.unmodelled)
    }

    /// The live moving blocks in ticking order.
    pub fn iter(&self) -> impl Iterator<Item = &MovingBlock> {
        self.blocks.iter().filter(|b| !b.removed)
    }

    /// `true` when a live moving block's cell, grown by one block, meets `bb`: a piston may
    /// move or push what is in `bb` this tick.
    #[must_use]
    pub fn touches(&self, bb: &Aabb) -> bool {
        self.iter().any(|m| {
            bb.intersects(&Aabb::new(
                f64::from(m.pos[0]) - 1.0,
                f64::from(m.pos[1]) - 1.0,
                f64::from(m.pos[2]) - 1.0,
                f64::from(m.pos[0]) + 2.0,
                f64::from(m.pos[1]) + 2.0,
                f64::from(m.pos[2]) + 2.0,
            ))
        })
    }

    /// Always `false` since 0.4.9. It flagged moving stairs / trapdoors next to the player,
    /// whose pushes differed from vanilla in rare cases: moved multi-box blocks now collide with
    /// vanilla's re-simplified union grid, which closed those cases.
    #[deprecated(
        since = "0.4.9",
        note = "moving multi-box blocks are modelled; always false"
    )]
    #[must_use]
    pub fn untracked_near(&self, _bb: &Aabb) -> bool {
        false
    }

    /// The live moving block at a position.
    #[must_use]
    pub fn at(&self, pos: [i32; 3]) -> Option<&MovingBlock> {
        self.blocks.iter().find(|b| !b.removed && b.pos == pos)
    }

    fn index_at(&self, pos: [i32; 3]) -> Option<usize> {
        self.blocks.iter().position(|b| !b.removed && b.pos == pos)
    }

    /// Forgets every moving block (world unload, dimension change).
    pub fn clear(&mut self) {
        self.blocks.clear();
    }

    /// A new client player entity: its piston move budget starts over.
    pub fn reset_player(&mut self) {
        self.delta = [0.0; 3];
        self.delta_time = 0;
    }

    /// Keeps only the moving blocks for which `keep` is `true`.
    pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
        self.blocks.retain(|b| !b.removed && keep(b));
    }

    /// A block at `pos` changed from `old` to `new` in the client world: a moving-piston block
    /// replaced by another block drops its moving block.
    pub fn block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
        if old.block() == Block::MOVING_PISTON
            && new.block() != Block::MOVING_PISTON
            && let Some(i) = self.index_at(pos)
        {
            self.blocks.remove(i);
        }
    }

    /// The moving blocks inside chunk column `(cx, cz)` are gone.
    pub fn chunk_replaced(&mut self, cx: i32, cz: i32) {
        self.blocks
            .retain(|b| !(b.pos[0] >> 4 == cx && b.pos[2] >> 4 == cz));
    }

    fn add(&mut self, mut b: MovingBlock) {
        if let Some(i) = self.index_at(b.pos) {
            self.blocks[i].removed = true;
        }
        b.removed = false;
        self.blocks.push(b);
    }

    fn drop_removed(&mut self) {
        self.blocks.retain(|b| !b.removed);
    }

    /// The block-event packet of a piston (`action` 0 extend, 1 retract, 2 retract without
    /// pulling; `data` the facing; the block at `pos` handles it, the packet's block is not
    /// read): runs the client's piston against `world` and appends the world changes to `edits`
    /// (apply them in order). `false`: ignored (no piston at `pos`).
    pub fn block_event<W: BlockView<State = BlockState>>(
        &mut self,
        world: &W,
        pos: [i32; 3],
        action: u8,
        data: u8,
        edits: &mut Edits,
    ) -> bool {
        let start = edits.len();
        let mut ov = Overlay {
            w: world,
            edits,
            start,
            pistons: self,
        };
        let r = ov.on_event(pos, action, data);
        self.drop_removed();
        r
    }

    /// The block-entity half of a client tick without the player (it rides: not pushed here).
    pub fn tick_blocks<W: BlockView<State = BlockState>>(
        &mut self,
        world: &W,
        time: i64,
        edits: &mut Edits,
    ) {
        if !self.is_empty() {
            let mut cx = Actors {
                p: None,
                others: &mut [],
                player_rank: 0,
                player_section: None,
            };
            tick_moving(&mut cx, world, time, self, edits);
        }
    }
}

/// The collision shapes of the moving blocks for one query context (`pushing`: the direction a
/// piston moves the asking entity in right now).
#[derive(Default)]
pub(crate) struct MovingShapes {
    shapes: Vec<([i32; 3], Placed)>,
    unions: Vec<UnionShape>,
}

/// A moving block's shape: built here, a static block shape, or a dumped piston part.
#[derive(Clone, Copy)]
enum Placed {
    Owned(OwnedShape),
    Static(VoxelShape<'static>, bool),
    /// A multi-box shape: index into [`MovingShapes::unions`].
    Union(usize),
}

/// The shape `VoxelShapes.union(empty, shape.offset(..))` gives a moved block with more than
/// one box: the union simplifies, so the shifted shape's boxes are combined one by one into a
/// new grid. Every box adds its own boundaries (a box that fits a power-of-two grid adds that
/// whole grid, as `VoxelShapes.cuboid` makes it a simple shape); the merged grid can have
/// boundaries inside a box, which stop an entity that already overlaps the shape.
#[derive(Clone, Debug, Default, PartialEq)]
struct UnionShape {
    pts: [Vec<f64>; 3],
    cells: Vec<u64>,
}

impl UnionShape {
    /// The union of `boxes` (block-local); `None` when all are empty.
    fn of(boxes: impl Iterator<Item = Aabb> + Clone) -> Option<UnionShape> {
        const EPS: f64 = 1.0e-7;
        let lo = |b: &Aabb, a: usize| [b.min_x, b.min_y, b.min_z][a];
        let hi = |b: &Aabb, a: usize| [b.max_x, b.max_y, b.max_z][a];
        // `findRequiredBitResolution`.
        let res = |l: f64, h: f64| -> Option<u32> {
            if l < -EPS || h > 1.000_000_1 {
                return None;
            }
            (0..=3).find(|&i| {
                let k = f64::from(1u32 << i);
                let (d, e) = (l * k, h * k);
                (d - d.floor()).abs() < EPS && (e - e.floor()).abs() < EPS
            })
        };
        let mut pts: [Vec<f64>; 3] = Default::default();
        let mut used: Vec<Aabb> = Vec::new();
        for b in boxes {
            let r = [
                res(b.min_x, b.max_x),
                res(b.min_y, b.max_y),
                res(b.min_z, b.max_z),
            ];
            match r {
                [Some(0), Some(0), Some(0)] => {
                    // The full cube, or the empty shape (adds nothing to an OR).
                    let inside = (0..3).all(|a| 0.5 >= lo(&b, a) && 0.5 < hi(&b, a));
                    if !inside {
                        continue;
                    }
                    for p in &mut pts {
                        p.extend([0.0, 1.0]);
                    }
                }
                [Some(i), Some(j), Some(k)] => {
                    for (a, n) in [i, j, k].into_iter().enumerate() {
                        let n = 1u32 << n;
                        pts[a].extend((0..=n).map(|q| f64::from(q) / f64::from(n)));
                    }
                }
                _ => {
                    for (a, p) in pts.iter_mut().enumerate() {
                        p.extend([lo(&b, a), hi(&b, a)]);
                    }
                }
            }
            used.push(b);
        }
        if used.is_empty() {
            return None;
        }
        // The merge of ascending boundary lists (`SimplePairList`: a value within 1e-7 of the
        // last kept one collapses into it).
        for p in &mut pts {
            p.sort_by(f64::total_cmp);
            let mut kept: Vec<f64> = Vec::with_capacity(p.len());
            for &v in p.iter() {
                if kept.last().is_none_or(|&l| l < v - EPS) {
                    kept.push(v);
                }
            }
            *p = kept;
        }
        let index = |a: usize, v: f64, p: &[Vec<f64>; 3]| {
            p[a].iter().rposition(|&q| q <= v + EPS).unwrap_or(0)
        };
        let n = [pts[0].len() - 1, pts[1].len() - 1, pts[2].len() - 1];
        let mut cells = vec![0u64; (n[0] * n[1] * n[2]).div_ceil(64)];
        for b in &used {
            let r: [(usize, usize); 3] =
                std::array::from_fn(|a| (index(a, lo(b, a), &pts), index(a, hi(b, a), &pts)));
            for x in r[0].0..r[0].1 {
                for y in r[1].0..r[1].1 {
                    for z in r[2].0..r[2].1 {
                        let i = (x * n[1] + y) * n[2] + z;
                        cells[i / 64] |= 1 << (i % 64);
                    }
                }
            }
        }
        Some(UnionShape { pts, cells })
    }

    fn view(&self) -> VoxelShape<'_> {
        VoxelShape {
            axes: [
                Points::Explicit(&self.pts[0]),
                Points::Explicit(&self.pts[1]),
                Points::Explicit(&self.pts[2]),
            ],
            cells: &self.cells,
        }
    }
}

/// A single-box shape as `VoxelShapes.cuboid` builds it.
#[derive(Clone, Copy)]
struct OwnedShape {
    /// Simple (power-of-two grid) or explicit two-point axes.
    simple: Option<[u32; 3]>,
    pts: [[f64; 2]; 3],
    cells: [u64; 8],
    /// Vanilla's shared full cube (collision takes the box fast path).
    full: bool,
}

impl OwnedShape {
    fn view(&self) -> VoxelShape<'_> {
        let axes = match self.simple {
            Some(n) => [
                Points::Fractional(n[0]),
                Points::Fractional(n[1]),
                Points::Fractional(n[2]),
            ],
            None => [
                Points::Explicit(&self.pts[0]),
                Points::Explicit(&self.pts[1]),
                Points::Explicit(&self.pts[2]),
            ],
        };
        VoxelShape {
            axes,
            cells: &self.cells,
        }
    }

    /// `VoxelShapes.cuboid(box)`.
    fn cuboid(b: &Aabb) -> Option<OwnedShape> {
        let (x0, y0, z0, x1, y1, z1) = (b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z);
        let res = |lo: f64, hi: f64| -> Option<u32> {
            if lo < -1.0e-7 || hi > 1.000_000_1 {
                return None;
            }
            (0..=3).find(|&i| {
                let k = f64::from(1u32 << i);
                let (d, e) = (lo * k, hi * k);
                (d - d.floor()).abs() < 1.0e-7 && (e - e.floor()).abs() < 1.0e-7
            })
        };
        let mut s = OwnedShape {
            simple: None,
            pts: [[x0, x1], [y0, y1], [z0, z1]],
            cells: [0; 8],
            full: false,
        };
        match (res(x0, x1), res(y0, y1), res(z0, z1)) {
            (Some(0), Some(0), Some(0)) => {
                // `box.contains(0.5, 0.5, 0.5)` ? full cube : empty.
                let inside =
                    0.5 >= x0 && 0.5 < x1 && 0.5 >= y0 && 0.5 < y1 && 0.5 >= z0 && 0.5 < z1;
                if !inside {
                    return None;
                }
                s.simple = Some([1, 1, 1]);
                s.cells[0] = 1;
                s.full = true;
            }
            (Some(i), Some(j), Some(k)) => {
                let (l, m, n) = (1u32 << i, 1u32 << j, 1u32 << k);
                let r = |v: f64, k: u32| (v * f64::from(k)).round() as i64;
                let (o, p) = (r(x0, l), r(x1, l));
                let (q, rr) = (r(y0, m), r(y1, m));
                let (t, u) = (r(z0, n), r(z1, n));
                s.simple = Some([l, m, n]);
                for x in o..p {
                    for y in q..rr {
                        for z in t..u {
                            let idx = ((x as u32 * m + y as u32) * n + z as u32) as usize;
                            s.cells[idx / 64] |= 1 << (idx % 64);
                        }
                    }
                }
            }
            _ => s.cells[0] = 1,
        }
        Some(s)
    }
}

impl MovingShapes {
    /// The shapes of every live moving block as an entity pushed towards `pushing` sees them.
    pub(crate) fn of(pistons: &Pistons, pushing: Option<Facing>) -> MovingShapes {
        let mut out = MovingShapes::default();
        for m in pistons.iter() {
            out.add_block(m, pushing);
        }
        out
    }

    fn add_block(&mut self, m: &MovingBlock, pushing: Option<Facing>) {
        // `PistonBlockEntity.getCollisionShape`: the retracting base's extended shape, then (unless
        // it is the entity's pusher) the moved shape offset by the progress; the union is
        // re-simplified, which gives the grid boundaries of all parts.
        let excluded = m.progress < 1.0 && pushing == Some(m.moves());
        if excluded {
            if !m.extending
                && m.source
                && let Shape::Grid { shape, full_cube } = collision_shape(
                    with(m.pushed, "extended", "true"),
                    m.pos[0],
                    m.pos[1],
                    m.pos[2],
                    None,
                )
            {
                self.shapes.push((m.pos, Placed::Static(shape, full_cube)));
            }
            return;
        }
        if m.source {
            // The piston's own parts: the vanilla union shapes (oracle dump).
            let k = if m.extending {
                0
            } else if m.pushed.block() == Block::STICKY_PISTON {
                2
            } else {
                1
            };
            let pi = if m.progress == 0.0 {
                Some(0)
            } else if m.progress == 0.5 {
                Some(1)
            } else if m.progress == 1.0 {
                Some(2)
            } else {
                None
            };
            if let Some(pi) = pi {
                let t = &SOURCE_SHAPES[m.facing as usize][k][pi];
                let axes = if t.simple {
                    [
                        Points::Fractional(t.sizes[0] as u32),
                        Points::Fractional(t.sizes[1] as u32),
                        Points::Fractional(t.sizes[2] as u32),
                    ]
                } else {
                    [
                        Points::Explicit(t.xs),
                        Points::Explicit(t.ys),
                        Points::Explicit(t.zs),
                    ]
                };
                let full = t.simple && t.sizes == [1, 1, 1];
                let shape = VoxelShape {
                    axes,
                    cells: t.cells,
                };
                self.shapes.push((m.pos, Placed::Static(shape, full)));
                return;
            }
        }
        let state = if m.source {
            let mut h = with(
                Block::PISTON_HEAD.default_state(),
                "facing",
                FACING_NAMES[m.facing as usize],
            );
            let short = m.extending != (1.0 - m.progress < 0.25);
            h = with(h, "short", if short { "true" } else { "false" });
            h
        } else {
            m.pushed
        };
        let f = m.shift(m.progress);
        let o = offset(m.facing);
        let (d, e, g) = (
            f64::from(o[0] as f32 * f),
            f64::from(o[1] as f32 * f),
            f64::from(o[2] as f32 * f),
        );
        let boxes = state.collision().boxes;
        let shift = |b: &Aabb| {
            Aabb::new(
                b.min_x + d,
                b.min_y + e,
                b.min_z + g,
                b.max_x + d,
                b.max_y + e,
                b.max_z + g,
            )
        };
        if let [b] = boxes {
            if let Some(s) = OwnedShape::cuboid(&shift(b)) {
                self.shapes.push((m.pos, Placed::Owned(s)));
            }
        } else if let Some(u) = UnionShape::of(boxes.iter().map(shift)) {
            self.unions.push(u);
            self.shapes
                .push((m.pos, Placed::Union(self.unions.len() - 1)));
        }
    }

    /// The shapes at a block position: `(shape, full cube)`.
    pub(crate) fn at(&self, pos: [i32; 3]) -> impl Iterator<Item = (VoxelShape<'_>, bool)> {
        self.shapes
            .iter()
            .filter(move |(p, _)| *p == pos)
            .map(|(_, s)| match s {
                Placed::Owned(o) => (o.view(), o.full),
                Placed::Static(v, full) => (*v, *full),
                Placed::Union(i) => (self.unions[*i].view(), false),
            })
    }
}

/// A world view with changes not yet applied on top (later changes win).
struct Layered<'a, W> {
    w: &'a W,
    edits: &'a [([i32; 3], BlockState)],
}

impl<W: BlockView<State = BlockState>> BlockView for Layered<'_, W> {
    type State = BlockState;

    #[inline]
    fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
        for (p, s) in self.edits.iter().rev() {
            if *p == [x, y, z] {
                return *s;
            }
        }
        self.w.block(x, y, z)
    }

    #[inline]
    fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
        self.w.is_chunk_loaded(cx, cz)
    }

    #[inline]
    fn world_border(&self) -> WorldBorder {
        self.w.world_border()
    }
}

/// The world with the changes made since `start` on top, recording changes and keeping the
/// moving blocks in step with the client world's rules.
struct Overlay<'a, W> {
    w: &'a W,
    edits: &'a mut Edits,
    start: usize,
    pistons: &'a mut Pistons,
}

#[inline]
fn valid(p: [i32; 3]) -> bool {
    (0..256).contains(&p[1])
}

impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
    fn get(&self, p: [i32; 3]) -> BlockState {
        if !valid(p) {
            return BlockState::AIR;
        }
        let v = Layered {
            w: self.w,
            edits: &self.edits[self.start..],
        };
        v.block(p[0], p[1], p[2])
    }

    /// The client world's `setBlockState(p, s, flags)` (maximum update depth `depth`): without
    /// flag 16 the neighbours' shape updates follow (`updateNeighbors`; `neighborUpdate`, flag
    /// 1, runs only on the server).
    fn set(&mut self, p: [i32; 3], s: BlockState, flags: u32, depth: u32) {
        if !valid(p) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
            return;
        }
        let old = self.get(p);
        if old == s {
            return;
        }
        if old.block() == Block::MOVING_PISTON
            && s.block() != Block::MOVING_PISTON
            && let Some(i) = self.pistons.index_at(p)
        {
            self.pistons.blocks[i].removed = true;
        }
        self.edits.push((p, s));
        if flags & 16 == 0 && depth > 0 {
            // `prepare` (old and new state) acts only for redstone wire.
            if old.block() == Block::REDSTONE_WIRE || s.block() == Block::REDSTONE_WIRE {
                self.pistons.unmodelled = true;
            }
            self.update_neighbors(p, s, flags & !33, depth - 1);
        }
    }

    /// `BlockState.updateNeighbors`: every neighbour of `p` recomputes its state for `s`
    /// (`Block.replace`: an air result is dropped on the client).
    fn update_neighbors(&mut self, p: [i32; 3], s: BlockState, flags: u32, depth: u32) {
        for d in 0..6 {
            let q = step(p, d, 1);
            let n = self.get(q);
            let new = match neighbor_update(self, n, opposite(d), s, q, p) {
                Ok(v) => v,
                Err(v) => {
                    self.pistons.unmodelled = true;
                    v
                }
            };
            if new != n && !new.is_air() {
                self.set(q, new, flags & !32, depth);
            }
        }
    }

    /// `Block.postProcessState`: `s` recomputed against its six neighbours at `p`.
    fn post_process(&mut self, s: BlockState, p: [i32; 3]) -> BlockState {
        let mut out = s;
        for d in 0..6 {
            let q = step(p, d, 1);
            let n = self.get(q);
            out = match neighbor_update(self, out, d, n, p, q) {
                Ok(v) => v,
                Err(v) => {
                    self.pistons.unmodelled = true;
                    v
                }
            };
        }
        out
    }

    /// `World.removeBlock(p, false)`: the fluid's block (air here) with flags 3.
    fn remove(&mut self, p: [i32; 3]) {
        let s = self.get(p);
        if s.fluid().is_some() {
            // A waterlogged block leaves water: not modelled.
            self.pistons.unmodelled = true;
        }
        self.set(p, BlockState::AIR, 3, MAX_DEPTH);
    }

    /// The collision shape of the moving block at `p` (none without a live block entity: an
    /// empty shape), as `f` sees it.
    fn with_moving_shape<T>(&self, p: [i32; 3], f: impl FnOnce(Option<&VoxelShape<'_>>) -> T) -> T {
        let Some(m) = self.pistons.at(p) else {
            return f(None);
        };
        let mut shapes = MovingShapes::default();
        shapes.add_block(m, None);
        let first = shapes.at(p).next().map(|v| v.0);
        f(first.as_ref())
    }

    fn add_moving(
        &mut self,
        pos: [i32; 3],
        pushed: BlockState,
        facing: Facing,
        extending: bool,
        source: bool,
    ) {
        if !valid(pos) || !self.w.is_chunk_loaded(pos[0] >> 4, pos[2] >> 4) {
            return;
        }
        self.pistons.add(MovingBlock {
            pos,
            pushed,
            facing,
            extending,
            source,
            progress: 0.0,
            last_progress: 0.0,
            hold: 0,
            removed: false,
        });
    }

    /// `PistonBlockEntity.finish` on the client (always runs there): a source leaves air, a
    /// moved block its `postProcessState` (air too when it lost its support).
    fn finish(&mut self, i: usize) {
        let b = self.pistons.blocks[i];
        let m = &mut self.pistons.blocks[i];
        m.progress = 1.0;
        m.last_progress = 1.0;
        m.removed = true;
        if self.get(b.pos).block() == Block::MOVING_PISTON {
            let s = if b.source {
                BlockState::AIR
            } else {
                self.post_process(b.pushed, b.pos)
            };
            self.set(b.pos, s, 3, MAX_DEPTH);
        }
    }

    fn moving_state(facing: Facing, sticky: bool) -> BlockState {
        let s = with(
            Block::MOVING_PISTON.default_state(),
            "facing",
            FACING_NAMES[facing as usize],
        );
        if sticky { with(s, "type", "sticky") } else { s }
    }

    fn on_event(&mut self, pos: [i32; 3], action: u8, data: u8) -> bool {
        let state = self.get(pos);
        if !is_piston(state.block()) {
            return false;
        }
        let Some(facing) = facing_of(state) else {
            return false;
        };
        let sticky = state.block() == Block::STICKY_PISTON;
        match action {
            0 => {
                if !self.move_blocks(pos, facing, true, sticky) {
                    return true;
                }
                self.set(pos, with(state, "extended", "true"), 67, MAX_DEPTH);
            }
            1 | 2 => {
                if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
                    self.finish(i);
                }
                let moving = Self::moving_state(facing, sticky);
                self.set(pos, moving, 20, MAX_DEPTH);
                let base = with(
                    state.block().default_state(),
                    "facing",
                    FACING_NAMES[(data & 7) as usize % 6],
                );
                self.add_moving(pos, base, facing, false, true);
                self.update_neighbors(pos, moving, 2, MAX_DEPTH);
                if sticky {
                    let p2 = step(pos, facing, 2);
                    let b = self.get(p2);
                    let mut finished = false;
                    if b.block() == Block::MOVING_PISTON
                        && let Some(i) = self.pistons.index_at(p2)
                        && self.pistons.blocks[i].facing == facing
                        && self.pistons.blocks[i].extending
                    {
                        self.finish(i);
                        finished = true;
                    }
                    if !finished {
                        let id = b.block().id();
                        if action != 1
                            || b.is_air()
                            || !self.movable(b, p2, opposite(facing), false, facing)
                            || (behaviour(id) != Behaviour::Normal && !is_piston(b.block()))
                        {
                            self.remove(step(pos, facing, 1));
                        } else {
                            self.move_blocks(pos, facing, false, sticky);
                        }
                    }
                } else {
                    self.remove(step(pos, facing, 1));
                }
            }
            _ => {}
        }
        true
    }

    /// `PistonBlock.isMovable`.
    fn movable(
        &self,
        b: BlockState,
        p: [i32; 3],
        dir: Facing,
        can_break: bool,
        piston: Facing,
    ) -> bool {
        if !valid(p) || !self.w.world_border().contains_block(p[0], p[2]) {
            return false;
        }
        if b.is_air() {
            return true;
        }
        let blk = b.block();
        if blk == Block::OBSIDIAN || blk == Block::CRYING_OBSIDIAN || blk == Block::RESPAWN_ANCHOR {
            return false;
        }
        if (dir == 0 && p[1] == 0) || (dir == 1 && p[1] == 255) {
            return false;
        }
        if is_piston(blk) {
            if b.get(prop("extended")) == Some("true") {
                return false;
            }
        } else {
            let id = blk.id();
            if unbreakable(id) {
                return false;
            }
            match behaviour(id) {
                Behaviour::Block => return false,
                Behaviour::Destroy => return can_break,
                Behaviour::PushOnly => return dir == piston,
                Behaviour::Normal => {}
            }
        }
        !has_block_entity(blk.id())
    }

    /// `PistonBlock.move`.
    fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
        let head_pos = step(pos, facing, 1);
        if !extend && self.get(head_pos).block() == Block::PISTON_HEAD {
            self.set(head_pos, BlockState::AIR, 20, MAX_DEPTH);
        }
        let mut h = Handler::new(pos, facing, extend);
        if !h.calculate(self) {
            return false;
        }
        let states: Vec<BlockState> = h.moved.iter().map(|&m| self.get(m)).collect();
        // The vacated cells (the moved blocks' old positions not refilled) with their states.
        let mut vacated: Vec<([i32; 3], BlockState)> = h
            .moved
            .iter()
            .copied()
            .zip(states.iter().copied())
            .collect();
        let push = if extend { facing } else { opposite(facing) };
        for &b in h.broken.iter().rev() {
            if self.get(b).block() == Block::REDSTONE_WIRE {
                // Its `prepare` after the move.
                self.pistons.unmodelled = true;
            }
            self.set(b, BlockState::AIR, 18, MAX_DEPTH);
        }
        for (k, &m) in h.moved.iter().enumerate().rev() {
            let dst = step(m, push, 1);
            vacated.retain(|v| v.0 != dst);
            self.set(dst, Self::moving_state(facing, false), 68, MAX_DEPTH);
            self.add_moving(dst, states[k], facing, extend, false);
        }
        if extend {
            vacated.retain(|v| v.0 != head_pos);
            self.set(head_pos, Self::moving_state(facing, sticky), 68, MAX_DEPTH);
            let mut head = with(
                Block::PISTON_HEAD.default_state(),
                "facing",
                FACING_NAMES[facing as usize],
            );
            if sticky {
                head = with(head, "type", "sticky");
            }
            self.add_moving(head_pos, head, facing, true, true);
        }
        // Vanilla keeps the vacated cells in a `HashMap<BlockPos, BlockState>` and walks it
        // in its iteration order: first all become air (no updates), then each one's
        // neighbours update.
        let order = hash_map_order(&h.moved, &vacated).unwrap_or_else(|| {
            self.pistons.unmodelled = true;
            (0..vacated.len()).collect()
        });
        for &k in &order {
            self.set(vacated[k].0, BlockState::AIR, 82, MAX_DEPTH);
        }
        for &k in &order {
            if vacated[k].1.block() == Block::REDSTONE_WIRE {
                self.pistons.unmodelled = true;
            }
            self.update_neighbors(vacated[k].0, BlockState::AIR, 2, MAX_DEPTH);
        }
        true
    }
}

impl<W: BlockView<State = BlockState>> UpdateView for Overlay<'_, W> {
    fn state(&self, p: [i32; 3]) -> BlockState {
        self.get(p)
    }

    fn side_solid(&self, p: [i32; 3], s: BlockState, face: Facing) -> Option<bool> {
        if s.block() == Block::MOVING_PISTON {
            // Dynamic bounds: the face of the block entity's current shape.
            return Some(self.with_moving_shape(p, |sh| {
                sh.is_some_and(|sh| face_covers(sh, face, [0.0, 0.0, 1.0, 1.0], true))
            }));
        }
        if s.has_dynamic_bounds() {
            return None;
        }
        Some(s.side_solid_full_square(side(face)))
    }

    fn down_face_covers(&self, p: [i32; 3], s: BlockState, rect: [f64; 4]) -> Option<bool> {
        if s.block() == Block::MOVING_PISTON {
            return Some(
                self.with_moving_shape(p, |sh| {
                    sh.is_some_and(|sh| face_covers(sh, 0, rect, false))
                }),
            );
        }
        if s.has_dynamic_bounds() {
            return None;
        }
        Some(match collision_shape(s, p[0], p[1], p[2], None) {
            Shape::Grid { shape, .. } => face_covers(&shape, 0, rect, false),
            Shape::Empty => false,
        })
    }
}

/// The order a `java.util.HashMap<BlockPos, _>` (16 buckets: at most 12 entries) walks the
/// `left` entries after `moved` were put in order: by bucket of the spread `BlockPos` hash,
/// then by insertion. Returns indices into `left`; `None` when a bucket would grow long enough
/// for the map to restructure itself.
fn hash_map_order(moved: &[[i32; 3]], left: &[([i32; 3], BlockState)]) -> Option<Vec<usize>> {
    let bucket = |p: [i32; 3]| {
        let h = (p[1].wrapping_add(p[2].wrapping_mul(31)))
            .wrapping_mul(31)
            .wrapping_add(p[0]);
        let spread = h ^ ((h as u32) >> 16) as i32;
        (spread & 15) as usize
    };
    let mut counts = [0usize; 16];
    for &p in moved {
        counts[bucket(p)] += 1;
    }
    if counts.iter().any(|&c| c >= 8) {
        return None;
    }
    let mut out = Vec::with_capacity(left.len());
    for b in 0..16 {
        for &p in moved {
            if bucket(p) == b
                && let Some(k) = left.iter().position(|v| v.0 == p)
            {
                out.push(k);
            }
        }
    }
    Some(out)
}

/// `PistonHandler`.
struct Handler {
    from: [i32; 3],
    to: [i32; 3],
    motion: Facing,
    piston: Facing,
    extend: bool,
    moved: Vec<[i32; 3]>,
    broken: Vec<[i32; 3]>,
}

impl Handler {
    fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
        let (motion, to) = if extend {
            (facing, step(pos, facing, 1))
        } else {
            (opposite(facing), step(pos, facing, 2))
        };
        Handler {
            from: pos,
            to,
            motion,
            piston: facing,
            extend,
            moved: Vec::new(),
            broken: Vec::new(),
        }
    }

    fn calculate<W: BlockView<State = BlockState>>(&mut self, ov: &Overlay<'_, W>) -> bool {
        self.moved.clear();
        self.broken.clear();
        let b = ov.get(self.to);
        if !ov.movable(b, self.to, self.motion, false, self.piston) {
            if self.extend && behaviour(b.block().id()) == Behaviour::Destroy {
                self.broken.push(self.to);
                return true;
            }
            return false;
        }
        if !self.try_move(ov, self.to, self.motion) {
            return false;
        }
        let mut i = 0;
        while i < self.moved.len() {
            let p = self.moved[i];
            if is_sticky_block(ov.get(p).block()) && !self.move_adjacent(ov, p) {
                return false;
            }
            i += 1;
        }
        true
    }

    fn try_move<W: BlockView<State = BlockState>>(
        &mut self,
        ov: &Overlay<'_, W>,
        pos: [i32; 3],
        dir: Facing,
    ) -> bool {
        let mut b = ov.get(pos);
        if b.is_air()
            || !ov.movable(b, pos, self.motion, false, dir)
            || pos == self.from
            || self.moved.contains(&pos)
        {
            return true;
        }
        let back = opposite(self.motion);
        let mut i = 1usize;
        if i + self.moved.len() > PUSH_LIMIT {
            return false;
        }
        while is_sticky_block(b.block()) {
            let bp = step(pos, back, i as i32);
            let prev = b.block();
            b = ov.get(bp);
            if b.is_air()
                || !stuck(prev, b.block())
                || !ov.movable(b, bp, self.motion, false, back)
                || bp == self.from
            {
                break;
            }
            i += 1;
            if i + self.moved.len() > PUSH_LIMIT {
                return false;
            }
        }
        let mut j = 0usize;
        for k in (0..i).rev() {
            self.moved.push(step(pos, back, k as i32));
            j += 1;
        }
        let mut l = 1;
        loop {
            let bp = step(pos, self.motion, l);
            if let Some(m) = self.moved.iter().position(|&p| p == bp) {
                self.reorder(j, m);
                for n in 0..=m + j {
                    let p = self.moved[n];
                    if is_sticky_block(ov.get(p).block()) && !self.move_adjacent(ov, p) {
                        return false;
                    }
                }
                return true;
            }
            let b = ov.get(bp);
            if b.is_air() {
                return true;
            }
            if !ov.movable(b, bp, self.motion, true, self.motion) || bp == self.from {
                return false;
            }
            if behaviour(b.block().id()) == Behaviour::Destroy {
                self.broken.push(bp);
                return true;
            }
            if self.moved.len() >= PUSH_LIMIT {
                return false;
            }
            self.moved.push(bp);
            j += 1;
            l += 1;
        }
    }

    fn reorder(&mut self, from: usize, to: usize) {
        let n = self.moved.len();
        let mut v = Vec::with_capacity(n);
        v.extend_from_slice(&self.moved[..to]);
        v.extend_from_slice(&self.moved[n - from..]);
        v.extend_from_slice(&self.moved[to..n - from]);
        self.moved = v;
    }

    fn move_adjacent<W: BlockView<State = BlockState>>(
        &mut self,
        ov: &Overlay<'_, W>,
        pos: [i32; 3],
    ) -> bool {
        let s = ov.get(pos).block();
        for d in 0..6 {
            if axis(d) != axis(self.motion) {
                let q = step(pos, d, 1);
                if stuck(ov.get(q).block(), s) && !self.try_move(ov, q, d) {
                    return false;
                }
            }
        }
        true
    }
}

/// The world seen through its own type, so the moving tick is compiled apart from the plain one.
pub(super) struct Distinct<'a, W>(pub(super) &'a W);

impl<W: BlockView<State = BlockState>> BlockView for Distinct<'_, W> {
    type State = BlockState;

    #[inline(always)]
    fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
        self.0.block(x, y, z)
    }

    #[inline(always)]
    fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
        self.0.is_chunk_loaded(cx, cz)
    }

    #[inline(always)]
    fn world_border(&self) -> WorldBorder {
        self.0.world_border()
    }
}

/// One client tick with moving blocks: the player's tick (as [`super::tick_ext`], the moving
/// blocks' shapes collide), then every moving block ticks in order and pushes the player; blocks
/// that finish are placed (appended to `edits`). `time` is the client world's time during this
/// tick (it limits the piston movement per world tick).
#[allow(clippy::too_many_arguments)]
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    x: &mut PlayerExt,
    around: &Surroundings<'_>,
    input: &TickInput,
    world: &W,
    pistons: &mut Pistons,
    time: i64,
    out: &mut Packets,
    edits: &mut Edits,
) {
    tick_player_among_pistons(p, x, around, input, world, pistons, out);
    pistons.tick_after_entities(p, x, around, world, time, edits);
}

/// The player's half of [`tick_with_pistons`]: its tick with the moving blocks' shapes.
/// Vanilla ticks every other entity after it and the moving blocks last: run those, then
/// [`Pistons::tick_after_entities`].
pub fn tick_player_among_pistons<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    x: &mut PlayerExt,
    around: &Surroundings<'_>,
    input: &TickInput,
    world: &W,
    pistons: &Pistons,
    out: &mut Packets,
) {
    let view = Distinct(world);
    let shapes = MovingShapes::of(pistons, None);
    tick_with_moving(p, x, around, input, &view, &shapes, out);
}

impl Pistons {
    /// The block-entity half of a client tick (`ClientWorld.tickEntities` ends with the block
    /// entities): every moving block advances and pushes the player, whose piston moves collide
    /// with `around`'s entity boxes as they are then (after the entities' ticks); finished
    /// blocks are placed (appended to `edits`). `time` is the client world's time.
    pub fn tick_after_entities<W: BlockView<State = BlockState>>(
        &mut self,
        p: &mut PlayerState,
        x: &mut PlayerExt,
        around: &Surroundings<'_>,
        world: &W,
        time: i64,
        edits: &mut Edits,
    ) {
        if !self.is_empty() {
            let mut cx = Actors {
                p: Some((p, x, around)),
                others: &mut [],
                player_rank: 0,
                player_section: None,
            };
            tick_moving(&mut cx, world, time, self, edits);
        }
    }

    /// [`Pistons::tick_after_entities`] with the other entities of the client world, which the
    /// moving blocks push too (vanilla moves them on the client: `Entity.move` with the piston
    /// move type, their own step height, collisions and per-world-tick budget). `others` is in
    /// `World.getOtherEntities` order (chunk entity sections); `player` is the player's place in
    /// it and its entity section. Their boxes, positions and states are updated in place. The
    /// player's piston moves collide with `around`'s entity boxes (entities not in `others`) and
    /// the collidable `others` as they are at that moment. Searches find an entity by the
    /// section it is filed in ([`PistonEntity::section`]).
    #[allow(clippy::too_many_arguments)]
    pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
        &mut self,
        p: &mut PlayerState,
        x: &mut PlayerExt,
        around: &Surroundings<'_>,
        others: &mut [PistonEntity],
        player: PlayerPlace,
        world: &W,
        time: i64,
        edits: &mut Edits,
    ) {
        if !self.is_empty() {
            let mut cx = Actors {
                p: Some((p, x, around)),
                others,
                player_rank: player.rank,
                player_section: Some(player.section),
            };
            tick_moving(&mut cx, world, time, self, edits);
        }
    }
}

/// Another entity of the client world as the moving blocks see it
/// ([`Pistons::tick_after_entities_among`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PistonEntity {
    /// Its box (updated by the pushes).
    pub bb: Aabb,
    /// Its position (`getPos`; the box's bottom centre after a move).
    pub pos: [f64; 3],
    /// `isOnGround` on the client (a honey block drags only what stands on it; a move sets it).
    pub on_ground: bool,
    /// `stepHeight`.
    pub step_height: f32,
    /// `getPistonBehavior` is not `IGNORE` and it is not a spectator: pistons move it.
    pub moved: bool,
    /// `isCollidable` (boats, live shulkers): every entity's moves stop at it.
    pub collidable: bool,
    /// `isPushable` (live, non-climbing living entities, boats, minecarts).
    pub pushable: bool,
    /// Its moves stop at pushable entities too (`BoatEntity.method_30959`: boats, minecarts).
    pub hits_pushable: bool,
    /// A living entity (sweet berry bushes slow it).
    pub living: bool,
    /// The chunk entity section it is filed in: chunk x, section y (0..16), chunk z (where its
    /// last tick left it; a search finds it there).
    pub section: [i32; 3],
    /// The state its moves carry from tick to tick.
    pub carry: PistonCarry,
}

/// The player's place among the others ([`Pistons::tick_after_entities_among`]): how many of
/// them come before it in `getOtherEntities` order, and its entity section (chunk x, section y,
/// chunk z).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlayerPlace {
    /// The number of others before the player.
    pub rank: usize,
    /// Its chunk entity section.
    pub section: [i32; 3],
}

/// `true` when a search over `q` (`World.getOtherEntities`: the chunks and sections of `q`
/// grown by 2) meets an entity filed in `section`.
#[must_use]
pub fn search_finds(section: [i32; 3], q: &Aabb) -> bool {
    let f = |v: f64| crate::math::floor(v / 16.0);
    let (x0, x1) = (f(q.min_x - 2.0), f(q.max_x + 2.0));
    let (z0, z1) = (f(q.min_z - 2.0), f(q.max_z + 2.0));
    let (y0, y1) = (f(q.min_y - 2.0).clamp(0, 15), f(q.max_y + 2.0).clamp(0, 15));
    (x0..=x1).contains(&section[0])
        && (y0..=y1).contains(&section[1])
        && (z0..=z1).contains(&section[2])
}

/// What an entity's piston moves carry over: the per-world-tick budget
/// (`pistonMovementDelta` / `pistonMovementTick`) and the `movementMultiplier` a cobweb or a
/// sweet berry bush left for its next move.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PistonCarry {
    delta: [f64; 3],
    delta_time: i64,
    multiplier: [f64; 3],
}

/// The entities a moving block can push: the player (absent while it rides) and the others.
struct Actors<'a, 'b, 'c> {
    p: Option<PlayerRef<'a, 'b>>,
    others: &'c mut [PistonEntity],
    player_rank: usize,
    /// The player's entity section (`None`: searches always find it).
    player_section: Option<[i32; 3]>,
}

/// One of [`Actors`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Actor {
    Player,
    Other(usize),
}

impl Actors<'_, '_, '_> {
    /// Every actor in `getOtherEntities` order.
    fn order(&self) -> impl Iterator<Item = Actor> + use<> {
        let n = self.others.len();
        let rank = if self.p.is_some() {
            Some(self.player_rank.min(n))
        } else {
            None
        };
        (0..=n).filter_map(move |k| match rank {
            Some(r) if k == r => Some(Actor::Player),
            Some(r) if k > r => Some(Actor::Other(k - 1)),
            _ if k < n => Some(Actor::Other(k)),
            _ => None,
        })
    }

    fn bb(&self, a: Actor) -> Aabb {
        match a {
            Actor::Player => self.p.as_ref().expect("player").0.bb,
            Actor::Other(k) => self.others[k].bb,
        }
    }

    /// A search over `q` meets the actor's entity section.
    fn found(&self, a: Actor, q: &Aabb) -> bool {
        match a {
            Actor::Player => self.player_section.is_none_or(|s| search_finds(s, q)),
            Actor::Other(k) => search_finds(self.others[k].section, q),
        }
    }
}

type PlayerRef<'a, 'b> = (&'a mut PlayerState, &'a mut PlayerExt, &'a Surroundings<'b>);

/// The block-entity half of the tick.
fn tick_moving<W: BlockView<State = BlockState>>(
    actors: &mut Actors<'_, '_, '_>,
    world: &W,
    time: i64,
    pistons: &mut Pistons,
    edits: &mut Edits,
) {
    let border = world.world_border();
    let start = edits.len();
    let mut i = 0;
    while i < pistons.blocks.len() {
        let b = pistons.blocks[i];
        i += 1;
        if b.removed || !valid(b.pos) || !border.contains_block(b.pos[0], b.pos[2]) {
            continue;
        }
        let m = &mut pistons.blocks[i - 1];
        m.last_progress = m.progress;
        if m.last_progress >= 1.0 {
            if m.hold < CLIENT_HOLD {
                m.hold += 1;
                continue;
            }
            m.removed = true;
            let m = *m;
            let mut ov = Overlay {
                w: world,
                edits,
                start,
                pistons,
            };
            if ov.get(m.pos).block() == Block::MOVING_PISTON {
                let s = ov.post_process(m.pushed, m.pos);
                if s.is_air() {
                    // Placed without updates; the break that follows is server-only.
                    ov.set(m.pos, m.pushed, 84, MAX_DEPTH);
                } else {
                    let s = s.with(prop("waterlogged"), "false").unwrap_or(s);
                    ov.set(m.pos, s, 67, MAX_DEPTH);
                }
            }
        } else {
            let f = m.progress + 0.5;
            let m = *m;
            if actors.p.is_some() {
                let view = Layered {
                    w: world,
                    edits: &edits[start..],
                };
                let view = Distinct(&view);
                let mut cx = PushCx {
                    a: actors,
                    world: &view,
                    time,
                    pistons,
                };
                cx.push(&m, f);
                cx.honey(&m, f);
            }
            let m = &mut pistons.blocks[i - 1];
            m.progress = f;
            if m.progress >= 1.0 {
                m.progress = 1.0;
            }
        }
    }
    pistons.drop_removed();
}

/// `Boxes.stretch(box, dir, d)`.
fn stretch(b: &Aabb, dir: Facing, d: f64) -> Aabb {
    let e = if dir & 1 == 1 { d } else { -d };
    let (f, g) = (e.min(0.0), e.max(0.0));
    match dir {
        4 => sorted_box(b.min_x + f, b.min_y, b.min_z, b.min_x + g, b.max_y, b.max_z),
        5 => sorted_box(b.max_x + f, b.min_y, b.min_z, b.max_x + g, b.max_y, b.max_z),
        0 => sorted_box(b.min_x, b.min_y + f, b.min_z, b.max_x, b.min_y + g, b.max_z),
        2 => sorted_box(b.min_x, b.min_y, b.min_z + f, b.max_x, b.max_y, b.min_z + g),
        3 => sorted_box(b.min_x, b.min_y, b.max_z + f, b.max_x, b.max_y, b.max_z + g),
        _ => sorted_box(b.min_x, b.max_y + f, b.min_z, b.max_x, b.max_y + g, b.max_z),
    }
}

/// `getIntersectionSize`: how far `b` reaches into `e` along `dir`.
fn reach(b: &Aabb, dir: Facing, e: &Aabb) -> f64 {
    match dir {
        5 => b.max_x - e.min_x,
        4 => e.max_x - b.min_x,
        0 => e.max_y - b.min_y,
        3 => b.max_z - e.min_z,
        2 => e.max_z - b.min_z,
        _ => b.max_y - e.min_y,
    }
}

fn union(a: &Aabb, b: &Aabb) -> Aabb {
    Aabb::new(
        a.min_x.min(b.min_x),
        a.min_y.min(b.min_y),
        a.min_z.min(b.min_z),
        a.max_x.max(b.max_x),
        a.max_y.max(b.max_y),
        a.max_z.max(b.max_z),
    )
}

/// `adjustMovementForPiston`: the move `d` within the budget of the current world tick (`None`:
/// nothing left).
fn piston_budget(
    delta: &mut [f64; 3],
    delta_time: &mut i64,
    time: i64,
    d: [f64; 3],
) -> Option<[f64; 3]> {
    if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= 1.0e-7 {
        // A tiny movement passes unchanged.
        return Some(d);
    }
    if time != *delta_time {
        *delta = [0.0; 3];
        *delta_time = time;
    }
    let k = [0, 1, 2].into_iter().find(|&k| d[k] != 0.0)?;
    let v = (d[k] + delta[k]).clamp(-0.51, 0.51);
    let mv = v - delta[k];
    delta[k] = v;
    if mv.abs() <= f64::from(1.0e-5f32) {
        return None;
    }
    let mut out = [0.0; 3];
    out[k] = mv;
    Some(out)
}

/// The entities while a moving block pushes them.
struct PushCx<'a, 'b, 'c, 'd, W> {
    a: &'a mut Actors<'b, 'c, 'd>,
    world: &'a W,
    time: i64,
    pistons: &'a mut Pistons,
}

impl<W: BlockView<State = BlockState>> PushCx<'_, '_, '_, '_, W> {
    /// `offsetHeadBox`.
    fn place(m: &MovingBlock, b: &Aabb) -> Aabb {
        let d = f64::from(m.shift(m.progress));
        let o = offset(m.facing);
        b.offset(
            f64::from(m.pos[0]) + d * f64::from(o[0]),
            f64::from(m.pos[1]) + d * f64::from(o[1]),
            f64::from(m.pos[2]) + d * f64::from(o[2]),
        )
    }

    /// Pistons move this actor (not a spectator, not `IGNORE`).
    fn movable(&self, a: Actor) -> bool {
        match a {
            Actor::Player => !self.a.p.as_ref().expect("player").0.spectator,
            Actor::Other(k) => self.a.others[k].moved,
        }
    }

    /// `pushEntities(f)`: the entities in the swept area (listed first, then moved one by one
    /// with their boxes as they are then).
    fn push(&mut self, m: &MovingBlock, f: f32) {
        let dir = m.moves();
        let d = f64::from(f - m.progress);
        let boxes = m.head_state().collision().boxes;
        if boxes.is_empty() {
            return;
        }
        let mut hull = boxes[0];
        for b in &boxes[1..] {
            hull = union(&hull, b);
        }
        let bx = Self::place(m, &hull);
        let query = union(&stretch(&bx, dir, d), &bx);
        let list: Vec<Actor> = self
            .a
            .order()
            .filter(|&a| {
                self.movable(a) && self.a.found(a, &query) && self.a.bb(a).intersects(&query)
            })
            .collect();
        for a in list {
            if m.pushed.block() == Block::SLIME_BLOCK
                && let Actor::Player = a
            {
                // Other entities get the velocity too, which their client copies never use.
                let k = axis_index(dir);
                self.a.p.as_mut().expect("player").0.vel[k] = f64::from(offset(dir)[k]);
            }
            let mut h: f64 = 0.0;
            for b in boxes {
                let b3 = stretch(&Self::place(m, b), dir, d);
                let bb = self.a.bb(a);
                if b3.intersects(&bb) {
                    h = h.max(reach(&b3, dir, &bb));
                    if h >= d {
                        break;
                    }
                }
            }
            #[allow(clippy::neg_cmp_op_on_partial_ord)]
            if !(h <= 0.0) {
                let h = h.min(d) + 0.01;
                self.move_by_piston(a, dir, dir, h);
                if !m.extending && m.source {
                    self.pull_back(a, m, dir, d);
                }
            }
        }
    }

    /// `push(entity, direction, amount)`: a retracting head pulls back what overlaps its cell.
    fn pull_back(&mut self, a: Actor, m: &MovingBlock, dir: Facing, amount: f64) {
        let bb = self.a.bb(a);
        let cell = Aabb::FULL.offset(
            f64::from(m.pos[0]),
            f64::from(m.pos[1]),
            f64::from(m.pos[2]),
        );
        if !bb.intersects(&cell) {
            return;
        }
        let back = opposite(dir);
        let d = reach(&cell, back, &bb) + 0.01;
        let inter = sorted_box(
            bb.min_x.max(cell.min_x),
            bb.min_y.max(cell.min_y),
            bb.min_z.max(cell.min_z),
            bb.max_x.min(cell.max_x),
            bb.max_y.min(cell.max_y),
            bb.max_z.min(cell.max_z),
        );
        let e = reach(&cell, back, &inter) + 0.01;
        if (d - e).abs() < 0.01 {
            let d = d.min(amount) + 0.01;
            self.move_by_piston(a, dir, back, d);
        }
    }

    /// `method_23674(f)`: a honey block moved sideways drags what stands on it.
    fn honey(&mut self, m: &MovingBlock, f: f32) {
        if m.pushed.block() != Block::HONEY_BLOCK {
            return;
        }
        let dir = m.moves();
        if axis(dir) == 0 {
            return;
        }
        let top = m
            .pushed
            .collision()
            .boxes
            .iter()
            .map(|b| b.max_y)
            .fold(f64::NEG_INFINITY, f64::max);
        let bx = Self::place(
            m,
            &Aabb::new(0.0, top, 0.0, 1.0, 1.500_000_099_999_999_8, 1.0),
        );
        let e = f64::from(f - m.progress);
        let stands = |bb: &Aabb, pos: [f64; 3], on_ground: bool| {
            on_ground
                && bb.intersects(&bx)
                && pos[0] >= bx.min_x
                && pos[0] <= bx.max_x
                && pos[2] >= bx.min_z
                && pos[2] <= bx.max_z
        };
        let list: Vec<Actor> = self
            .a
            .order()
            .filter(|&a| {
                self.movable(a)
                    && self.a.found(a, &bx)
                    && match a {
                        Actor::Player => {
                            let p = &*self.a.p.as_ref().expect("player").0;
                            stands(&p.bb, p.pos, p.on_ground)
                        }
                        Actor::Other(k) => {
                            let o = &self.a.others[k];
                            stands(&o.bb, o.pos, o.on_ground)
                        }
                    }
            })
            .collect();
        for a in list {
            self.move_by_piston(a, dir, dir, e);
        }
    }

    /// `entity.move(PISTON, e * dir)` with the per-world-tick limit (`pushing`: the thread-local
    /// direction the collision query leaves out).
    fn move_by_piston(&mut self, a: Actor, pushing: Facing, dir: Facing, e: f64) {
        let o = offset(dir);
        let d = [
            e * f64::from(o[0]),
            e * f64::from(o[1]),
            e * f64::from(o[2]),
        ];
        match a {
            Actor::Player => self.move_player(pushing, d),
            Actor::Other(k) => self.move_other(k, pushing, d),
        }
    }

    fn move_player(&mut self, pushing: Facing, d: [f64; 3]) {
        let time = self.time;
        let pistons = &mut *self.pistons;
        let (p, x, around) = self.a.p.as_mut().expect("player");
        if p.no_clip {
            return;
        }
        let Some(d) = piston_budget(&mut pistons.delta, &mut pistons.delta_time, time, d) else {
            return;
        };
        let shapes = MovingShapes::of(pistons, Some(pushing));
        // The collidable others as they are now, after `around`'s boxes.
        let mut boxes: Vec<Aabb>;
        let around = if self.a.others.iter().any(|o| o.collidable) {
            // `getEntityCollisions`: the entities in the sections of the swept box.
            let q = super::collide::stretch(&p.bb, V3::new(d[0], d[1], d[2]))
                .grow(1.0e-7, 1.0e-7, 1.0e-7);
            boxes = around.entities.to_vec();
            boxes.extend(
                self.a
                    .others
                    .iter()
                    .filter(|o| o.collidable && search_finds(o.section, &q))
                    .map(|o| o.bb),
            );
            Surroundings::new()
                .with_entities(&boxes)
                .with_others(around.others)
        } else {
            **around
        };
        let cx = PlayerStepCtx {
            x,
            around: &around,
            shapes: &shapes,
        };
        piston_move(p, cx, self.world, d);
    }

    /// `Entity.move(PISTON, d)` of another entity (no sneak guard; its own step height; the
    /// entities it collides with as they are now).
    fn move_other(&mut self, k: usize, pushing: Facing, d: [f64; 3]) {
        let time = self.time;
        let o = self.a.others[k];
        let mut carry = o.carry;
        let Some(mut m) = piston_budget(&mut carry.delta, &mut carry.delta_time, time, d) else {
            self.a.others[k].carry = carry;
            return;
        };
        let mm = carry.multiplier;
        if mm[0] * mm[0] + mm[1] * mm[1] + mm[2] * mm[2] > 1.0e-7 {
            m = [m[0] * mm[0], m[1] * mm[1], m[2] * mm[2]];
            carry.multiplier = [0.0; 3];
        }
        // `getEntityCollisions`: the entities it collides with, in query order.
        let player_pushable = self.a.p.as_ref().is_some_and(|(p, _, _)| {
            !p.spectator
                && !super::blocks::is_climbable_at(
                    self.world,
                    crate::math::floor(p.pos[0]),
                    crate::math::floor(p.pos[1]),
                    crate::math::floor(p.pos[2]),
                )
        });
        let q =
            super::collide::stretch(&o.bb, V3::new(m[0], m[1], m[2])).grow(1.0e-7, 1.0e-7, 1.0e-7);
        let boxes: Vec<Aabb> = self
            .a
            .order()
            .filter(|&b| self.a.found(b, &q))
            .filter(|&b| match b {
                Actor::Player => o.hits_pushable && player_pushable,
                Actor::Other(j) => {
                    j != k && {
                        let t = &self.a.others[j];
                        t.collidable || (o.hits_pushable && t.pushable)
                    }
                }
            })
            .map(|b| self.a.bb(b))
            .collect();
        let shapes = MovingShapes::of(self.pistons, Some(pushing));
        let border = BorderShape::new(&self.world.world_border());
        let col = Collider {
            w: self.world,
            border: &border,
            ctx: ShapeCtx {
                min_y: o.pos[1],
                descending: false,
            },
            entities: WithMoving {
                ents: &boxes,
                shapes: &shapes,
            },
        };
        let mv = V3::new(m[0], m[1], m[2]);
        let v = col.adjust(mv, &o.bb, o.on_ground, o.step_height);
        let t = &mut self.a.others[k];
        if v.length_sq() > 1.0e-7 {
            t.bb = t.bb.offset(v.x, v.y, v.z);
            t.pos = [
                (t.bb.min_x + t.bb.max_x) / 2.0,
                t.bb.min_y,
                (t.bb.min_z + t.bb.max_z) / 2.0,
            ];
        }
        t.on_ground = mv.y != v.y && mv.y < 0.0;
        // `checkBlockCollision`: a cobweb or a sweet berry bush slows its next move.
        let c = t.bb;
        let lo = |v: f64| crate::math::floor(v + 0.001);
        let hi = |v: f64| crate::math::floor(v - 0.001);
        for x in lo(c.min_x)..=hi(c.max_x) {
            for y in lo(c.min_y)..=hi(c.max_y) {
                for z in lo(c.min_z)..=hi(c.max_z) {
                    let b = self.world.block(x, y, z).block();
                    if b == Block::COBWEB {
                        carry.multiplier = [0.25, f64::from(0.05f32), 0.25];
                    } else if b == Block::SWEET_BERRY_BUSH && t.living {
                        carry.multiplier = [f64::from(0.8f32), 0.75, f64::from(0.8f32)];
                    }
                }
            }
        }
        t.carry = carry;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Read;

    /// The generated source-shape table equals the oracle's dump (`piston_shapes.jsonl.gz`).
    #[test]
    fn source_shapes_match_oracle_dump() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/golden/1.16.5/piston_shapes.jsonl.gz");
        let mut text = String::new();
        flate2::read::GzDecoder::new(std::fs::File::open(path).expect("shapes"))
            .read_to_string(&mut text)
            .expect("gzip");
        let bits = |v: &serde_json::Value| {
            f64::from_bits(u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
        };
        let mut n = 0;
        for line in text.lines() {
            let v: serde_json::Value = serde_json::from_str(line).unwrap();
            let f = v["facing"].as_u64().unwrap() as usize;
            let k = match v["kind"].as_str().unwrap() {
                "head" => 0,
                "base" => 1,
                _ => 2,
            };
            let p = match v["progress"][1].as_str().unwrap() {
                "00000000" => 0,
                "3f000000" => 1,
                _ => 2,
            };
            let t = &SOURCE_SHAPES[f][k][p];
            assert_eq!(t.simple, v["class"] == "simple");
            for (axis, pts) in [("x", t.xs), ("y", t.ys), ("z", t.zs)] {
                let want: Vec<u64> = v[format!("points_{axis}")]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|x| bits(x).to_bits())
                    .collect();
                let got: Vec<u64> = pts.iter().map(|x| x.to_bits()).collect();
                assert_eq!(got, want, "{line}");
            }
            for (i, c) in v["filled"].as_str().unwrap().chars().enumerate() {
                assert_eq!(t.cells[i / 64] >> (i % 64) & 1 == 1, c == '1', "{line}");
            }
            n += 1;
        }
        assert_eq!(n, 54);
    }

    /// Moved multi-box blocks collide with the grid vanilla's re-simplified union gives
    /// (`moving_shapes.jsonl.gz`: every distinct movable multi-box shape, each facing, both
    /// directions, progress 0 / 0.5 / 1).
    #[test]
    fn moving_shapes_match_oracle_dump() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/golden/1.16.5/moving_shapes.jsonl.gz");
        let mut text = String::new();
        flate2::read::GzDecoder::new(std::fs::File::open(path).expect("moving shapes"))
            .read_to_string(&mut text)
            .expect("gzip");
        let bits = |v: &serde_json::Value| u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap();
        let mut n = 0;
        for line in text.lines() {
            let v: serde_json::Value = serde_json::from_str(line).unwrap();
            let progress = f32::from_bits(bits(&v["progress"]) as u32);
            let m = MovingBlock {
                pos: [0, 0, 0],
                pushed: BlockState::from_id(v["state"].as_u64().unwrap() as u16).unwrap(),
                facing: v["facing"].as_u64().unwrap() as Facing,
                extending: v["extending"].as_bool().unwrap(),
                source: false,
                progress,
                last_progress: progress,
                hold: 0,
                removed: false,
            };
            let mut shapes = MovingShapes::default();
            shapes.add_block(&m, None);
            let got: Vec<_> = shapes.at([0, 0, 0]).collect();
            assert_eq!(got.len(), 1, "{line}");
            let shape = got[0].0;
            for (a, axis) in ["x", "y", "z"].into_iter().enumerate() {
                let want: Vec<u64> = v[format!("points_{axis}")]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(bits)
                    .collect();
                let p = shape.axes[a];
                let got: Vec<u64> = (0..=p.cells()).map(|i| p.get(i).to_bits()).collect();
                assert_eq!(got, want, "{axis}: {line}");
            }
            for (i, c) in v["filled"].as_str().unwrap().chars().enumerate() {
                assert_eq!(shape.cells[i / 64] >> (i % 64) & 1 == 1, c == '1', "{line}");
            }
            n += 1;
        }
        assert!(n > 2000);
    }

    /// The handler's block tables equal the oracle's dump (`piston_facts.jsonl.gz`, per block).
    #[test]
    fn facts_match_oracle_dump() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/golden/1.16.5/piston_facts.jsonl.gz");
        let mut text = String::new();
        flate2::read::GzDecoder::new(std::fs::File::open(path).expect("facts"))
            .read_to_string(&mut text)
            .expect("gzip");
        let mut n = 0;
        for line in text.lines() {
            let v: serde_json::Value = serde_json::from_str(line).unwrap();
            let id = v["block"].as_u64().unwrap() as u16;
            let b = match v["piston"].as_u64().unwrap() {
                0 => Behaviour::Normal,
                1 => Behaviour::Destroy,
                2 => Behaviour::Block,
                _ => Behaviour::PushOnly,
            };
            assert_eq!(behaviour(id), b, "behaviour of {id}");
            assert_eq!(
                unbreakable(id),
                v["unbreakable"].as_bool().unwrap(),
                "hardness of {id}"
            );
            assert_eq!(
                has_block_entity(id),
                v["block_entity"].as_bool().unwrap(),
                "block entity of {id}"
            );
            assert!(v["same_for_all_states"].as_bool().unwrap());
            let blk = Block::from_id(id).expect("block");
            assert_eq!(blk.name(), v["name"].as_str().unwrap());
            n += 1;
        }
        assert!(n > 700);
    }
}