ghast-physics 0.5.2

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
//! Pistons on the 1.8.9 client: the blocks a piston moves, their collision while they travel,
//! and how they move the player.
//!
//! The client does not wait for the server to move blocks. A block-action packet makes the
//! client run the piston itself: it picks the blocks to move (at most 12, slime blocks drag their
//! side neighbours, fragile blocks are broken), turns every moving block into a moving-piston
//! block (`piston_extension`, id 36) with a [`MovingBlock`] behind it, and ticks those after the
//! player in every client tick. An extending block pushes everything its leading part overlaps
//! by `0.5625`, `0.5625` and, in its final tick, `0.25` (a retracting one only by `0.25` at the
//! end); a pushed slime block sets the velocity instead. While it travels it collides with a box
//! that grows (or shrinks) with its progress.
//!
//! [`Pistons`] holds the moving blocks in vanilla's ticking order. World changes are returned as
//! [`Edits`] (the physics never writes to a world): apply them to the client world in order.
//! [`tick_with_pistons`] replaces [`super::tick_with`] while any block moves; a world without
//! moving blocks takes the plain tick.

use ghast_data::v1_8::{Block, BlockState};

use super::blocks::{fence_links, is_valid_pos, pane_links, shape_kind, state_at, wall_links};
use super::player::{Options, PlayerState, other_push_move, push_move, tick_with_moving};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::world::{BlockView, WorldBorder};

/// Block id of the moving-piston block (`piston_extension`).
pub const MOVING_PISTON: u8 = 36;
const STICKY_PISTON: u8 = 29;
const PISTON: u8 = 33;
const PISTON_HEAD: u8 = 34;
const OBSIDIAN: u8 = 49;
const SLIME: u8 = 165;
/// The piston handler's limit of moved blocks.
const PUSH_LIMIT: usize = 12;

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

/// 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]
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]
}

/// 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 (pushed or the head going out).
    pub extending: bool,
    /// The piston base itself (retracting).
    pub source: bool,
    /// Progress `0..=1` after the last tick.
    pub progress: f32,
    /// Progress before the last tick (what the collision box uses).
    pub last_progress: f32,
    removed: bool,
    /// Replaced by `setBlockEntity` (invalidated but still in the tick list, which drops it on
    /// its turn and with it whatever block entity the chunk then holds at its position).
    /// Implies `removed`.
    stale: bool,
}

impl MovingBlock {
    /// The box this block collides with right now (vanilla `getCollisionBox` of a moving
    /// piston block): the pushed block's box cut back on the side it moves towards.
    #[must_use]
    pub fn collision_box(&self) -> Option<Aabb> {
        self.collision_box_with(FULL)
    }

    /// [`MovingBlock::collision_box`] with the piston head block's current shared bounds
    /// ([`Pistons::head_bounds`]).
    #[must_use]
    pub fn collision_box_with(&self, head: [f64; 6]) -> Option<Aabb> {
        let f = if self.extending {
            1.0 - self.last_progress
        } else {
            self.last_progress
        };
        shrunk_box(self.pushed, self.pos, f, self.facing, head)
    }
}

/// A block state's box for a moving block (the pushed block's `getCollisionBox(world, pos,
/// state)`, with the world showing the moving block at `pos`). Full cubes, pistons and piston
/// heads are a full cube (a moving head uses the head block's last bounds: the full cube a head
/// collision query leaves behind). Other blocks use their single collision box (not checked
/// against vanilla: their bounds depend on the client's history).
fn base_box(s: BlockState, head: [f64; 6]) -> Option<[f64; 6]> {
    match s.block().id() {
        PISTON | STICKY_PISTON => Some(FULL),
        PISTON_HEAD => Some(head),
        _ => s
            .collision()
            .boxes
            .first()
            .map(|b| [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]),
    }
}

/// `true` when the moving box of `s` is exact here: vanilla builds it from the block's
/// `getCollisionBox(world, pos, state)`, which for most non-full blocks reads bounds the last
/// collision query or crosshair ray left in the block (or the moving-piston block's state at
/// `pos`). Exact: pistons, heads (their shared bounds are tracked), blocks without a box, full
/// cubes, blocks whose box depends on the state alone (snow layers, soul sand, farmland,
/// carpets), walls (their box comes from the neighbours of the moving position) and the
/// slabs, trapdoors, stairs, fences and panes whose shared bounds [`Pistons`] follows (a use
/// while they are not known is reported by [`Pistons::take_unmodelled`]).
#[must_use]
pub fn box_is_tracked(s: BlockState) -> bool {
    match s.block().id() {
        PISTON | STICKY_PISTON | PISTON_HEAD | WALL => true,
        // SnowLayerBlock, SoulSandBlock, FarmlandBlock override getCollisionBox with the state;
        // carpets keep constant bounds.
        78 | 88 | 60 | 171 => true,
        id if shared_kind(id).is_some() => true,
        _ => {
            let c = s.collision();
            c.boxes.is_empty() || c.is_full_cube()
        }
    }
}

const WALL: u8 = 139;

/// How a block object's shared bounds change (blocks whose moving box is built from them).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SharedKind {
    /// Slabs and trapdoors: a collision query or a ray leaves the box of the block's own
    /// state (`SlabBlock.setBoundingBox` / `TrapdoorBlock.setDoorBounds`).
    Own,
    /// A query leaves the full cube (its last step); a ray leaves the sub-cube of its last
    /// pass, which depends on the stairs' facing and half.
    Stairs,
    /// Query and ray leave the post plus arms of the fence's connections, 1.0 high.
    Fence,
    /// A query leaves the last bar it set; a ray the union of the bars.
    Pane,
}

/// The block objects with tracked shared bounds: slot in [`Pistons::shared`] and kind.
const fn shared_kind(id: u8) -> Option<(usize, SharedKind)> {
    use SharedKind::{Fence, Own, Pane, Stairs};
    Some(match id {
        44 => (0, Own),
        126 => (1, Own),
        182 => (2, Own),
        96 => (3, Own),
        167 => (4, Own),
        53 => (5, Stairs),
        67 => (6, Stairs),
        108 => (7, Stairs),
        109 => (8, Stairs),
        114 => (9, Stairs),
        128 => (10, Stairs),
        134 => (11, Stairs),
        135 => (12, Stairs),
        136 => (13, Stairs),
        156 => (14, Stairs),
        163 => (15, Stairs),
        164 => (16, Stairs),
        180 => (17, Stairs),
        85 => (18, Fence),
        113 => (19, Fence),
        188 => (20, Fence),
        189 => (21, Fence),
        190 => (22, Fence),
        191 => (23, Fence),
        192 => (24, Fence),
        101 => (25, Pane),
        102 => (26, Pane),
        160 => (27, Pane),
        _ => return None,
    })
}

const SHARED_SLOTS: usize = 28;

