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
//! The 1.16.5 client's shape updates around a piston's writes.
//!
//! From 1.13 on, `World.setBlockState` without flag 16 makes every neighbour recompute its state
//! for the changed block (`getStateForNeighborUpdate`), on the client too, and a finished move
//! places the moved block's `postProcessState` (its state recomputed against all six
//! neighbours). On the client a result of air is dropped (`Block.replace` breaks blocks only on
//! the server), scheduled ticks do nothing and `neighborUpdate` never runs, so what changes the
//! client's world are the blocks that derive properties from their neighbours. This module
//! models fences, panes and iron bars, walls, stairs, fence gates in walls, snowy grass,
//! chests, mushroom blocks, attached stems, campfires, chorus plants and concrete powder (doors
//! and beds only take a property from their other half, which a piston never writes: they stay
//! or turn into air, which the client drops); the other blocks that would change on the client
//! ([`Kind::Other`]) leave the state as it is and report the update as not modelled.

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

use super::piston::{Facing, offset};
use crate::voxel::{EPSILON, VoxelShape};

/// What a block's `getStateForNeighborUpdate` does on the client (by the class that declares
/// it; oracle `piston_facts.jsonl.gz`, field `shape_update`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Kind {
    /// The state stays (or becomes air, which the client drops; or only ticks are scheduled).
    Inert,
    /// `FenceBlock`: horizontal connections.
    Fence,
    /// `PaneBlock` (glass panes, iron bars): horizontal connections.
    Pane,
    /// `WallBlock`: side heights and the post.
    Wall,
    /// `StairsBlock`: the corner shape.
    Stairs,
    /// `FenceGateBlock`: `in_wall`.
    Gate,
    /// `SnowyBlock` (grass block, podzol, mycelium): `snowy`.
    Snowy,
    /// `CarpetBlock`: air over air (matters where a finished move places it).
    Carpet,
    /// `CoralParentBlock` (dead corals and coral fans): air without a solid top below.
    DeadCoral,
    /// `DeadCoralWallFanBlock`: air without a solid side behind.
    DeadWallFan,
    /// `ChestBlock`: a double chest whose other half's cell changed becomes single (and a single
    /// one joins a double chest's half next to it).
    Chest,
    /// `MushroomBlock` (mushroom blocks and stems): the face towards the same block is hidden.
    Mushroom,
    /// `AttachedStemBlock`: a plain stem of age 7 once its gourd is gone.
    AttachedStem,
    /// `CampfireBlock`: `signal_fire` over a hay bale.
    Campfire,
    /// `ChorusPlantBlock`: connections to chorus plants and flowers (and end stone below).
    ChorusPlant,
    /// `ConcretePowderBlock`: concrete next to water.
    ConcretePowder,
    /// Changes the client's world in a way not modelled (chests, doors, beds, redstone wire,
    /// vines, fire, ...).
    Other,
}

/// The client shape-update behaviour of a block.
#[must_use]
pub(crate) fn kind(b: Block) -> Kind {
    let n = b.name();
    if n.ends_with("_fence_gate") {
        Kind::Gate
    } else if n.ends_with("_fence") {
        Kind::Fence
    } else if n == "iron_bars" || n == "glass_pane" || n.ends_with("_stained_glass_pane") {
        Kind::Pane
    } else if n.ends_with("_wall") {
        Kind::Wall
    } else if n.ends_with("_stairs") {
        Kind::Stairs
    } else if matches!(n, "grass_block" | "podzol" | "mycelium") {
        Kind::Snowy
    } else if n.ends_with("_carpet") {
        Kind::Carpet
    } else if n.starts_with("dead_") && n.ends_with("_coral_wall_fan") {
        Kind::DeadWallFan
    } else if n.starts_with("dead_") && (n.ends_with("_coral") || n.ends_with("_coral_fan")) {
        Kind::DeadCoral
    } else if n == "chest" || n == "trapped_chest" {
        Kind::Chest
    } else if n.ends_with("_mushroom_block") || n == "mushroom_stem" {
        Kind::Mushroom
    } else if n.starts_with("attached_") {
        Kind::AttachedStem
    } else if n == "campfire" || n == "soul_campfire" {
        Kind::Campfire
    } else if n == "chorus_plant" {
        Kind::ChorusPlant
    } else if n.ends_with("_concrete_powder") {
        Kind::ConcretePowder
    } else if matches!(
        n,
        "kelp"
            | "kelp_plant"
            | "weeping_vines"
            | "weeping_vines_plant"
            | "twisting_vines"
            | "twisting_vines_plant"
            | "bamboo"
            | "bamboo_sapling"
            | "bell"
            | "note_block"
            | "bubble_column"
            | "fire"
            | "redstone_wire"
            | "tripwire"
            | "tripwire_hook"
            | "vine"
    ) {
        Kind::Other
    } else {
        Kind::Inert
    }
}

