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
//! Camels and camel husks (`Camel`, an `AbstractHorse`), as the 26.x client ticks them: the horse
//! path with the camel's own rules.
//!
//! - **Sitting** (`LAST_POSE_CHANGE_TICK` entity data, negative while sitting, against the level's
//!   game time): a sitting camel or one changing pose (40 ticks sitting down, 52 standing up)
//!   refuses to move (`refuseToMove`): no rider input, its own rotation, no horizontal motion on
//!   the ground, no jump bar. The rider's forward key makes a sitting camel stand up on the client
//!   (`Camel.tickRidden` -> `standUp`); a sitting camel in water stands up at once. Sitting
//!   (`Pose.SITTING`) is a lower box (2.375 - 1.43 high).
//! - **Dash**: the released jump bar is a dash along the look (`executeRidersJump`: x 22.2222 of
//!   the bar x speed x the block's speed factor, up 1.4285 x the bar x the jump power), then 55
//!   ticks of cooldown (`dashCooldown`, also started by the server's `DASH` entity data) without a
//!   jump bar or a new dash.
//! - **Sprint**: the rider can sprint on it (`canSprint`): +0.1 speed while no dash cools down.
//! - **Seat**: half a block forward, at a height that follows the sitting animation
//!   (`getBodyAnchorAnimationYOffset`); no rearing offset.

use super::super::math::{self as m, DEG_TO_RAD, V3};
use super::super::player::{Dimensions, PlayerState};

/// `Camel.DASH_COOLDOWN_TICKS`.
pub(super) const DASH_COOLDOWN: i32 = 55;

/// The camel's own client state.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct CamelState {
    /// `dashCooldown`.
    pub(super) dash_cooldown: i32,
    /// `DASH` entity data.
    pub(super) dashing: bool,
    /// The entity's pose is `SITTING` (`DATA_POSE`; the box).
    pub(super) sitting_pose: bool,
    /// `LAST_POSE_CHANGE_TICK` (negative: sitting).
    pub(super) last_pose_tick: i64,
    /// The level's game time.
    pub(super) game_time: i64,
}

impl CamelState {
    /// `isCamelSitting`.
    pub(super) fn sitting(&self) -> bool {
        self.last_pose_tick < 0
    }

    /// `getPoseTime`.
    fn pose_time(&self) -> i64 {
        self.game_time
            .wrapping_sub(self.last_pose_tick.wrapping_abs())
    }

    /// `isInPoseTransition`.
    pub(super) fn in_transition(&self) -> bool {
        self.pose_time() < if self.sitting() { 40 } else { 52 }
    }

    /// `refuseToMove`.
    pub(super) fn refuse_to_move(&self) -> bool {
        self.sitting() || self.in_transition()
    }

    /// `setDashing` (a change, or any value from the server): `onSyncedDataUpdated` starts the
    /// cooldown when none runs (not in the entity's first tick).
    pub(super) fn set_dashing(&mut self, on: bool, from_server: bool, first_tick: bool) {
        let changed = self.dashing != on;
        self.dashing = on;
        if (changed || from_server) && !first_tick && self.dash_cooldown == 0 {
            self.dash_cooldown = DASH_COOLDOWN;
        }
    }

    /// `standUp` (sitting only): standing, the pose changed now.
    pub(super) fn stand_up(&mut self, e: &mut PlayerState) {
        if self.sitting() {
            self.set_pose(false, e);
            self.last_pose_tick = self.game_time;
        }
    }

    /// `standUpInstantly`: standing, the change long enough ago to be over.
    pub(super) fn stand_up_instantly(&mut self, e: &mut PlayerState) {
        self.set_pose(false, e);
        self.last_pose_tick = 0i64.max(self.game_time.wrapping_sub(52).wrapping_sub(1));
    }

    /// `setPose` -> `refreshDimensions` (the client: the new box at the same position).
    pub(super) fn set_pose(&mut self, sitting: bool, e: &mut PlayerState) {
        self.sitting_pose = sitting;
        e.dims = dimensions(sitting);
        let [x, y, z] = e.pos;
        e.set_pos(x, y, z);
    }
}

/// `Camel.getDefaultDimensions`: the type's box, or the sitting one.
pub(super) fn dimensions(sitting: bool) -> Dimensions {
    if sitting {
        Dimensions {
            width: 1.7,
            height: 2.375 - 1.43,
            eye_height: 0.845,
        }
    } else {
        Dimensions {
            width: 1.7,
            height: 2.375,
            eye_height: 2.275,
        }
    }
}

/// `Camel.getRiddenSpeed`: the movement speed, + 0.1 while the rider sprints and no dash cools
/// down.
pub(super) fn ridden_speed(c: &CamelState, attr: f64, rider_sprinting: bool) -> f32 {
    let bonus = if rider_sprinting && c.dash_cooldown == 0 {
        0.1
    } else {
        0.0
    };
    attr as f32 + bonus
}

/// `Entity.calculateViewVector(xRot, yRot)`.
fn view_vector(x_rot: f32, y_rot: f32) -> V3 {
    let rx = x_rot * DEG_TO_RAD;
    let ry = -y_rot * DEG_TO_RAD;
    let (yc, ys) = (m::cos(f64::from(ry)), m::sin(f64::from(ry)));
    let (xc, xs) = (m::cos(f64::from(rx)), m::sin(f64::from(rx)));
    V3::new(f64::from(ys * xc), f64::from(-xs), f64::from(yc * xc))
}

