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
//! Pistons on the modern client (26.1 – 26.3): the blocks a piston moves, their collision shapes
//! while they travel, and how they move the player.
//!
//! The client runs the piston itself on a block-event packet (`PistonBaseBlock.triggerEvent` of
//! the block at the position; types 0 extend, 1 retract, 2 the server's fast retract that pulls
//! nothing): the block choice of `PistonStructureResolver` (slime and honey are sticky, but not to
//! each other; at most 12 blocks), the moved blocks become moving-piston blocks with a
//! [`v26_1::MovingBlock`] (vanilla's `PistonMovingBlockEntity`), ticked after every entity
//! (`Level.tickBlockEntities` follows `tickEntities`). Every tick a block advances by 0.5 and
//! moves each entity its shape sweeps by the overlap (plus 0.01, at most the step) with the piston
//! move type: at most 0.51 per axis per game tick, no stuck multiplier, no edge back-off, the block
//! effects of that move at once; a slime block also sets the velocity, a honey block moved
//! sideways drags what stands on it, a retracting head pulls back what it overlapped. A finished
//! block stays a moving block for 5 more client ticks before it is placed. While it moves its
//! collision shape is the moved shape offset by the progress, re-simplified like vanilla's shape
//! join, and the entity a piston pushes ignores blocks moving its way.
//!
//! The client's shape updates of these writes (`updateNeighbourShapes` through the level's
//! neighbour updater) are run for the blocks whose `updateShape` leaves the state as it is;
//! blocks the model does not cover are reported by `Pistons::take_unmodelled`.
//!
//! One module per rule set ([`v26_1`], [`v26_2`], `v26_3`); world changes are returned as `Edits` (apply
//! them in order).

/// A direction id (`Direction.get3DDataValue`): 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
}

/// Axis of a direction: 0 y, 1 z, 2 x (pairs of direction ids).
#[inline]
const fn axis(f: Facing) -> u8 {
    f >> 1
}

/// The coordinate index (0 x, 1 y, 2 z) of a direction's axis.
#[inline]
const fn axis_index(f: Facing) -> usize {
    [1, 2, 0][(f >> 1) as usize]
}

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

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

/// `BlockBehaviour.UPDATE_SHAPE_ORDER`: west, east, north, south, down, up.
const UPDATE_SHAPE_ORDER: [Facing; 6] = [4, 5, 2, 3, 0, 1];

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

use crate::math::{Aabb, sorted_box};

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

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

/// `AABB.minmax`.
fn union(a: &Aabb, b: &Aabb) -> Aabb {
    sorted_box(
        a.min_x.min(b.min_x),
        a.min_y.min(b.min_y),
        a.min_z.min(b.min_z),
        a.max_x.max(b.max_x),
        a.max_y.max(b.max_y),
        a.max_z.max(b.max_z),
    )
}

/// `AABB.intersect`.
fn intersect(a: &Aabb, b: &Aabb) -> Aabb {
    sorted_box(
        a.min_x.max(b.min_x),
        a.min_y.max(b.min_y),
        a.min_z.max(b.min_z),
        a.max_x.min(b.max_x),
        a.max_y.min(b.max_y),
        a.max_z.min(b.max_z),
    )
}

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

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

/// The player's place among the others (`Pistons::tick_after_entities_among`): its entity
/// section is where its position is (the client files an entity in the section of its block
/// position as it moves).
///
/// `true` when a query over `q` (`Level.getEntities`: the sections of `q` grown by 2
/// horizontally and 4 downwards) meets an entity at `pos`.
#[inline]
fn search_finds(pos: [f64; 3], q: &Aabb) -> bool {
    super::section_query_reaches(q, pos)
}

/// 26.1.
#[cfg(feature = "v26_1")]
pub mod v26_1 {
    use super::super::V26_1 as R;
    use ghast_data::v26_1 as ver;
    static FACTS: &[u8] = &super::super::piston_facts::FACTS_26_1;
    static UPDATE: &[u8] = &super::super::piston_facts::UPDATE_26_1;
    static TAGS: &[u8] = &super::super::piston_facts::TAGS_26_1;
    static ENTITIES: &[(&str, f32, u8)] = &super::super::piston_facts::ENTITIES_26_1;
    #[cfg(test)]
    const GOLDEN: &str = "26.1";
    #[cfg(test)]
    const PISTON_CODES: [u8; 5] = [0, 1, 2, 3, 4];
    include!("piston_body.rs");
}

/// 26.2 (the 26.1 rules; see the module docs of [`super::V26_2`]).
#[cfg(feature = "v26_2")]
pub mod v26_2 {
    use super::super::V26_2 as R;
    use ghast_data::v26_2 as ver;
    static FACTS: &[u8] = &super::super::piston_facts::FACTS_26_2;
    static UPDATE: &[u8] = &super::super::piston_facts::UPDATE_26_2;
    static TAGS: &[u8] = &super::super::piston_facts::TAGS_26_2;
    static ENTITIES: &[(&str, f32, u8)] = &super::super::piston_facts::ENTITIES_26_2;
    #[cfg(test)]
    const GOLDEN: &str = "26.2";
    #[cfg(test)]
    const PISTON_CODES: [u8; 5] = [0, 1, 2, 3, 4];
    include!("piston_body.rs");
}

/// 26.3 (the 26.1 piston rules over the 26.3 tables; see [`super::V26_3`]).
#[cfg(feature = "v26_3")]
pub mod v26_3 {
    use super::super::V26_3 as R;
    use ghast_data::v26_3 as ver;
    static FACTS: &[u8] = &super::super::piston_facts::FACTS_26_3;
    static UPDATE: &[u8] = &super::super::piston_facts::UPDATE_26_3;
    static TAGS: &[u8] = &super::super::piston_facts::TAGS_26_3;
    static ENTITIES: &[(&str, f32, u8)] = &super::super::piston_facts::ENTITIES_26_3;
    #[cfg(test)]
    const GOLDEN: &str = "26.3";
    /// The dump's push reaction (26.3 enum order) in the tables' order.
    #[cfg(test)]
    const PISTON_CODES: [u8; 5] = [0, 4, 1, 2, 3];
    include!("piston_body.rs");
}

/// `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)`).
fn cell_index(shape: &crate::voxel::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);
    }
    (0..=n).find(|&k| coord < p.get(k)).unwrap_or(n + 1) as isize - 1
}

/// Whether the face layer of `shape` on `dir` (`VoxelShape.getFaceShape`: 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.
fn face_covers(
    shape: &crate::voxel::VoxelShape<'_>,
    dir: Facing,
    rect: [f64; 4],
    exact: bool,
) -> bool {
    use crate::voxel::EPSILON;
    let a = axis_index(dir);
    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
    };
    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
}

/// A shape of the block tables as the face tests read it.
fn table_view(
    r: &'static super::rules::shared::VoxelShapeRef,
) -> crate::voxel::VoxelShape<'static> {
    super::collide::voxel(r, None)
}

/// A moving block's part as the face tests read it.
fn part_view(p: &super::moving::Part) -> crate::voxel::VoxelShape<'_> {
    match p {
        super::moving::Part::Cube => crate::voxel::VoxelShape::FULL_CUBE,
        super::moving::Part::Table(r) => table_view(r),
        super::moving::Part::Grid(g) => g.view(),
    }
}

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

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

/// `WallBlock.TEST_SHAPES_WALL` footprints (`[x0, z0, x1, z1]`, sixteenths) in north, east,
/// south, west order, and `TEST_SHAPE_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)
}

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