/// `BlockTags.WOODEN_FENCES` among the fences (the nether brick fence is not wooden).
fn wooden_fence(b: Block) -> bool {
    b.name() != "nether_brick_fence"
}

/// `Block.cannotConnect`.
#[must_use]
pub(crate) fn cannot_connect(b: Block) -> bool {
    let n = b.name();
    n.ends_with("_leaves")
        || n == "shulker_box"
        || n.ends_with("_shulker_box")
        || matches!(
            n,
            "barrier" | "carved_pumpkin" | "jack_o_lantern" | "melon" | "pumpkin"
        )
}

/// `BlockTags.WALL_POST_OVERRIDE`.
#[must_use]
pub(crate) fn wall_post_override(b: Block) -> bool {
    let n = b.name();
    n.ends_with("_sign")
        || n.ends_with("_banner")
        || n.ends_with("_pressure_plate")
        || matches!(n, "torch" | "soul_torch" | "redstone_torch" | "tripwire")
}

/// What the rules read of the client world.
pub(super) trait UpdateView {
    /// The block state at a position.
    fn state(&self, p: [i32; 3]) -> BlockState;
    /// `isSideSolidFullSquare(world, p, face)` of the state `s` at `p`; `None` when it is not
    /// known here (a block with dynamic bounds other than a moving block).
    fn side_solid(&self, p: [i32; 3], s: BlockState, face: Facing) -> Option<bool>;
    /// Whether the down face of `s`'s collision shape at `p` covers the footprint
    /// `[x0, z0, x1, z1]` (block-local); `None` when not known here.
    fn down_face_covers(&self, p: [i32; 3], s: BlockState, rect: [f64; 4]) -> Option<bool>;
}

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

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

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

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

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

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

/// `rotateYClockwise` of a horizontal direction.
const fn clockwise(f: Facing) -> Facing {
    match f {
        2 => 5,
        5 => 3,
        3 => 4,
        _ => 2,
    }
}

/// `rotateYCounterclockwise` of a horizontal direction.
const fn counter_clockwise(f: Facing) -> Facing {
    match f {
        2 => 4,
        4 => 3,
        3 => 5,
        _ => 2,
    }
}

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

/// The data's side of a direction id.
pub(super) fn side(f: Facing) -> Side {
    match f {
        0 => Side::Down,
        1 => Side::Up,
        2 => Side::North,
        3 => Side::South,
        4 => Side::West,
        _ => Side::East,
    }
}

