ghast-physics 0.5.5

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
//! Item-steered mounts (`ItemSteerable`): pigs and striders, as the 26.x client ticks them.
//!
//! A saddled pig follows a rider holding a carrot on a stick, a saddled strider one holding a
//! warped fungus on a stick, in either hand (`getControllingPassenger`, `Player.isHolding`). The
//! controlled mount always walks forward (`getRiddenInput` is `(0, 0, 1)`), turned to the rider's
//! yaw and half its pitch, at its ridden speed: the movement speed attribute times 0.225 (pig) or
//! 0.55 (strider; 0.35 while it is cold), times the boost factor. A boost starts when the server
//! sends the mount's boost time (`ItemBasedSteering.onSynced`, after the rider used the stick) and
//! lasts that many ticks, its factor `1 + 1.15 sin(pi t / total)`.
//!
//! A strider stands on lava sources (`canStandOnFluid`: the lava block's collision shape is its
//! bottom half while the strider's feet are above it and no lava is above), never travels as in a
//! fluid while its block holds lava, floats up in lava (`floatStrider`), takes no fall distance in
//! lava, is cold out of lava (`setSuffocating`: a -34 % speed modifier, which the client computes
//! itself each tick) and moves its rider up and down with its walk animation.

use super::super::attr::ModifierId;
use super::super::collide::{MountExt, World};
use super::super::fluid;
use super::super::math::{V3, floor};
use super::super::player::{Ctx, PlayerState};
use super::super::rules::Rules;
use super::super::rules::shared::{VoxelClass, VoxelShapeRef};
use super::MountKind;
use crate::world::{BlockView, TickCache};

/// `ItemBasedSteering` and the strider's own client state.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct SteerState {
    /// The rider holds a carrot on a stick / a warped fungus on a stick (either hand).
    pub(super) carrot: bool,
    pub(super) fungus: bool,
    pub(super) boosting: bool,
    pub(super) boost_time: i32,
    /// The boost-time entity data (`DATA_BOOST_TIME`).
    pub(super) boost_total: i32,
    /// `DATA_SUFFOCATING` (strider), as the client sets it each tick.
    pub(super) suffocating: bool,
    /// `walkAnimation` speed and position (strider: it moves the rider).
    pub(super) walk_speed: f32,
    pub(super) walk_pos: f32,
}

/// `Strider.SUFFOCATING_MODIFIER` amount (`ADD_MULTIPLIED_BASE`).
const SUFFOCATING_AMOUNT: f64 = -0.34f32 as f64;

fn suffocating_id() -> ModifierId {
    ModifierId::new("minecraft:suffocating")
}

impl SteerState {
    /// `ItemBasedSteering.onSynced`: the server's boost time arrived.
    pub(super) fn boost(&mut self, total: i32) {
        self.boost_total = total;
        self.boosting = true;
        self.boost_time = 0;
    }

    /// `tickBoost`.
    fn tick_boost(&mut self) {
        if self.boosting {
            let t = self.boost_time;
            self.boost_time += 1;
            if t > self.boost_total {
                self.boosting = false;
            }
        }
    }

    /// `boostFactor`.
    fn boost_factor(&self) -> f32 {
        if self.boosting {
            let a = self.boost_time as f32 / self.boost_total as f32 * core::f32::consts::PI;
            1.0 + 1.15 * super::super::math::sin(f64::from(a))
        } else {
            1.0
        }
    }

    /// The rider holds the stick of this kind.
    pub(super) fn holds(&self, kind: MountKind) -> bool {
        match kind {
            MountKind::Pig => self.carrot,
            MountKind::Strider => self.fungus,
            _ => false,
        }
    }
}

type MCtx<'a, 'b, 'c, R, W> = Ctx<'a, 'b, R, TickCache<'c, W>, MountExt<'c>>;

/// `Strider.tick`'s first part (before the living tick): cold out of lava and lava blocks
/// (`setSuffocating`: the entity data and the speed modifier).
pub(super) fn strider_cold<R: Rules, W: BlockView<State = R::State>>(
    t: &MCtx<'_, '_, '_, R, W>,
    st: &mut SteerState,
    attrs: &mut super::super::player::Attributes,
) {
    let p = &*t.p;
    let lava_block = |pos: [i32; 3]| fluid::kind(t.w.fluid(pos[0], pos[1], pos[2])) == 2;
    let inside = [floor(p.pos[0]), floor(p.pos[1]), floor(p.pos[2])];
    let warm = lava_block(inside) || lava_block(t.on_pos(0.2)) || p.lava_height > 0.0;
    let cold = !warm;
    st.suffocating = cold;
    let ms = &mut attrs.movement_speed;
    if cold {
        if !ms.contains(suffocating_id()) {
            ms.add(suffocating_id(), SUFFOCATING_AMOUNT, 1);
        }
    } else {
        ms.remove(suffocating_id());
    }
}