/// `Camel.executeRidersJump`'s push: along the look (flattened), the dash and the lift.
pub(super) fn dash_push(
    yaw: f32,
    pitch: f32,
    amount: f32,
    speed: f64,
    block_speed: f32,
    jump_power: f32,
) -> V3 {
    let l = view_vector(pitch, yaw);
    let flat = V3::new(l.x * 1.0, l.y * 0.0, l.z * 1.0).normalize();
    let s = f64::from(22.2222f32 * amount) * speed * f64::from(block_speed);
    flat.scale(s).add(V3::new(
        0.0,
        f64::from(1.4285f32 * amount) * f64::from(jump_power),
        0.0,
    ))
}

/// `Camel.getPassengerAttachmentPoint` of passenger `index` of `count`: the driver (index 0)
/// half a block forward, the one behind it 0.7 back (only with two or more passengers), at the
/// body anchor's height of the front or the back (the sitting animation differs), turned with
/// the camel.
pub(super) fn seat(c: &CamelState, dims: Dimensions, yaw: f32, index: u8, count: u8) -> V3 {
    let scale = 1.0f32;
    let driver = index == 0;
    // (float) of the anchor height; with two passengers the one behind sits 0.7 back (a player
    // is not an `Animal`: no extra 0.2).
    let height = f64::from(body_anchor(c, driver, dims, scale) as f32);
    let offset = if count > 1 && !driver { -0.7f32 } else { 0.5 };
    let a = -yaw * DEG_TO_RAD;
    let (cs, sn) = (
        f64::from(m::cos(f64::from(a))),
        f64::from(m::sin(f64::from(a))),
    );
    let v = V3::new(0.0, height, f64::from(offset * scale));
    V3::new(v.x * cs + v.z * sn, v.y, v.z * cs - v.x * sn)
}

/// `Mth.lerp(float, float, float)`.
fn lerp(t: f32, a: f32, b: f32) -> f32 {
    a + t * (b - a)
}

/// `Camel.getBodyAnchorAnimationYOffset(isFront, 0, dimensions, scale)`.
fn body_anchor(c: &CamelState, front: bool, dims: Dimensions, scale: f32) -> f64 {
    let mut base = f64::from(dims.height - 0.375 * scale);
    let shd = scale * 1.43;
    let drop = shd - scale * 0.2;
    let bottom = shd - drop;
    let transition = c.in_transition();
    let sitting = c.sitting();
    if transition {
        let duration = if sitting { 40 } else { 52 };
        let (half, flex) = if sitting {
            (28, if front { 0.5f32 } else { 0.1 })
        } else if front {
            (24, 0.6)
        } else {
            (32, 0.35)
        };
        // Mth.clamp((float) getPoseTime() + partialTicks, 0, duration)
        let t = c.pose_time() as f32 + 0.0;
        let t = if t < 0.0 { 0.0 } else { t.min(duration as f32) };
        let first = t < half as f32;
        let part = if first {
            t / half as f32
        } else {
            (t - half as f32) / (duration - half) as f32
        };
        let flex_point = shd - flex * drop;
        base += f64::from(if sitting {
            lerp(
                part,
                if first { shd } else { flex_point },
                if first { flex_point } else { bottom },
            )
        } else {
            lerp(
                part,
                if first {
                    bottom - shd
                } else {
                    bottom - flex_point
                },
                if first { bottom - flex_point } else { 0.0 },
            )
        });
    }
    if sitting && !transition {
        base += f64::from(bottom);
    }
    base
}

type MCtx<'a, 'b, 'c, R, W> = super::super::player::Ctx<
    'a,
    'b,
    R,
    crate::world::TickCache<'c, W>,
    super::super::collide::MountExt<'c>,
>;

/// `Camel.executeRidersJump`: the dash, then its cooldown and the `DASH` flag.
pub(super) fn dash<R: super::super::rules::Rules, W: crate::world::BlockView<State = R::State>>(
    t: &mut MCtx<'_, '_, '_, R, W>,
    c: &mut CamelState,
    amount: f32,
) {
    // getJumpPower(): no jump boost on a mount.
    let jump = t.p.attributes.jump_strength.value() as f32 * 1.0 * t.block_jump_factor();
    let push = dash_push(
        t.p.yaw,
        t.p.pitch,
        amount,
        t.p.movement_speed(),
        t.block_speed_factor(),
        jump,
    );
    t.p.vel = V3::of(t.p.vel).add(push).arr();
    c.dash_cooldown = DASH_COOLDOWN;
    c.set_dashing(true, false, t.p.first_tick);
}

/// `Camel.tick` after the living tick: the dash ends on the ground or in a liquid, the cooldown
/// counts down, a sitting camel in water stands up at once.
pub(super) fn after_tick(c: &mut CamelState, e: &mut PlayerState) {
    if c.dashing && c.dash_cooldown < 50 && (e.on_ground || e.touching_water || e.in_lava()) {
        c.set_dashing(false, false, e.first_tick);
    }
    if c.dash_cooldown > 0 {
        c.dash_cooldown -= 1;
    }
    if c.sitting() && e.touching_water {
        c.stand_up_instantly(e);
    }
}