/// `getStateForNeighborUpdate` on the client: the new state of `s` at `pos` after its
/// neighbour in direction `dir` (at `npos`) became `n`. `Err` with the unchanged state when
/// the update is not modelled. An air result is real for `postProcessState` (a finished move
/// places it) and dropped by neighbour updates; only movable blocks give it here (other
/// blocks that turn into air are never post-processed, so they keep their state).
pub(super) fn neighbor_update<V: UpdateView>(
    v: &V,
    s: BlockState,
    dir: Facing,
    n: BlockState,
    pos: [i32; 3],
    npos: [i32; 3],
) -> Result<BlockState, BlockState> {
    let horizontal = dir >= 2;
    match kind(s.block()) {
        Kind::Inert => Ok(s),
        Kind::Other => Err(s),
        Kind::Fence if horizontal => {
            let solid = v.side_solid(npos, n, opposite(dir)).ok_or(s)?;
            let c = fence_connects(s.block(), n, solid, opposite(dir));
            Ok(with(s, NAMES[dir as usize], bool_str(c)))
        }
        Kind::Pane if horizontal => {
            let solid = v.side_solid(npos, n, opposite(dir)).ok_or(s)?;
            let c = pane_connects(n, solid);
            Ok(with(s, NAMES[dir as usize], bool_str(c)))
        }
        Kind::Gate => {
            let f = facing_of(s).ok_or(s)?;
            if axis(clockwise(f)) != axis(dir) {
                return Ok(s);
            }
            let w = is_wall(n.block()) || is_wall(v.state(step(pos, opposite(dir))).block());
            Ok(with(s, "in_wall", bool_str(w)))
        }
        Kind::Snowy if dir == 1 => {
            let b = n.block();
            let snowy = b == Block::SNOW_BLOCK || b == Block::SNOW;
            Ok(with(s, "snowy", bool_str(snowy)))
        }
        Kind::Stairs if horizontal => Ok(with(s, "shape", stair_shape(v, s, pos))),
        Kind::Carpet => Ok(if v.state(step(pos, 0)).is_air() {
            BlockState::AIR
        } else {
            s
        }),
        Kind::DeadCoral if dir == 0 => {
            let below = step(pos, 0);
            let solid = v.side_solid(below, v.state(below), 1).ok_or(s)?;
            Ok(if solid { s } else { BlockState::AIR })
        }
        Kind::DeadWallFan => {
            let f = facing_of(s).ok_or(s)?;
            if opposite(dir) != f {
                return Ok(s);
            }
            let behind = step(pos, opposite(f));
            let solid = v.side_solid(behind, v.state(behind), f).ok_or(s)?;
            Ok(if solid { s } else { BlockState::AIR })
        }
        Kind::Chest => Ok(chest_update(s, dir, n)),
        Kind::Mushroom if n.block() == s.block() => Ok(with(s, NAMES[dir as usize], "false")),
        Kind::AttachedStem => {
            let f = facing_of(s).ok_or(s)?;
            let (gourd, stem) = if s.block() == Block::ATTACHED_PUMPKIN_STEM {
                (Block::PUMPKIN, Block::PUMPKIN_STEM)
            } else {
                (Block::MELON, Block::MELON_STEM)
            };
            Ok(if dir == f && n.block() != gourd {
                with(stem.default_state(), "age", "7")
            } else {
                s
            })
        }
        Kind::Campfire if dir == 0 => Ok(with(
            s,
            "signal_fire",
            bool_str(n.block() == Block::HAY_BLOCK),
        )),
        Kind::ChorusPlant => {
            if !chorus_can_stay(v, pos) {
                // Only a scheduled tick (nothing on the client).
                return Ok(s);
            }
            let b = n.block();
            let c = b == Block::CHORUS_PLANT
                || b == Block::CHORUS_FLOWER
                || (dir == 0 && b == Block::END_STONE);
            Ok(with(s, NAMES[dir as usize], bool_str(c)))
        }
        Kind::ConcretePowder => {
            let wet = |d: Facing| {
                let q = step(pos, d);
                let ns = v.state(q);
                if !ns
                    .fluid()
                    .is_some_and(|f| f.kind == ghast_data::FluidKind::Water)
                {
                    return Some(false);
                }
                // `isSideSolidFullSquare(world, pos, ..)`: the neighbour's state at the
                // powder's own position.
                v.side_solid(pos, ns, opposite(d)).map(|solid| !solid)
            };
            let mut hardens = false;
            for d in 1..6 {
                if wet(d).ok_or(s)? {
                    hardens = true;
                    break;
                }
            }
            Ok(if hardens { concrete_of(s.block()) } else { s })
        }
        Kind::Wall if dir != 0 => {
            let mut c = [false; 4];
            for (k, side) in WALL_SIDES.iter().enumerate() {
                c[k] = s.get(prop(side)) != Some("none");
            }
            let above = if dir == 1 {
                (npos, n)
            } else {
                let k = WALL_SIDES
                    .iter()
                    .position(|w| *w == NAMES[dir as usize])
                    .expect("horizontal");
                let solid = v.side_solid(npos, n, opposite(dir)).ok_or(s)?;
                c[k] = wall_connects(n, solid, opposite(dir));
                let up = step(pos, 1);
                (up, v.state(up))
            };
            wall_state(v, s, above.0, above.1, c).ok_or(s)
        }
        _ => Ok(s),
    }
}