/// The single box of `s` (its first collision box).
fn own_box(s: BlockState) -> Option<[f64; 6]> {
    s.collision()
        .boxes
        .first()
        .map(|b| [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
}

/// The post plus arms of a fence with these connections (north, south, west, east), 1.0 high
/// (what `FenceBlock.appendCollisionBoxes` and `setBoundingBox` leave).
fn fence_union([n, s, w, e]: [bool; 4]) -> [f64; 6] {
    [
        if w { 0.0 } else { 0.375 },
        0.0,
        if n { 0.0 } else { 0.375 },
        if e { 1.0 } else { 0.625 },
        1.0,
        if s { 1.0 } else { 0.625 },
    ]
}

/// The bars of a pane with these connections: along X, then along Z (each `None` when not
/// set): one half towards a single connection on that axis, the whole bar for both or for no
/// connection at all, nothing when only the other axis connects.
fn pane_bars([n, s, w, e]: [bool; 4]) -> (Option<[f64; 6]>, Option<[f64; 6]>) {
    let any = n || s || w || e;
    let (lo, hi) = (0.4375, 0.5625);
    let x = if w && e || !any {
        Some([0.0, 0.0, lo, 1.0, 1.0, hi])
    } else if w {
        Some([0.0, 0.0, lo, 0.5, 1.0, hi])
    } else if e {
        Some([0.5, 0.0, lo, 1.0, 1.0, hi])
    } else {
        None
    };
    let z = if n && s || !any {
        Some([lo, 0.0, 0.0, hi, 1.0, 1.0])
    } else if n {
        Some([lo, 0.0, 0.0, hi, 1.0, 0.5])
    } else if s {
        Some([lo, 0.0, 0.5, hi, 1.0, 1.0])
    } else {
        None
    };
    (x, z)
}

/// The union of a pane's bars (what `PaneBlock.setBoundingBox` leaves, a ray's): towards a
/// single connection on an axis the bar reaches the far side of the middle bar.
fn pane_union([n, s, w, e]: [bool; 4]) -> [f64; 6] {
    let any = n || s || w || e;
    let (lo, hi) = (0.4375, 0.5625);
    let span = |a: bool, b: bool| {
        if (!a || !b) && any {
            if a {
                (0.0, hi)
            } else if b {
                (lo, 1.0)
            } else {
                (lo, hi)
            }
        } else {
            (0.0, 1.0)
        }
    };
    let (x0, x1) = span(w, e);
    let (z0, z1) = span(n, s);
    [x0, 0.0, z0, x1, 1.0, z1]
}

/// The sub-cube a ray leaves in the stairs' bounds: the last of the eight passes that the
/// stairs' facing and half (`meta`) do not skip.
fn stairs_ray_bounds(meta: u8) -> [f64; 6] {
    let last = if meta & 4 != 0 {
        7
    } else {
        // East, west, south, north.
        [7, 6, 7, 5][usize::from(meta & 3)]
    };
    let h = |bit: u8| if last & bit != 0 { 0.5 } else { 0.0 };
    let (x, y, z) = (h(1), h(4), h(2));
    [x, y, z, x + 0.5, y + 0.5, z + 0.5]
}

/// The box of a wall at `pos` from its neighbours there, 1.5 high (`WallBlock.getCollisionBox`
/// sets its bounds from the neighbours before it builds the box).
fn wall_bounds<W: BlockView<State = BlockState>>(w: &W, pos: [i32; 3]) -> [f64; 6] {
    let [n, s, we, e] = wall_links(w, pos[0], pos[1], pos[2]);
    let mut b = [
        if we { 0.0 } else { 0.25 },
        0.0,
        if n { 0.0 } else { 0.25 },
        if e { 1.0 } else { 0.75 },
        1.5,
        if s { 1.0 } else { 0.75 },
    ];
    if n && s && !we && !e {
        b[0] = 0.3125;
        b[3] = 0.6875;
    } else if we && e && !n && !s {
        b[2] = 0.3125;
        b[5] = 0.6875;
    }
    b
}

/// What a moving block collides with.
#[derive(Clone, Copy, Debug)]
enum Shape {
    /// Its box.
    Exact(Aabb),
    /// Built from shared bounds this model does not know: every box it can be lies inside
    /// this one.
    Unknown(Aabb),
}

/// `b` (block-local) at `pos`, cut back by `progress` on the side the block moves towards.
fn shrink(b: [f64; 6], pos: [i32; 3], progress: f32, facing: Facing) -> Aabb {
    let (x, y, z) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
    let mut v = [x + b[0], y + b[1], z + b[2], x + b[3], y + b[4], z + b[5]];
    let o = offset(facing);
    for axis in 0..3 {
        // int * float in float, widened.
        let d = f64::from(o[axis] as f32 * progress);
        if o[axis] < 0 {
            v[axis] -= d;
        } else {
            v[axis + 3] -= d;
        }
    }
    sorted_box(v[0], v[1], v[2], v[3], v[4], v[5])
}

/// A box holding [`shrink`] of every block-local box inside the unit cube: on the moving axis
/// each face lies between the cube's faces, moved or not.
fn shrink_hull(pos: [i32; 3], progress: f32, facing: Facing) -> Aabb {
    let p = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])];
    let o = offset(facing);
    let mut lo = p;
    let mut hi = [p[0] + 1.0, p[1] + 1.0, p[2] + 1.0];
    for axis in 0..3 {
        if o[axis] != 0 {
            let d = f64::from(o[axis] as f32 * progress);
            let (a, b) = (p[axis] - d, (p[axis] + 1.0) - d);
            lo[axis] = lo[axis].min(a).min(b);
            hi[axis] = hi[axis].max(a).max(b);
        }
    }
    Aabb::new(lo[0], lo[1], lo[2], hi[0], hi[1], hi[2])
}

/// `PistonExtensionBlock.getCollisionBox(world, pos, state, progress, direction)`.
fn shrunk_box(
    s: BlockState,
    pos: [i32; 3],
    progress: f32,
    facing: Facing,
    head: [f64; 6],
) -> Option<Aabb> {
    if s.block().id() == MOVING_PISTON || s.is_air() {
        return None;
    }
    let b = base_box(s, head)?;
    Some(shrink(b, pos, progress, facing))
}

