ghast-physics 0.5.4

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
//! The collision shapes of moving piston blocks in the modern core (version-independent part).
//!
//! `PistonMovingBlockEntity.getCollisionShape` returns `Shapes.or(base, moved)`: the shape of the
//! retracting base (empty for every other moving block) joined with the moved block's collision
//! shape offset by the progress. The join re-simplifies (`VoxelShape.optimize`): the boxes are
//! combined one by one into a new grid, every box adding its own boundaries (a box that fits a
//! power-of-two grid adds that whole grid, `Shapes.box` makes it a cube shape; any other box adds
//! its two ends). That grid can have boundaries inside a filled region, which stop an entity that
//! already overlaps the shape, so the exact grid matters for pushes.

use super::rules::shared::VoxelShapeRef;
use crate::math::Aabb;
use crate::voxel::{Points, VoxelShape};

const EPS: f64 = 1.0e-7;

/// `Shapes.findBits`: the power-of-two resolution (`0..=3`) both ends of an axis fit, if any.
fn bits(lo: f64, hi: f64) -> Option<u32> {
    if lo < -EPS || hi > 1.0 + EPS {
        return None;
    }
    (0..=3).find(|&i| {
        let k = f64::from(1u32 << i);
        let (d, e) = (lo * k, hi * k);
        (d - d.round()).abs() < EPS * k && (e - e.round()).abs() < EPS * k
    })
}

/// A re-simplified shape grid (explicit boundaries, filled cells in vanilla's bit order).
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Grid {
    pts: [Vec<f64>; 3],
    cells: Vec<u64>,
}

impl Grid {
    /// The view the collision code reads.
    pub(crate) fn view(&self) -> VoxelShape<'_> {
        VoxelShape {
            axes: [
                Points::Explicit(&self.pts[0]),
                Points::Explicit(&self.pts[1]),
                Points::Explicit(&self.pts[2]),
            ],
            cells: &self.cells,
        }
    }

    /// `getCoords(Y)`.
    pub(crate) fn ys(&self) -> &[f64] {
        &self.pts[1]
    }

    /// `true` when the grid is the full cube (`Shapes.block()`).
    fn is_full_cube(&self) -> bool {
        self.pts.iter().all(|p| p == &[0.0, 1.0]) && self.cells == [1]
    }
}

/// One shape of a moving block.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Part {
    /// `Shapes.block()` (vanilla's identity full cube).
    Cube,
    /// A fixed shape (the piston's own parts, from the oracle dump).
    Table(&'static VoxelShapeRef),
    /// A built grid.
    Grid(Grid),
}

/// `optimize()` of a shape whose `forAllBoxes` gives `boxes` (block-local): the join of
/// `Shapes.box(b)` over every box. `None`: empty.
pub(crate) fn union(boxes: impl Iterator<Item = Aabb>) -> Option<Part> {
    let lo = |b: &Aabb, a: usize| [b.min_x, b.min_y, b.min_z][a];
    let hi = |b: &Aabb, a: usize| [b.max_x, b.max_y, b.max_z][a];
    let mut pts: [Vec<f64>; 3] = Default::default();
    let mut used: Vec<Aabb> = Vec::new();
    for b in boxes {
        // `Shapes.box` of a box thinner than 1e-7 on some axis is empty.
        if (0..3).any(|a| hi(&b, a) - lo(&b, a) < EPS) {
            continue;
        }
        let r = [0, 1, 2].map(|a| bits(lo(&b, a), hi(&b, a)));
        match r {
            [Some(0), Some(0), Some(0)] => {
                for p in &mut pts {
                    p.extend([0.0, 1.0]);
                }
            }
            [Some(i), Some(j), Some(k)] => {
                for (a, n) in [i, j, k].into_iter().enumerate() {
                    let n = 1u32 << n;
                    pts[a].extend((0..=n).map(|q| f64::from(q) / f64::from(n)));
                }
            }
            _ => {
                for (a, p) in pts.iter_mut().enumerate() {
                    p.extend([lo(&b, a), hi(&b, a)]);
                }
            }
        }
        used.push(b);
    }
    if used.is_empty() {
        return None;
    }
    // The merge of ascending boundary lists (a value within 1e-7 of the last kept one collapses).
    for p in &mut pts {
        p.sort_by(f64::total_cmp);
        let mut kept: Vec<f64> = Vec::with_capacity(p.len());
        for &v in p.iter() {
            if kept.last().is_none_or(|&l| l < v - EPS) {
                kept.push(v);
            }
        }
        *p = kept;
    }
    let index =
        |a: usize, v: f64, p: &[Vec<f64>; 3]| p[a].iter().rposition(|&q| q <= v + EPS).unwrap_or(0);
    let n = [pts[0].len() - 1, pts[1].len() - 1, pts[2].len() - 1];
    let mut cells = vec![0u64; (n[0] * n[1] * n[2]).div_ceil(64)];
    for b in &used {
        let r: [(usize, usize); 3] =
            std::array::from_fn(|a| (index(a, lo(b, a), &pts), index(a, hi(b, a), &pts)));
        for x in r[0].0..r[0].1 {
            for y in r[1].0..r[1].1 {
                for z in r[2].0..r[2].1 {
                    let i = (x * n[1] + y) * n[2] + z;
                    cells[i / 64] |= 1 << (i % 64);
                }
            }
        }
    }
    let g = Grid { pts, cells };
    Some(if used.len() == 1 && g.is_full_cube() {
        Part::Cube
    } else {
        Part::Grid(g)
    })
}

/// The shapes of the moving blocks for one collision query (the moving blocks the asking entity
/// is pushed by in the pushing direction are left out by the caller).
#[derive(Clone, Debug, Default)]
pub(crate) struct MovingShapes {
    parts: Vec<([i32; 3], Part)>,
}

impl MovingShapes {
    /// No shapes.
    pub(crate) fn new() -> MovingShapes {
        MovingShapes { parts: Vec::new() }
    }

    /// Adds a shape at a block position.
    pub(crate) fn push(&mut self, pos: [i32; 3], part: Part) {
        self.parts.push((pos, part));
    }

    /// The shapes at a block position, in the order they were added.
    pub(crate) fn at(&self, pos: [i32; 3]) -> impl Iterator<Item = &Part> {
        self.parts
            .iter()
            .filter(move |(p, _)| *p == pos)
            .map(|(_, s)| s)
    }
}

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

    #[test]
    fn full_cube_union_is_the_identity_cube() {
        let p = union([Aabb::new(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)].into_iter());
        assert_eq!(p, Some(Part::Cube));
        let shifted = union([Aabb::new(0.5, 0.0, 0.0, 1.5, 1.0, 1.0)].into_iter());
        let Some(Part::Grid(g)) = shifted else {
            panic!("grid")
        };
        assert_eq!(g.pts[0], [0.5, 1.5]);
        assert_eq!(g.pts[1], [0.0, 1.0]);
    }
}