/// `ChestBlock.getFacing`: the direction of a double chest's other half (a single chest's
/// counter-clockwise side).
fn chest_partner(s: BlockState) -> Option<Facing> {
    let f = facing_of(s)?;
    Some(if s.get(prop("type")) == Some("left") {
        clockwise(f)
    } else {
        counter_clockwise(f)
    })
}

/// `ChestBlock.getStateForNeighborUpdate` (`n`: the neighbour in direction `dir`).
fn chest_update(s: BlockState, dir: Facing, n: BlockState) -> BlockState {
    if n.block() == s.block() && dir >= 2 {
        let t = n.get(prop("type"));
        if s.get(prop("type")) == Some("single")
            && t != Some("single")
            && facing_of(s) == facing_of(n)
            && chest_partner(n) == Some(opposite(dir))
        {
            let other = if t == Some("left") { "right" } else { "left" };
            return with(s, "type", other);
        }
        s
    } else if chest_partner(s) == Some(dir) {
        with(s, "type", "single")
    } else {
        s
    }
}

/// `ChorusPlantBlock.canPlaceAt` at `pos`.
fn chorus_can_stay<V: UpdateView>(v: &V, pos: [i32; 3]) -> bool {
    let below = v.state(step(pos, 0));
    let vertical = !v.state(step(pos, 1)).is_air() && !below.is_air();
    for d in 2..6 {
        let q = step(pos, d);
        if v.state(q).block() == Block::CHORUS_PLANT {
            if vertical {
                return false;
            }
            let b = v.state(step(q, 0)).block();
            if b == Block::CHORUS_PLANT || b == Block::END_STONE {
                return true;
            }
        }
    }
    let b = below.block();
    b == Block::CHORUS_PLANT || b == Block::END_STONE
}

/// The concrete a concrete powder hardens into.
fn concrete_of(b: Block) -> BlockState {
    let name = b.name().trim_end_matches("_powder");
    Block::from_name(name).map_or(BlockState::AIR, Block::default_state)
}

const fn bool_str(b: bool) -> &'static str {
    if b { "true" } else { "false" }
}

fn is_wall(b: Block) -> bool {
    kind(b) == Kind::Wall
}

/// `FenceGateBlock.canWallConnect`.
fn gate_connects(n: BlockState, side: Facing) -> bool {
    kind(n.block()) == Kind::Gate && facing_of(n).is_some_and(|f| axis(f) == axis(clockwise(side)))
}

/// `FenceBlock.canConnect`.
fn fence_connects(fence: Block, n: BlockState, solid: bool, side: Facing) -> bool {
    let b = n.block();
    let same_fence = kind(b) == Kind::Fence && wooden_fence(b) == wooden_fence(fence);
    (!cannot_connect(b) && solid) || same_fence || gate_connects(n, side)
}

/// `PaneBlock.connectsTo`.
fn pane_connects(n: BlockState, solid: bool) -> bool {
    let b = n.block();
    (!cannot_connect(b) && solid) || kind(b) == Kind::Pane || is_wall(b)
}

/// `WallBlock.shouldConnectTo`.
fn wall_connects(n: BlockState, solid: bool, side: Facing) -> bool {
    let b = n.block();
    is_wall(b) || (!cannot_connect(b) && solid) || kind(b) == Kind::Pane || gate_connects(n, side)
}