/// 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.
#[derive(Clone, Debug, PartialEq)]
pub struct Pistons {
    blocks: Vec<MovingBlock>,
    /// The shared bounds of the piston head block: 0..=5 the plate of that facing (a crosshair
    /// ray passed a head), 6..=8 the full cube (any collision query that met a head; a fresh
    /// client's bounds) with what the caller asked for (`HEAD_FULL`, `HEAD_FULL_RAY`,
    /// `HEAD_FULL_WATCH`).
    head: std::cell::Cell<u8>,
    /// A push met an entity the caller does not follow ([`PistonEntity::followed`]), or its
    /// outcome depended on head bounds this model does not know.
    unmodelled: bool,
    /// The head bounds' history is not known ([`Pistons::forget_head_bounds`]): the model takes
    /// the full cube, vanilla may hold the plate of any facing in this mask (bit = facing).
    head_unknown: std::cell::Cell<u8>,
    /// [`Pistons::set_ray_needed`].
    ray_needed: std::cell::Cell<bool>,
    /// [`Pistons::set_heads_loaded`].
    heads_loaded: std::cell::Cell<bool>,
    /// The shared bounds of the block objects of [`shared_kind`] (block-local), `None` while
    /// not known: a fresh model, or vanilla may have changed them on ticks this model did not
    /// follow ([`Pistons::begin_bounds_tick`]).
    shared: [std::cell::Cell<Option<[f64; 6]>>; SHARED_SLOTS],
    /// The player's `ticks_alive` after the last followed tick ([`Pistons::end_bounds_tick`]).
    bounds_tick: std::cell::Cell<Option<i32>>,
    /// A collision query met a moving box built from shared bounds that are not known
    /// (reported by [`Pistons::take_unmodelled`]).
    bounds_missed: std::cell::Cell<bool>,
    /// [`Pistons::note_use_ray`].
    use_ray: std::cell::Cell<bool>,
}

impl Default for Pistons {
    fn default() -> Pistons {
        Pistons::new()
    }
}

/// The unit cube.
const FULL: [f64; 6] = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
const HEAD_FULL: u8 = 6;
/// The full cube, and the caller wants the ray traced on every tick
/// ([`Pistons::set_ray_needed`]).
const HEAD_FULL_RAY: u8 = 7;
/// The full cube, and piston heads are loaded but none is within the ray's reach: the caller
/// checks that on every tick ([`Pistons::set_heads_loaded`], [`Pistons::watch_only`]).
const HEAD_FULL_WATCH: u8 = 8;

/// The head plate bounds by facing (`PistonHeadBlock.setHeadBoundingBox`).
const HEAD_PLATE: [[f64; 6]; 6] = [
    [0.0, 0.0, 0.0, 1.0, 0.25, 1.0],
    [0.0, 0.75, 0.0, 1.0, 1.0, 1.0],
    [0.0, 0.0, 0.0, 1.0, 1.0, 0.25],
    [0.0, 0.0, 0.75, 1.0, 1.0, 1.0],
    [0.0, 0.0, 0.0, 0.25, 1.0, 1.0],
    [0.75, 0.0, 0.0, 1.0, 1.0, 1.0],
];

impl Pistons {
    /// No moving blocks.
    #[must_use]
    pub const fn new() -> Pistons {
        Pistons {
            blocks: Vec::new(),
            head: std::cell::Cell::new(HEAD_FULL),
            unmodelled: false,
            head_unknown: std::cell::Cell::new(0),
            ray_needed: std::cell::Cell::new(false),
            heads_loaded: std::cell::Cell::new(false),
            shared: [const { std::cell::Cell::new(None) }; SHARED_SLOTS],
            bounds_tick: std::cell::Cell::new(None),
            bounds_missed: std::cell::Cell::new(false),
            use_ray: std::cell::Cell::new(false),
        }
    }

    /// The piston head block's shared bounds (block-local): a moving head's box is built from
    /// them. The full cube unless a crosshair ray passed a head since the last collision query
    /// that met one.
    #[must_use]
    pub fn head_bounds(&self) -> [f64; 6] {
        match self.head.get() {
            f @ 0..=5 => HEAD_PLATE[f as usize],
            _ => FULL,
        }
    }

    /// `true` while the head bounds are a plate, the ray is wanted
    /// ([`Pistons::set_ray_needed`]) or heads are loaded ([`Pistons::set_heads_loaded`]): the
    /// player's ticks must then take [`tick_with_pistons`] (which tracks the collision queries
    /// that reset them) and trace the crosshair ray ([`Pistons::crosshair`]) even when nothing
    /// moves, except while [`Pistons::watch_only`] holds and no head is within the ray's reach.
    #[inline]
    #[must_use]
    pub fn head_bounds_set(&self) -> bool {
        self.head.get() != HEAD_FULL
    }

    /// Piston heads are within the crosshair's reach (`on`): the caller keeps tracing the ray on
    /// every tick ([`Pistons::head_bounds_set`] stays `true`), so the shared bounds stay known.
    pub fn set_ray_needed(&self, on: bool) {
        self.ray_needed.set(on);
        if self.head.get() >= HEAD_FULL {
            self.head.set(self.full_code());
        }
    }

    /// Piston heads may be loaded in the client world (`on`), though maybe out of the
    /// crosshair's reach: [`Pistons::head_bounds_set`] stays `true` so the caller checks the
    /// reach on every tick ([`Pistons::watch_only`]) instead of taking the plain tick blindly.
    pub fn set_heads_loaded(&self, on: bool) {
        self.heads_loaded.set(on);
        if self.head.get() >= HEAD_FULL {
            self.head.set(self.full_code());
        }
    }

    /// `true` when the head bounds are the full cube and the only reason for
    /// [`Pistons::head_bounds_set`] is [`Pistons::set_heads_loaded`]: with nothing moving and no
    /// head within the crosshair's reach the plain tick applies (its ray cannot meet a head, and
    /// its collision queries leave the full cube the bounds already are).
    #[inline]
    #[must_use]
    pub fn watch_only(&self) -> bool {
        self.head.get() == HEAD_FULL_WATCH
    }

    /// The full-cube code for what the caller asked for.
    fn full_code(&self) -> u8 {
        if self.ray_needed.get() {
            HEAD_FULL_RAY
        } else if self.heads_loaded.get() {
            HEAD_FULL_WATCH
        } else {
            HEAD_FULL
        }
    }

    /// The crosshair ray of a client tick (`GameRenderer.updateTargetedEntity(1.0F)`, before the
    /// world tick): `Entity.rayTrace(reach, 1.0F)` from `eye` along `look` (1.8: the head yaw,
    /// which is the previous tick's yaw). Every piston head the ray reaches sets the head bounds
    /// to its plate.
    pub fn crosshair<W: BlockView<State = BlockState>>(
        &self,
        world: &W,
        eye: [f64; 3],
        look: [f64; 3],
        reach: f64,
    ) {
        let end = crate::pick::legacy::ray_end(eye, look, reach);
        let mut last = None;
        crate::pick::legacy::trace(eye, end, true, |p| {
            let s = state_at(world, p[0], p[1], p[2]);
            if s.block().id() == PISTON_HEAD && s.meta() & 7 <= 5 {
                last = Some(s.meta() & 7);
            }
            self.rayed(world, p, s);
            crate::pick::v1_8::shape(world, p, false)
        });
        if let Some(f) = last {
            self.head.set(f);
            self.head_unknown.set(0);
        }
        if self.use_ray.take() {
            self.forget_shared_bounds();
        }
    }