/// `travelRidden` of a pig or strider: input `(0, 0, 1)`, `tickRidden` (the rider's yaw and half
/// its pitch, the boost tick), then `travel` at the ridden speed. Returns that speed
/// (`LivingEntity.speed`).
pub(super) fn travel_ridden<R: Rules, W: BlockView<State = R::State>>(
    t: &mut MCtx<'_, '_, '_, R, W>,
    st: &mut SteerState,
    kind: MountKind,
    rider: &PlayerState,
) -> f32 {
    let input = V3::new(0.0, 0.0, 1.0);
    t.p.yaw = rider.yaw % 360.0;
    t.p.pitch = ((rider.pitch * 0.5) % 360.0 % 360.0).clamp(-90.0, 90.0);
    st.tick_boost();
    let attr = t.p.attributes.movement_speed.value();
    let speed = match kind {
        MountKind::Strider => {
            let f = if st.suffocating { 0.35f32 } else { 0.55f32 };
            (attr * f64::from(f) * f64::from(st.boost_factor())) as f32
        }
        _ => (attr * 0.225 * f64::from(st.boost_factor())) as f32,
    };
    // `travel` reads `getSpeed()`: the movement speed for this travel is the ridden speed.
    let saved = t.p.attributes.movement_speed;
    // (Unclamped: a boost factor below zero, after a boost time shorter than the boost, makes
    // it negative.)
    t.p.attributes.movement_speed =
        super::super::attr::Attribute::new(f64::from(speed), f64::MIN, f64::MAX);
    t.travel(input);
    t.p.attributes.movement_speed = saved;
    speed
}

/// `LivingEntity.calculateEntityAnimation(false)` -> `updateWalkAnimation` (client, not a
/// passenger): the horizontal distance moved this tick.
pub(super) fn walk_animation(st: &mut SteerState, pos: [f64; 3], old: V3) {
    let (dx, dz) = (pos[0] - old.x, pos[2] - old.z);
    let distance = (dx * dx + 0.0 * 0.0 + dz * dz).sqrt() as f32;
    let target = (distance * 4.0).min(1.0);
    st.walk_speed += (target - st.walk_speed) * 0.4;
    st.walk_pos += st.walk_speed;
}

/// `Strider.floatStrider` (after its living tick): in lava, it stands on the surface when its
/// feet are above the lava block's half and no lava is above, else it floats up.
pub(super) fn float_strider<R: Rules, W: BlockView<State = R::State>>(
    t: &mut MCtx<'_, '_, '_, R, W>,
) {
    if !t.p.in_lava() {
        return;
    }
    let p = &*t.p;
    let b = [floor(p.pos[0]), floor(p.pos[1]), floor(p.pos[2])];
    let above = p.pos[1] > f64::from(b[1]) + 0.5 - f64::from(1.0e-5f32);
    if above && fluid::kind(t.w.fluid(b[0], b[1] + 1, b[2])) != 2 {
        t.set_on_ground(true, None);
    } else {
        let v = V3::of(t.p.vel).scale(0.5).add(V3::new(0.0, 0.05, 0.0));
        t.p.vel = v.arr();
    }
}

/// The strider's passenger attachment on the client: up and down with its walk animation.
pub(super) fn strider_seat_offset(st: &SteerState) -> f64 {
    let speed = st.walk_speed.min(0.25);
    let offset = 0.12f32 * super::super::math::cos(f64::from(st.walk_pos * 1.5)) * 2.0 * speed;
    f64::from(offset * 1.0)
}

/// Whether the lava block at `(x, y, z)` (fluid byte `fl`) is solid for a strider whose feet are
/// at `feet_y` (`LiquidBlock.getCollisionShape` with `canStandOnFluid`): a source block
/// (`LEVEL` 0) with the feet above its half and no lava above.
#[inline]
pub(crate) fn stands_on_lava<
    R: Rules,
    W: BlockView<State = R::State>,
    E: super::super::collide::Extra,
>(
    w: &World<'_, R, W, E>,
    fl: u8,
    x: i32,
    y: i32,
    z: i32,
    feet_y: f64,
) -> bool {
    fluid::kind(fl) == 2
        && fluid::amount(fl) == 8
        && fl & 0x10 == 0
        && feet_y > f64::from(y) + 0.5 - f64::from(1.0e-5f32)
        && fluid::kind(w.fluid(x, y + 1, z)) != 2
}

/// `LivingEntity.getLiquidCollisionShape` of a strider: `Block.column(16, 0, 8)`.
pub(crate) static LIQUID_STABLE: VoxelShapeRef = VoxelShapeRef {
    class: VoxelClass::Simple,
    sizes: [1, 2, 1],
    xs: &[0.0, 1.0],
    ys: &[0.0, 0.5, 1.0],
    zs: &[0.0, 1.0],
    cells: &[1],
    empty: false,
    boxes: &[crate::math::Aabb {
        min_x: 0.0,
        min_y: 0.0,
        min_z: 0.0,
        max_x: 1.0,
        max_y: 0.5,
        max_z: 1.0,
    }],
};

#[cfg(test)]
mod tests {
    /// The strider's liquid shape is the bottom slab's shape (`Block.column(16, 0, 8)`).
    #[test]
    fn liquid_stable_is_the_bottom_half() {
        let slab =
            super::super::super::rules::shared::BlockState::parse("smooth_stone_slab[type=bottom]")
                .unwrap();
        assert_eq!(slab.voxel_shape(), &super::LIQUID_STABLE);
    }
}