/// Wall side properties in vanilla's argument order (north, east, south, west).
const WALL_SIDES: [&str; 4] = ["north", "east", "south", "west"];

/// The tall side shapes' footprints (`[x0, z0, x1, z1]`, in sixteenths) in [`WALL_SIDES`]
/// order, and the tall post's.
const TALL_SIDES: [[f64; 4]; 4] = [
    [7.0, 0.0, 9.0, 9.0],
    [7.0, 7.0, 16.0, 9.0],
    [7.0, 7.0, 9.0, 16.0],
    [0.0, 7.0, 9.0, 9.0],
];
const TALL_POST: [f64; 4] = [7.0, 7.0, 9.0, 9.0];

fn sixteenths(r: [f64; 4]) -> [f64; 4] {
    r.map(|v| v / 16.0)
}

/// `WallBlock.method_24422`: the side heights from the connections `c` and the block above's
/// down face, then the post.
fn wall_state<V: UpdateView>(
    v: &V,
    s: BlockState,
    above_pos: [i32; 3],
    above: BlockState,
    c: [bool; 4],
) -> Option<BlockState> {
    let mut out = s;
    let mut tall = [false; 4];
    for k in 0..4 {
        let value = if c[k] {
            tall[k] = v.down_face_covers(above_pos, above, sixteenths(TALL_SIDES[k]))?;
            if tall[k] { "tall" } else { "low" }
        } else {
            "none"
        };
        out = with(out, WALL_SIDES[k], value);
    }
    let up = if is_wall(above.block()) && above.get(prop("up")) == Some("true") {
        true
    } else {
        let [n, e, so, w] = c.map(|x| !x);
        if (n && so && w && e) || n != so || w != e {
            true
        } else if (tall[0] && tall[2]) || (tall[1] && tall[3]) {
            false
        } else {
            wall_post_override(above.block())
                || v.down_face_covers(above_pos, above, sixteenths(TALL_POST))?
        }
    };
    Some(with(out, "up", bool_str(up)))
}

fn is_stairs(s: BlockState) -> bool {
    kind(s.block()) == Kind::Stairs
}

/// `StairsBlock.getStairShape`.
fn stair_shape<V: UpdateView>(v: &V, s: BlockState, pos: [i32; 3]) -> &'static str {
    let half = s.get(prop("half"));
    let Some(f) = facing_of(s) else {
        return "straight";
    };
    let different = |d: Facing| {
        let o = v.state(step(pos, d));
        !is_stairs(o) || facing_of(o) != Some(f) || o.get(prop("half")) != half
    };
    let front = v.state(step(pos, f));
    if is_stairs(front)
        && front.get(prop("half")) == half
        && let Some(d2) = facing_of(front)
        && axis(d2) != axis(f)
        && different(opposite(d2))
    {
        return if d2 == counter_clockwise(f) {
            "outer_left"
        } else {
            "outer_right"
        };
    }
    let back = v.state(step(pos, opposite(f)));
    if is_stairs(back)
        && back.get(prop("half")) == half
        && let Some(d3) = facing_of(back)
        && axis(d3) != axis(f)
        && different(d3)
    {
        return if d3 == counter_clockwise(f) {
            "inner_left"
        } else {
            "inner_right"
        };
    }
    "straight"
}

/// `getCoordIndex` of a block-local `coord` on `axis`: `-1` below the first boundary, the cell
/// count at or above the last (a simple shape rounds with `floor(coord * n)`). Kept apart from
/// the collision code's own lookup so the plain tick's code stays as it is.
fn cell_index(shape: &VoxelShape<'_>, axis: usize, coord: f64) -> isize {
    let p = shape.axes[axis];
    let n = p.cells();
    if shape
        .axes
        .iter()
        .all(|q| matches!(q, crate::voxel::Points::Fractional(_)))
    {
        let v = crate::math::floor(coord * n as f64);
        return (v as isize).clamp(-1, n as isize);
    }
    // The first boundary strictly above `coord`, minus one.
    (0..=n).find(|&k| coord < p.get(k)).unwrap_or(n + 1) as isize - 1
}