    /// The player used an item this tick whose use may trace a ray of its own (buckets, boats,
    /// bottles, lily pads; `Item.onItemRightClick`), after the crosshair ray and before the
    /// player's move: the next [`Pistons::crosshair`] forgets the shared bounds of slabs,
    /// trapdoors, stairs, fences and panes once it has traced.
    pub fn note_use_ray(&self) {
        self.use_ray.set(true);
    }

    /// The head bounds' history since the last [`Pistons::crosshair`] is not known (ticks
    /// without the ray, e.g. the plain ticks): vanilla's crosshair ray may have left the plate
    /// of a head it passed since, or a collision query the full cube. `facings`: the plates it
    /// may hold (bit `1 << facing`; `0x3f` when nothing is known about the heads it passed).
    /// Until a ray passes a head or a collision query meets one, a push whose outcome would
    /// differ with one of them, or with the full cube while the model holds a plate, is reported
    /// by [`Pistons::take_unmodelled`], and so is the player's move touching a moving head
    /// ([`Pistons::head_unknown_touching`]); the model goes on with its own bounds.
    pub fn forget_head_bounds(&self, facings: u8) {
        let full = u8::from(self.head.get() < HEAD_FULL) << 6;
        self.head_unknown
            .set(self.head_unknown.get() | (facings & 0x3f) | full);
    }

    /// `true` when a live moving block whose 1.8 box comes from bounds this crate does not track
    /// ([`box_is_tracked`] is false: stairs, slabs, fences, walls, panes, trapdoors, ...) is
    /// within one block of `bb`: the client's push or collision there may differ from this
    /// model. Pistons, heads, full cubes, slime, snow layers, soul sand, farmland and carpets are
    /// tracked exactly.
    #[must_use]
    pub fn untracked_near(&self, bb: &Aabb) -> bool {
        let area = bb.grow(1.0, 1.0, 1.0);
        self.iter().any(|m| {
            !box_is_tracked(m.pushed)
                && area.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,
                ))
        })
    }

    /// `true` (once) when a push since the last call met another entity that
    /// [`Pistons::tick_after_entities_among`] was told not to follow
    /// ([`PistonEntity::followed`]: boats, minecarts, riders, ...): vanilla moved it, this model
    /// did not.
    pub fn take_unmodelled(&mut self) -> bool {
        std::mem::take(&mut self.unmodelled) | self.bounds_missed.take()
    }

    /// A tick this model follows begins (the crosshair ray, the player's move with the moving
    /// blocks, the blocks' tick), at the player's `ticks_alive` before it. Unless the last
    /// followed tick ended right before ([`Pistons::end_bounds_tick`]), vanilla's collision
    /// queries and rays since may have changed the shared bounds of slabs, trapdoors, stairs,
    /// fences and panes, which are then not known until a query or ray here sets them.
    pub fn begin_bounds_tick(&self, ticks_alive: i32) {
        if self.bounds_tick.get() != Some(ticks_alive) {
            self.forget_shared_bounds();
        }
    }

    /// A followed tick ended: the player's `ticks_alive` after it.
    pub fn end_bounds_tick(&self, ticks_alive: i32) {
        self.bounds_tick.set(Some(ticks_alive));
    }

    /// Vanilla may have changed the shared bounds of slabs, trapdoors, stairs, fences and
    /// panes in ways this model did not follow (another entity's move or ray, a new player).
    pub fn forget_shared_bounds(&self) {
        for b in &self.shared {
            b.set(None);
        }
        self.bounds_tick.set(None);
    }

    /// A collision query met `s` at `(x, y, z)` (`appendCollisionBoxes`): the bounds it leaves
    /// in the block object.
    #[inline]
    pub(super) fn block_queried<W: BlockView<State = BlockState>>(
        &self,
        w: &W,
        x: i32,
        y: i32,
        z: i32,
        s: BlockState,
    ) {
        let id = s.block().id();
        let Some((slot, kind)) = shared_kind(id) else {
            return;
        };
        let b = match kind {
            SharedKind::Own => own_box(s),
            SharedKind::Stairs => Some(FULL),
            SharedKind::Fence => Some(fence_union(fence_links(w, x, y, z, shape_kind(id)))),
            SharedKind::Pane => {
                let (bx, bz) = pane_bars(pane_links(w, x, y, z));
                bz.or(bx)
            }
        };
        if b.is_some() {
            self.shared[slot].set(b);
        }
    }

    /// The crosshair ray met `s` at `p` (`Block.rayTrace` sets the bounds from the world first;
    /// `StairsBlock.rayTrace` runs its passes, the last one's sub-cube stays).
    fn rayed<W: BlockView<State = BlockState>>(&self, w: &W, p: [i32; 3], s: BlockState) {
        let id = s.block().id();
        let Some((slot, kind)) = shared_kind(id) else {
            return;
        };
        let b = match kind {
            SharedKind::Own => own_box(s),
            SharedKind::Stairs => Some(stairs_ray_bounds(s.meta())),
            SharedKind::Fence => Some(fence_union(fence_links(
                w,
                p[0],
                p[1],
                p[2],
                shape_kind(id),
            ))),
            SharedKind::Pane => Some(pane_union(pane_links(w, p[0], p[1], p[2]))),
        };
        if b.is_some() {
            self.shared[slot].set(b);
        }
    }

    /// What the moving block `s` at `pos` collides with at `progress` (`getCollisionBox` of a
    /// moving-piston block, in `w`).
    fn shape<W: BlockView<State = BlockState>>(
        &self,
        w: &W,
        s: BlockState,
        pos: [i32; 3],
        progress: f32,
        facing: Facing,
    ) -> Option<Shape> {
        let id = s.block().id();
        if id == MOVING_PISTON || s.is_air() {
            return None;
        }
        let b = if id == WALL {
            wall_bounds(w, pos)
        } else if let Some((slot, _)) = shared_kind(id) {
            match self.shared[slot].get() {
                Some(b) => b,
                None => return Some(Shape::Unknown(shrink_hull(pos, progress, facing))),
            }
        } else {
            base_box(s, self.head_bounds())?
        };
        Some(Shape::Exact(shrink(b, pos, progress, facing)))
    }

    /// The box the moving block at `(x, y, z)` adds to a collision query with box `query` (in
    /// `w`, the world the query reads). Built from shared bounds that are not known, a box
    /// that may meet `query` is reported ([`Pistons::take_unmodelled`]).
    #[inline]
    pub(super) fn moving_box_in<W: BlockView<State = BlockState>>(
        &self,
        w: &W,
        x: i32,
        y: i32,
        z: i32,
        query: &Aabb,
    ) -> Option<Aabb> {
        let m = self.at([x, y, z])?;
        let f = if m.extending {
            1.0 - m.last_progress
        } else {
            m.last_progress
        };
        match self.shape(w, m.pushed, m.pos, f, m.facing)? {
            Shape::Exact(b) => Some(b),
            Shape::Unknown(hull) => {
                if hull.intersects(query) {
                    self.bounds_missed.set(true);
                }
                None
            }
        }
    }

    /// `true` while the head bounds' history is not known ([`Pistons::forget_head_bounds`]) and
    /// the player's move from box `before` to box `after` (grown by the step height) touches a
    /// moving piston head's full-cube box: its collision there may have met a plate vanilla
    /// holds and this model does not (a plate box lies inside the full one).
    #[must_use]
    pub fn head_unknown_touching(&self, before: &Aabb, after: &Aabb) -> bool {
        if self.head_unknown.get() == 0 {
            return false;
        }
        let swept = Aabb::new(
            before.min_x.min(after.min_x) - 0.01,
            before.min_y.min(after.min_y) - 0.01,
            before.min_z.min(after.min_z) - 0.01,
            before.max_x.max(after.max_x) + 0.01,
            before.max_y.max(after.max_y) + 0.61,
            before.max_z.max(after.max_z) + 0.01,
        );
        self.iter().any(|m| {
            m.pushed.block().id() == PISTON_HEAD
                && m.collision_box_with(FULL)
                    .is_some_and(|b| b.intersects(&swept))
        })
    }

    /// A collision query met a piston head (`PistonHeadBlock.appendCollisionBoxes` leaves the
    /// full cube in the shared bounds).
    #[inline]
    pub(super) fn head_queried(&self) {
        self.head.set(self.full_code());
        self.head_unknown.set(0);
    }

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

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

    /// The live moving block at a position (vanilla `getBlockEntity`).
    #[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 block at `pos` changed from `old` to `new` in the client world (a block-update packet,
    /// a chunk replaced, …): a moving-piston block replaced by another block drops its moving
    /// block (no final push). Edits returned by this module already did this.
    pub fn block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
        if old.block().id() == MOVING_PISTON
            && new.block().id() != MOVING_PISTON
            && let Some(i) = self.index_at(pos)
        {
            self.blocks.remove(i);
        }
    }

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

    /// Adds a block entity at `pos` (vanilla `setBlockEntity` outside the tick loop: it ticks in
    /// the next tick loop, and replaces one already there).
    fn add(&mut self, mut b: MovingBlock) {
        if let Some(i) = self.index_at(b.pos) {
            // Chunk.addBlockEntity invalidates the old one; it stays in the tick list.
            self.blocks[i].removed = true;
            self.blocks[i].stale = true;
        }
        b.removed = false;
        self.blocks.push(b);
    }

    /// The block-entity half of a client tick without the player (it rides a vehicle: the
    /// pushes of riders are not modelled): the blocks advance and finished ones are placed.
    pub fn tick_blocks<W: BlockView<State = BlockState>>(&mut self, world: &W, edits: &mut Edits) {
        if !self.is_empty() {
            tick_moving(None, world, &Options::default(), self, &mut [], &[], edits);
        }
    }

    /// [`Pistons::tick_blocks`] with the other entities of the client world (see
    /// [`Pistons::tick_after_entities_among`]); the player (riding) is not pushed.
    pub fn tick_blocks_among<W: BlockView<State = BlockState>>(
        &mut self,
        world: &W,
        options: &Options,
        others: &mut [PistonEntity],
        solids: &[(Aabb, [i32; 3])],
        edits: &mut Edits,
    ) {
        if !self.is_empty() {
            tick_moving(None, world, options, self, others, solids, edits);
        }
    }

    /// The block-entity half of a client tick (`World.tickEntities` after every entity): every
    /// moving block advances and pushes the player; finished blocks are placed (appended to
    /// `edits`). Run it after [`tick_player_among_pistons`] and the other entities' ticks.
    pub fn tick_after_entities<W: BlockView<State = BlockState>>(
        &mut self,
        p: &mut PlayerState,
        world: &W,
        options: &Options,
        edits: &mut Edits,
    ) {
        if !self.is_empty() {
            tick_moving(Some(p), world, options, self, &mut [], &[], 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 with `Entity.move`: their own
    /// step height, the blocks, the moving blocks and the solid entities `solids` — boats' boxes
    /// with the chunk entity section they are filed in). Their boxes, positions and states are
    /// updated in place; a search finds an entity by the section it is filed in
    /// ([`PistonEntity::section`]). A push that meets an entity that is not
    /// [`PistonEntity::followed`] leaves it as it is and is reported by
    /// [`Pistons::take_unmodelled`].
    pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
        &mut self,
        p: &mut PlayerState,
        world: &W,
        options: &Options,
        others: &mut [PistonEntity],
        solids: &[(Aabb, [i32; 3])],
        edits: &mut Edits,
    ) {
        if !self.is_empty() {
            tick_moving(Some(p), world, options, self, others, solids, edits);
        }
    }

    /// Keeps only the moving blocks for which `keep` is `true` (e.g. those whose world block is
    /// still a moving-piston block after a packet changed blocks).
    pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
        self.blocks.retain(|b| b.stale || (!b.removed && keep(b)));
    }

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

    /// The block-action packet of a piston (`block` = the packet's block id, 29 sticky or 33,
    /// `action` 0 extend / 1 retract, `data` the facing). Runs the client's piston at `pos`
    /// against `world` and appends the world changes to `edits` (apply them in order). Returns
    /// `false` when the client ignores the packet (no piston-like block at `pos`).
    pub fn block_event<W: BlockView<State = BlockState>>(
        &mut self,
        world: &W,
        pos: [i32; 3],
        block: u8,
        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, block, action, data);
        self.drop_removed();
        r
    }
}

/// 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 (the box's bottom centre after a move).
    pub pos: [f64; 3],
    /// `onGround` on the client (a move sets it; the step-up reads it).
    pub on_ground: bool,
    /// `inWeb` (a cobweb it touched slows its next move; only a move clears it).
    pub in_web: bool,
    /// `stepHeight` (living entities 0.6, other players 0, endermen 1, horses 0.5).
    pub step_height: f32,
    /// Another player that sneaks: its move keeps to the block edges.
    pub sneaking: bool,
    /// Searches find it (not a spectator).
    pub moved: bool,
    /// The caller follows its moves. A push that meets an entity with `false` leaves it as it
    /// is and raises [`Pistons::take_unmodelled`].
    pub followed: bool,
    /// The chunk entity list it is filed in: chunk x, section y (0..16), chunk z.
    pub section: [i32; 3],
}

/// `true` when a search over `q` (`World.getEntitiesIn`: the chunks and entity lists of `q`
/// grown by 2) meets an entity filed in `section` (chunk x, section y, chunk z).
#[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])
}

/// 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 (reads see earlier writes), 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,
}

/// The piston handler's view of a block (oracle `piston_facts.jsonl.gz`).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Behaviour {
    Normal,
    Destroy,
    Block,
}

fn behaviour(id: u8) -> Behaviour {
    match id {
        6
        | 8..=11
        | 18
        | 26
        | 30..=32
        | 37..=40
        | 50
        | 51
        | 55
        | 59
        | 64
        | 65
        | 69..=72
        | 75..=78
        | 81
        | 83
        | 86
        | 91..=94
        | 103..=106
        | 111
        | 115
        | 122
        | 127
        | 131
        | 132
        | 140..=144
        | 147..=150
        | 161
        | 175
        | 193..=197 => Behaviour::Destroy,
        29 | 33 | 34 | 36 | 90 | 119 | 145 | 166 => Behaviour::Block,
        _ => Behaviour::Normal,
    }
}