/// Whether the face layer of `shape` on `dir` (vanilla `getFace`: the cell layer at `1e-7` /
/// `0.9999999` along the axis) covers the rectangle `rect` (`[lo_b, lo_c, hi_b, hi_c]` on the
/// other two axes in ascending order; for Y that is `[x0, z0, x1, z1]`). `exact`: also nothing
/// filled outside it (`isShapeFullCube` of the face against the unit square).
pub(super) fn face_covers(
    shape: &VoxelShape<'_>,
    dir: Facing,
    rect: [f64; 4],
    exact: bool,
) -> bool {
    let a = [1usize, 2, 0][(dir >> 1) as usize];
    let (b, c) = match a {
        0 => (1, 2),
        1 => (0, 2),
        _ => (0, 1),
    };
    if shape.is_empty() {
        return false;
    }
    let layer = cell_index(shape, a, if dir & 1 == 1 { 0.999_999_9 } else { EPSILON });
    let pts = |k: usize| -> Vec<f64> {
        let p = shape.axes[k];
        (0..=p.cells()).map(|i| p.get(i)).collect()
    };
    let merged = |p: &[f64], lo: f64, hi: f64| -> Vec<f64> {
        let mut all: Vec<f64> = p.iter().copied().chain([lo, hi]).collect();
        all.sort_by(f64::total_cmp);
        let mut kept: Vec<f64> = Vec::with_capacity(all.len());
        for v in all {
            if kept.last().is_none_or(|&l| l < v - EPSILON) {
                kept.push(v);
            }
        }
        kept
    };
    // The shape cell holding `x`, if any.
    let cell = |p: &[f64], x: f64| -> Option<usize> {
        let k = p.iter().rposition(|&q| q <= x)?;
        (k + 1 < p.len()).then_some(k)
    };
    let (pb, pc) = (pts(b), pts(c));
    let (mb, mc) = (merged(&pb, rect[0], rect[2]), merged(&pc, rect[1], rect[3]));
    let n = [
        shape.axes[0].cells(),
        shape.axes[1].cells(),
        shape.axes[2].cells(),
    ];
    let in_layer = layer >= 0 && (layer as usize) < n[a];
    for u in mb.windows(2) {
        let inside_b = u[0] >= rect[0] - EPSILON && u[1] <= rect[2] + EPSILON;
        let jb = cell(&pb, f64::midpoint(u[0], u[1]));
        for w in mc.windows(2) {
            let inside = inside_b && w[0] >= rect[1] - EPSILON && w[1] <= rect[3] + EPSILON;
            let jc = cell(&pc, f64::midpoint(w[0], w[1]));
            let filled = in_layer
                && match (jb, jc) {
                    (Some(jb), Some(jc)) => {
                        let mut q = [0isize; 3];
                        q[a] = layer;
                        q[b] = jb as isize;
                        q[c] = jc as isize;
                        shape.filled(q[0], q[1], q[2])
                    }
                    _ => false,
                };
            if inside != filled && (inside || exact) {
                return false;
            }
        }
    }
    true
}

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

    /// The shape-update classification and the tags / kinds the rules read equal the oracle's
    /// dump (`piston_facts.jsonl.gz`).
    #[test]
    fn kinds_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 b = Block::from_id(v["block"].as_u64().unwrap() as u16).unwrap();
            let class = v["shape_update"].as_str().unwrap();
            let want = match class {
                "FenceBlock" => Kind::Fence,
                "PaneBlock" => Kind::Pane,
                "WallBlock" => Kind::Wall,
                "StairsBlock" => Kind::Stairs,
                "FenceGateBlock" => Kind::Gate,
                "SnowyBlock" => Kind::Snowy,
                "CarpetBlock" => Kind::Carpet,
                "CoralParentBlock" => Kind::DeadCoral,
                "DeadCoralWallFanBlock" => Kind::DeadWallFan,
                "ChestBlock" => Kind::Chest,
                "MushroomBlock" => Kind::Mushroom,
                "AttachedStemBlock" => Kind::AttachedStem,
                "CampfireBlock" => Kind::Campfire,
                "ChorusPlantBlock" => Kind::ChorusPlant,
                "ConcretePowderBlock" => Kind::ConcretePowder,
                "AbstractPlantBlock"
                | "AbstractPlantStemBlock"
                | "BambooBlock"
                | "BambooSaplingBlock"
                | "BellBlock"
                | "BubbleColumnBlock"
                | "FireBlock"
                | "NoteBlock"
                | "RedstoneWireBlock"
                | "TripwireBlock"
                | "TripwireHookBlock"
                | "VineBlock" => Kind::Other,
                // Read on the 1.16.5 classes: the state stays, becomes air (dropped on the
                // client) or only ticks are scheduled.
                "AbstractBlock"
                | "AbstractPressurePlateBlock"
                | "BannerBlock"
                // A door or bed takes properties only from its other half, which a piston
                // never writes; otherwise it stays or turns into air (dropped on the client).
                | "BedBlock"
                | "DoorBlock"
                | "BeehiveBlock"
                | "CactusBlock"
                | "CakeBlock"
                | "ChainBlock"
                | "ChorusFlowerBlock"
                | "CocoaBlock"
                | "ConduitBlock"
                | "CoralBlock"
                | "CoralBlockBlock"
                | "CoralFanBlock"
                | "CoralWallFanBlock"
                | "EnderChestBlock"
                | "FallingBlock"
                | "FarmlandBlock"
                | "FlowerPotBlock"
                | "FluidBlock"
                | "GrassPathBlock"
                | "LadderBlock"
                | "LanternBlock"
                | "LeavesBlock"
                | "MagmaBlock"
                | "NetherPortalBlock"
                | "ObserverBlock"
                | "PistonHeadBlock"
                | "PlantBlock"
                | "RepeaterBlock"
                | "ScaffoldingBlock"
                | "SeaPickleBlock"
                | "SeagrassBlock"
                | "SignBlock"
                | "SlabBlock"
                | "SnowBlock"
                | "SoulFireBlock"
                | "SoulSandBlock"
                | "SugarCaneBlock"
                | "TallPlantBlock"
                | "TorchBlock"
                | "TrapdoorBlock"
                | "WallBannerBlock"
                | "WallMountedBlock"
                | "WallRedstoneTorchBlock"
                | "WallSignBlock"
                | "WallTorchBlock" => Kind::Inert,
                other => panic!("{other}: read its getStateForNeighborUpdate and classify it"),
            };
            assert_eq!(kind(b), want, "{} ({class})", b.name());
            let flag = |k: &str| v[k].as_bool().unwrap();
            assert_eq!(is_wall(b), flag("walls"), "walls {}", b.name());
            assert_eq!(is_wall(b), flag("wall_block"), "wall {}", b.name());
            assert_eq!(
                kind(b) == Kind::Fence,
                flag("fences"),
                "fences {}",
                b.name()
            );
            assert_eq!(
                kind(b) == Kind::Fence && wooden_fence(b),
                flag("wooden_fences"),
                "wooden {}",
                b.name()
            );
            assert_eq!(kind(b) == Kind::Pane, flag("pane"), "pane {}", b.name());
            assert_eq!(
                kind(b) == Kind::Gate,
                flag("fence_gate"),
                "gate {}",
                b.name()
            );
            assert_eq!(
                is_stairs(b.default_state()),
                flag("stairs_block"),
                "{}",
                b.name()
            );
            assert_eq!(cannot_connect(b), flag("cannot_connect"), "{}", b.name());
            assert_eq!(
                wall_post_override(b),
                flag("wall_post_override"),
                "post override {}",
                b.name()
            );
            assert_eq!(
                b.default_state().has_dynamic_bounds(),
                flag("dynamic_bounds"),
                "dynamic {}",
                b.name()
            );
            n += 1;
        }
        assert!(n > 700);
    }
}