/// Strength -1 (bedrock, moving piston, portals, end portal frame, command block, barrier).
fn unbreakable(id: u8) -> bool {
    matches!(id, 7 | 36 | 90 | 119 | 120 | 137 | 166)
}

/// Blocks with a block entity.
fn has_block_entity(id: u8) -> bool {
    matches!(
        id,
        23 | 25
            | 36
            | 52
            | 54
            | 61..=63
            | 68
            | 84
            | 116
            | 117
            | 119
            | 130
            | 137
            | 138
            | 140
            | 144
            | 146
            | 149
            | 150
            | 151
            | 154
            | 158
            | 176..=178
    )
}

#[inline]
fn is_piston(id: u8) -> bool {
    id == PISTON || id == STICKY_PISTON
}

/// The facing a block action reads from the world state (`state.get(FACING)`): pistons, piston
/// heads and moving pistons. Other blocks: the client drops the action.
fn facing_of(s: BlockState) -> Option<Facing> {
    match s.block().id() {
        PISTON | STICKY_PISTON | PISTON_HEAD | MOVING_PISTON => {
            let f = s.meta() & 7;
            (f <= 5).then_some(f)
        }
        _ => None,
    }
}

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

    /// The client world's `setBlockState`: nothing outside the world or in an unloaded column,
    /// the same state is no change, a moving-piston block replaced drops its block entity.
    fn set(&mut self, p: [i32; 3], s: BlockState) {
        if !is_valid_pos(p[0], p[1], p[2]) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
            return;
        }
        let old = self.get(p);
        if old == s {
            return;
        }
        if old.block().id() == MOVING_PISTON
            && s.block().id() != MOVING_PISTON
            && let Some(i) = self.pistons.index_at(p)
        {
            self.pistons.blocks[i].removed = true;
        }
        self.edits.push((p, s));
    }

    /// `setBlockEntity` right after the moving-piston block was placed.
    fn add_moving(
        &mut self,
        pos: [i32; 3],
        pushed: BlockState,
        facing: Facing,
        extending: bool,
        source: bool,
    ) {
        if !is_valid_pos(pos[0], pos[1], pos[2])
            || !self.w.is_chunk_loaded(pos[0] >> 4, pos[2] >> 4)
        {
            // The block entity would sit in the tick list without a world position: inert.
            return;
        }
        self.pistons.add(MovingBlock {
            pos,
            pushed,
            facing,
            extending,
            source,
            progress: 0.0,
            last_progress: 0.0,
            removed: false,
            stale: false,
        });
    }

    /// `PistonBlockEntity.finish`: jump to the end without pushing.
    fn finish(&mut self, i: usize) {
        let b = self.pistons.blocks[i];
        if b.last_progress < 1.0 {
            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().id() == MOVING_PISTON {
                self.set(b.pos, b.pushed);
            }
        }
    }

    fn on_event(&mut self, pos: [i32; 3], block: u8, action: u8, data: u8) -> bool {
        let state = self.get(pos);
        let Some(facing) = facing_of(state) else {
            return false;
        };
        let sticky = block == STICKY_PISTON;
        match action {
            0 => {
                if !self.move_blocks(pos, facing, true, sticky) {
                    return true;
                }
                // `state.with(EXTENDED, true)`: only a piston state has the property (others
                // throw here, after the move).
                if is_piston(state.block().id()) {
                    self.set(pos, BlockState::new(state.block(), state.meta() | 8));
                }
            }
            1 => {
                if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
                    self.finish(i);
                }
                let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
                self.set(
                    pos,
                    BlockState::new(moving, facing | if sticky { 8 } else { 0 }),
                );
                let base = Block::from_id(block).unwrap_or(state.block());
                self.add_moving(pos, BlockState::new(base, data & 15), facing, false, true);
                if sticky {
                    let p2 = step(pos, facing, 2);
                    let b = self.get(p2);
                    let mut finished = false;
                    if b.block().id() == 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;
                    }
                    let id = b.block().id();
                    if !finished
                        && !b.is_air()
                        && self.movable(b, p2, opposite(facing), false)
                        && (behaviour(id) == Behaviour::Normal || is_piston(id))
                    {
                        self.move_blocks(pos, facing, false, sticky);
                    }
                } else {
                    self.set(step(pos, facing, 1), BlockState::AIR);
                }
            }
            _ => {}
        }
        true
    }

    /// `PistonBlock.isMovable`.
    fn movable(&self, b: BlockState, p: [i32; 3], dir: Facing, can_break: bool) -> bool {
        let id = b.block().id();
        if id == OBSIDIAN {
            return false;
        }
        if !self.w.world_border().contains_block(p[0], p[2]) {
            return false;
        }
        if p[1] < 0 || (dir == 0 && p[1] == 0) || p[1] > 255 || (dir == 1 && p[1] == 255) {
            return false;
        }
        if is_piston(id) {
            if self.get(p).meta() & 8 != 0 {
                return false;
            }
        } else {
            if unbreakable(id) {
                return false;
            }
            match behaviour(id) {
                Behaviour::Block => return false,
                Behaviour::Destroy => return can_break,
                Behaviour::Normal => {}
            }
        }
        !has_block_entity(id)
    }

    /// `PistonBlock.move`: `extend` pushes away from the piston, otherwise a sticky piston
    /// pulls the block two in front of it.
    fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
        if !extend {
            self.set(step(pos, facing, 1), BlockState::AIR);
        }
        let mut h = Handler::new(pos, facing, extend);
        if !h.calculate(self) {
            return false;
        }
        let push = if extend { facing } else { opposite(facing) };
        for &b in h.broken.iter().rev() {
            self.set(b, BlockState::AIR);
        }
        let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
        for &m in h.moved.iter().rev() {
            let s = self.get(m);
            self.set(m, BlockState::AIR);
            let dst = step(m, push, 1);
            self.set(dst, BlockState::new(moving, facing));
            self.add_moving(dst, s, facing, extend, false);
        }
        if extend {
            let head_pos = step(pos, facing, 1);
            let t = if sticky { 8 } else { 0 };
            let head = Block::from_id(PISTON_HEAD).expect("piston head");
            self.set(head_pos, BlockState::new(moving, facing | t));
            self.add_moving(
                head_pos,
                BlockState::new(head, facing | t),
                facing,
                true,
                false,
            );
        }
        true
    }
}

/// `PistonHandler`: the blocks a piston moves and breaks.
struct Handler {
    from: [i32; 3],
    to: [i32; 3],
    dir: Facing,
    moved: Vec<[i32; 3]>,
    broken: Vec<[i32; 3]>,
}

impl Handler {
    fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
        let (dir, to) = if extend {
            (facing, step(pos, facing, 1))
        } else {
            (opposite(facing), step(pos, facing, 2))
        };
        Handler {
            from: pos,
            to,
            dir,
            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.dir, false) {
            if behaviour(b.block().id()) != Behaviour::Destroy {
                return false;
            }
            self.broken.push(self.to);
            return true;
        }
        if !self.try_move(ov, self.to) {
            return false;
        }
        let mut i = 0;
        while i < self.moved.len() {
            let p = self.moved[i];
            if ov.get(p).block().id() == SLIME && !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],
    ) -> bool {
        let mut b = ov.get(pos);
        if b.is_air()
            || !ov.movable(b, pos, self.dir, false)
            || pos == self.from
            || self.moved.contains(&pos)
        {
            return true;
        }
        let back = opposite(self.dir);
        let mut i = 1usize;
        if i + self.moved.len() > PUSH_LIMIT {
            return false;
        }
        while b.block().id() == SLIME {
            let bp = step(pos, back, i as i32);
            b = ov.get(bp);
            if b.is_air() || !ov.movable(b, bp, self.dir, false) || 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.dir, 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 ov.get(p).block().id() == SLIME && !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.dir, true) || 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;
        }
    }

    /// `setMovedBlocks(from, to)`: the last `from` entries move in front of entry `to`.
    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 {
        for d in 0..6 {
            if axis(d) != axis(self.dir) && !self.try_move(ov, step(pos, d, 1)) {
                return false;
            }
        }
        true
    }
}

/// One client tick with moving blocks: the player's tick (moving blocks collide with their
/// current box), then every moving block ticks in order and pushes the player; blocks that
/// finish are placed (appended to `edits`). With no moving blocks the result equals
/// [`super::tick_with`]'s; call that one then (it is the faster path).
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    input: &TickInput,
    world: &W,
    options: &Options,
    pistons: &mut Pistons,
    out: &mut Packets,
    edits: &mut Edits,
) {
    // A distinct world type: the moving tick's code is its own copy, so the plain tick's helpers
    // keep a single caller each and stay inlined there (measured: +4 % instructions otherwise).
    let view = Distinct(world);
    tick_with_moving(p, input, &view, options, pistons, out);
    tick_moving(Some(p), world, options, pistons, &mut [], &[], edits);
}

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

/// The world seen through another type (see [`tick_with_pistons`]).
struct Distinct<'a, W>(&'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()
    }
}

/// The block-entity half of the tick (`World.tickEntities` after the entities).
fn tick_moving<W: BlockView<State = BlockState>>(
    mut p: Option<&mut PlayerState>,
    world: &W,
    options: &Options,
    pistons: &mut Pistons,
    others: &mut [PistonEntity],
    solids: &[(Aabb, [i32; 3])],
    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.stale {
            // The tick loop drops an invalid block entity and removes the chunk's block entity
            // at its position (the one that replaced it, which then never ticks).
            pistons.blocks[i - 1].stale = false;
            if let Some(j) = pistons.index_at(b.pos) {
                pistons.blocks[j].removed = true;
            }
            continue;
        }
        if b.removed || !(0..256).contains(&b.pos[1]) || !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 {
            let m = *m;
            if p.is_some() || !others.is_empty() {
                let mut a = Pushes {
                    p: p.as_deref_mut(),
                    others,
                    solids,
                };
                push(
                    &mut a,
                    world,
                    options,
                    pistons,
                    &edits[start..],
                    &m,
                    1.0,
                    0.25,
                );
            }
            pistons.blocks[i - 1].removed = true;
            let mut ov = Overlay {
                w: world,
                edits,
                start,
                pistons,
            };
            if ov.get(m.pos).block().id() == MOVING_PISTON {
                ov.set(m.pos, m.pushed);
            }
        } else {
            m.progress += 0.5;
            if m.progress >= 1.0 {
                m.progress = 1.0;
            }
            let m = *m;
            if m.extending && (p.is_some() || !others.is_empty()) {
                let distance = m.progress - m.last_progress + 0.0625;
                let mut a = Pushes {
                    p: p.as_deref_mut(),
                    others,
                    solids,
                };
                push(
                    &mut a,
                    world,
                    options,
                    pistons,
                    &edits[start..],
                    &m,
                    m.progress,
                    distance,
                );
            }
        }
    }
    pistons.drop_removed();
}

/// The entities a push can move: the player and the others.
struct Pushes<'a, 'b, 'c> {
    p: Option<&'a mut PlayerState>,
    others: &'b mut [PistonEntity],
    solids: &'c [(Aabb, [i32; 3])],
}

/// `pushEntities(progress, distance)`. The entities found are moved one by one; their moves do
/// not meet each other (players and mobs are not solid for a move; boats are, but a boat in a
/// push is not followed), so the player goes first.
#[allow(clippy::too_many_arguments)]
fn push<W: BlockView<State = BlockState>>(
    a: &mut Pushes<'_, '_, '_>,
    world: &W,
    options: &Options,
    pistons: &mut Pistons,
    edits: &[([i32; 3], BlockState)],
    m: &MovingBlock,
    progress: f32,
    distance: f32,
) {
    let progress = if m.extending {
        1.0 - progress
    } else {
        progress - 1.0
    };
    let view = Layered { w: world, edits };
    let bx = match pistons.shape(&view, m.pushed, m.pos, progress, m.facing) {
        None => return,
        Some(Shape::Exact(b)) => b,
        Some(Shape::Unknown(hull)) => {
            unknown_push(a, pistons, &hull);
            return;
        }
    };
    let o = offset(m.facing);
    let slime = m.pushed.block().id() == SLIME && m.extending;
    let d = [
        f64::from(distance * o[0] as f32),
        f64::from(distance * o[1] as f32),
        f64::from(distance * o[2] as f32),
    ];
    if m.pushed.block().id() == PISTON_HEAD && pistons.head_unknown.get() != 0 {
        plate_check(a, pistons, m, progress, &bx);
    }
    // Spectators are not pushed (the entity query skips them).
    if let Some(p) = a.p.as_deref_mut()
        && !p.spectator
        && p.bb.intersects(&bx)
    {
        if slime {
            let axis = axis(m.facing) as usize;
            // Direction axes: 0 = y, 1 = z, 2 = x.
            let i = [1, 2, 0][axis];
            p.vel[i] = f64::from(o[i]);
        } else {
            push_move(p, &view, options, pistons, d);
        }
    }
    if a.others.is_empty() {
        return;
    }
    push_others(a, &view, options, pistons, &bx, slime, d);
}

/// A moving block whose box comes from shared bounds that are not known pushes: reported when
/// an entity it can push meets `hull` (holding every box it can be); none does, it pushes
/// nothing.
#[cold]
#[inline(never)]
fn unknown_push(a: &Pushes<'_, '_, '_>, pistons: &mut Pistons, hull: &Aabb) {
    let player =
        a.p.as_deref()
            .is_some_and(|p| !p.spectator && p.bb.intersects(hull));
    let other = a
        .others
        .iter()
        .any(|e| e.moved && search_finds(e.section, hull) && e.bb.intersects(hull));
    if player || other {
        pistons.unmodelled = true;
    }
}

/// A moving head pushes while its bounds are not known: the push is reported when some plate
/// would push a different set of entities than the full cube `bx` does.
#[cold]
#[inline(never)]
fn plate_check(
    a: &Pushes<'_, '_, '_>,
    pistons: &mut Pistons,
    m: &MovingBlock,
    progress: f32,
    bx: &Aabb,
) {
    let mask = pistons.head_unknown.get();
    for (f, plate) in HEAD_PLATE.into_iter().chain([FULL]).enumerate() {
        if mask & (1 << f) == 0 {
            continue;
        }
        let alt = shrunk_box(m.pushed, m.pos, progress, m.facing, plate);
        let differs = |bb: &Aabb| bb.intersects(bx) != alt.is_some_and(|b| bb.intersects(&b));
        let player =
            a.p.as_deref()
                .is_some_and(|p| !p.spectator && differs(&p.bb));
        let other = a
            .others
            .iter()
            .any(|e| e.moved && search_finds(e.section, bx) && differs(&e.bb));
        if player || other {
            pistons.unmodelled = true;
            return;
        }
    }
}

/// The other entities' part of [`push`] (`bx`: the moving block's box).
#[cold]
#[inline(never)]
fn push_others<W: BlockView<State = BlockState>>(
    a: &mut Pushes<'_, '_, '_>,
    world: &W,
    options: &Options,
    pistons: &mut Pistons,
    bx: &Aabb,
    slime: bool,
    d: [f64; 3],
) {
    let mut solids: Vec<Aabb> = Vec::new();
    for e in a.others.iter_mut() {
        if !e.moved || !search_finds(e.section, bx) || !e.bb.intersects(bx) {
            continue;
        }
        if !e.followed {
            pistons.unmodelled = true;
            continue;
        }
        if slime {
            // Only the velocity, which the client copy does not move by.
            continue;
        }
        // `World.doesBoxCollide`: the boats in the lists of the swept box grown by 0.25.
        let q = e.bb.stretch(d[0], d[1], d[2]).grow(0.25, 0.25, 0.25);
        solids.clear();
        solids.extend(
            a.solids
                .iter()
                .filter(|s| search_finds(s.1, &q))
                .map(|s| s.0),
        );
        other_push_move(
            &mut e.bb,
            &mut e.pos,
            &mut e.on_ground,
            &mut e.in_web,
            e.sneaking,
            e.step_height,
            &solids,
            world,
            options,
            pistons,
            d,
        );
    }
}

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

    /// The handler's block tables equal the oracle's dump (`piston_facts.jsonl.gz`).
    #[test]
    fn facts_match_oracle_dump() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/golden/1.8.9/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["id"].as_u64().unwrap() as u8;
            let b = match v["piston"].as_u64().unwrap() {
                0 => Behaviour::Normal,
                1 => Behaviour::Destroy,
                _ => Behaviour::Block,
            };
            assert!(behaviour(id) == b, "behaviour of {id}");
            assert_eq!(
                unbreakable(id),
                v["unbreakable"].as_bool().unwrap(),
                "strength of {id}"
            );
            assert_eq!(
                has_block_entity(id),
                v["block_entity"].as_bool().unwrap(),
                "block entity of {id}"
            );
            let air = Block::from_id(id).is_some_and(|b| b.default_state().is_air());
            assert_eq!(air, v["air"].as_bool().unwrap(), "air of {id}");
            n += 1;
        }
        assert_eq!(n, 198);
    }

    /// Every box the shared bounds of a slab, trapdoor, stairs, fence or pane can hold (their
    /// states, rays, queries, constructors and item-render bounds), moved like a moving block,
    /// lies inside [`shrink_hull`]: an unknown moving box missing a query or an entity there
    /// misses it in every case.
    #[test]
    fn shrink_hull_holds_every_shared_box() {
        let mut cands = vec![
            FULL,
            [0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
            [0.0, 0.5, 0.0, 1.0, 1.0, 1.0],
            [0.0, 0.40625, 0.0, 1.0, 0.59375, 1.0],
        ];
        for t in 0..16u16 {
            cands.extend(own_box(BlockState::from_raw_vanilla(96 << 4 | t)));
        }
        cands.extend((0..8).map(stairs_ray_bounds));
        for c in 0..16u8 {
            let l = [c & 1 != 0, c & 2 != 0, c & 4 != 0, c & 8 != 0];
            cands.push(fence_union(l));
            cands.push(pane_union(l));
            let (x, z) = pane_bars(l);
            cands.extend(x);
            cands.extend(z);
        }
        for pos in [[0, 64, 0], [-3, 70, 5], [7, 1, -9]] {
            for facing in 0..6 {
                for p in [-1.0f32, -0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0] {
                    let h = shrink_hull(pos, p, facing);
                    for c in &cands {
                        let b = shrink(*c, pos, p, facing);
                        assert!(
                            h.min_x <= b.min_x
                                && h.min_y <= b.min_y
                                && h.min_z <= b.min_z
                                && b.max_x <= h.max_x
                                && b.max_y <= h.max_y
                                && b.max_z <= h.max_z,
                            "{c:?} at {pos:?} facing {facing} progress {p}: {b:?} outside {h:?}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn empty_pistons_take_the_plain_tick() {
        let mut w = super::super::memory_world();
        w.load_chunks(-1, -1, 0, 0);
        w.fill_raw([-4, 63, -4], [4, 63, 4], 1 << 4);
        let mut a = PlayerState::new([0.5, 64.0, 0.5], 0.0, 0.0);
        let mut b = a;
        let input = TickInput::default();
        let (mut oa, mut ob) = (Packets::new(), Packets::new());
        let mut edits = Edits::new();
        for _ in 0..20 {
            oa.clear();
            ob.clear();
            super::super::tick_with(&mut a, &input, &w, &Options::default(), &mut oa);
            tick_with_pistons(
                &mut b,
                &input,
                &w,
                &Options::default(),
                &mut Pistons::new(),
                &mut ob,
                &mut edits,
            );
            assert_eq!(a, b);
            assert_eq!(oa.as_slice(), ob.as_slice());
        }
        assert!(edits.is_empty());
    }
}