ghast-physics 0.5.3

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
//! Launch velocities of player-launched projectiles, cast fishing bobbers, aimed fireballs and
//! dropped items in 1.16.5, exactly as the server computes them (`ProjectileEntity.setProperties`,
//! the bobber's casting constructor, `ExplosiveProjectileEntity`'s aimed constructor,
//! `PlayerEntity.dropItem`), checked against the vanilla oracle
//! (`tests/golden/1.16.5/projectile_launch.jsonl.gz`).
//!
//! The server adds a random spread: per axis of the normalised direction a Gaussian term
//! `nextGaussian() * 0.0075 * uncertainty`, before the power scales it. A client cannot know the
//! server's random, so [`shoot`] with [`Noise::NONE`] is the expected launch; the spread's standard
//! deviation per axis is [`SPREAD`] `* uncertainty * power`. A thrown or shot projectile starts at
//! the shooter's `x, eye_y - 0.1, z` ([`launch_y`]), a dropped item at `eye_y - 0.3` ([`drop_y`]).

use super::fluid::V3;
use crate::math::{cos, sin, sqrt_f64_as_f32};
use crate::nonliving::{LegacyRandom, atan2, degrees};

/// The spread's standard deviation per unit of uncertainty (`0.0075F`).
pub const SPREAD: f64 = 0.0075f32 as f64;

/// How an item launches its projectile.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct LaunchSpec {
    /// Speed of the launch.
    pub power: f32,
    /// Added to the shooter's pitch for the vertical direction (potions and bottles are thrown
    /// 20 degrees higher).
    pub pitch_offset: f32,
    /// `divergence` (1 for players).
    pub uncertainty: f32,
}

impl LaunchSpec {
    /// A launch of `power` with the vertical direction `pitch_offset` degrees off the shooter's
    /// pitch and the given uncertainty.
    #[must_use]
    pub const fn new(power: f32, pitch_offset: f32, uncertainty: f32) -> LaunchSpec {
        LaunchSpec {
            power,
            pitch_offset,
            uncertainty,
        }
    }

    /// Snowballs, eggs and ender pearls (`1.5`).
    pub const THROWN: LaunchSpec = LaunchSpec::new(1.5, 0.0, 1.0);
    /// Splash and lingering potions (`0.5`, 20 degrees up).
    pub const POTION: LaunchSpec = LaunchSpec::new(0.5, -20.0, 1.0);
    /// Bottles o' enchanting (`0.7`, 20 degrees up).
    pub const EXPERIENCE_BOTTLE: LaunchSpec = LaunchSpec::new(0.7, -20.0, 1.0);
    /// Thrown tridents (`2.5`).
    pub const TRIDENT: LaunchSpec = LaunchSpec::new(2.5, 0.0, 1.0);

    /// A bow released after `ticks_held` ticks (power `3 * bow_power(ticks)`); `None` when the
    /// draw is too short to shoot (power below 0.1).
    #[must_use]
    pub fn bow(ticks_held: i32) -> Option<LaunchSpec> {
        let p = bow_power(ticks_held);
        if f64::from(p) < 0.1 {
            None
        } else {
            Some(LaunchSpec::new(p * 3.0, 0.0, 1.0))
        }
    }
}

/// `BowItem.getPullProgress(ticks)`: `(t^2 + 2t) / 3` with `t = ticks / 20`, at most 1.
#[must_use]
pub fn bow_power(ticks_held: i32) -> f32 {
    let t = ticks_held as f32 / 20.0;
    let p = (t * t + t * 2.0) / 3.0;
    if p > 1.0 { 1.0 } else { p }
}

/// The three random spread terms of a launch (`nextGaussian() * 0.0075F * uncertainty` for x, y,
/// z, in that order).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Noise(pub [f64; 3]);

impl Noise {
    /// No spread: the expected launch.
    pub const NONE: Noise = Noise([0.0; 3]);

    /// The spread a projectile whose entity random was created with `seed` draws (the server's
    /// projectile; for tests and replays with a known seed).
    #[must_use]
    pub fn from_seed(seed: i64, uncertainty: f32) -> Noise {
        let mut r = LegacyRandom::new(seed);
        let k = f64::from(0.0075f32);
        let u = f64::from(uncertainty);
        let x = r.next_gaussian() * k * u;
        let y = r.next_gaussian() * k * u;
        let z = r.next_gaussian() * k * u;
        Noise([x, y, z])
    }
}

/// A launched projectile's motion and rotation.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Launch {
    /// The projectile's motion after the launch.
    pub vel: [f64; 3],
    /// Its yaw (degrees, from the motion before the shooter's own motion is added).
    pub yaw: f32,
    /// Its pitch.
    pub pitch: f32,
}

const DEG_TO_RAD: f32 = (core::f64::consts::PI / 180.0) as f32;

/// `MathHelper.sqrt(squaredHorizontalLength(v))`.
fn horizontal(v: V3) -> f64 {
    f64::from(sqrt_f64_as_f32(v.x * v.x + v.z * v.z))
}

/// `ProjectileEntity.setProperties(shooter, pitch, yaw, pitch_offset, power, uncertainty)` with
/// the given spread: the direction from the rotation (sine table), normalised, plus the noise,
/// times the power, plus the shooter's motion (its vertical part only when it is not on the
/// ground).
#[must_use]
pub fn shoot(
    yaw: f32,
    pitch: f32,
    spec: &LaunchSpec,
    noise: Noise,
    shooter_motion: [f64; 3],
    shooter_on_ground: bool,
) -> Launch {
    let x = -sin(yaw * DEG_TO_RAD) * cos(pitch * DEG_TO_RAD);
    let y = -sin((pitch + spec.pitch_offset) * DEG_TO_RAD);
    let z = cos(yaw * DEG_TO_RAD) * cos(pitch * DEG_TO_RAD);
    let m = V3::new(f64::from(x), f64::from(y), f64::from(z))
        .normalize()
        .add(V3::new(noise.0[0], noise.0[1], noise.0[2]))
        .scale(f64::from(spec.power));
    let launch_yaw = degrees(atan2(m.x, m.z));
    let launch_pitch = degrees(atan2(m.y, horizontal(m)));
    let s = shooter_motion;
    let v = m.add(V3::new(
        s[0],
        if shooter_on_ground { 0.0 } else { s[1] },
        s[2],
    ));
    Launch {
        vel: [v.x, v.y, v.z],
        yaw: launch_yaw,
        pitch: launch_pitch,
    }
}

/// Where a thrown or shot projectile starts: 0.1 below the shooter's eyes.
#[must_use]
pub fn launch_y(eye_y: f64) -> f64 {
    eye_y - f64::from(0.1f32)
}

/// A cast fishing bobber: its start position and its launch, for a player at `pos` with
/// `eye_height` looking at `yaw`, `pitch`, and the bobber's three Gaussian draws (`[0.0; 3]` for
/// the expected cast; [`bobber_noise`] for a known seed).
#[must_use]
pub fn bobber_cast(
    yaw: f32,
    pitch: f32,
    pos: [f64; 3],
    eye_height: f32,
    gaussians: [f64; 3],
) -> ([f64; 3], Launch) {
    let h = cos(-yaw * DEG_TO_RAD - core::f32::consts::PI);
    let i = sin(-yaw * DEG_TO_RAD - core::f32::consts::PI);
    let j = -cos(-pitch * DEG_TO_RAD);
    let k = sin(-pitch * DEG_TO_RAD);
    let start = [
        pos[0] - f64::from(i) * 0.3,
        pos[1] + f64::from(eye_height),
        pos[2] - f64::from(h) * 0.3,
    ];
    let dir = V3::new(
        f64::from(-i),
        f64::from((-(k / j)).clamp(-5.0, 5.0)),
        f64::from(-h),
    );
    let m = dir.length();
    let f = |g: f64| 0.6 / m + 0.5 + g * 0.0045;
    let v = V3::new(
        dir.x * f(gaussians[0]),
        dir.y * f(gaussians[1]),
        dir.z * f(gaussians[2]),
    );
    let yaw = degrees(atan2(v.x, v.z));
    let pitch = degrees(atan2(v.y, horizontal(v)));
    (
        start,
        Launch {
            vel: [v.x, v.y, v.z],
            yaw,
            pitch,
        },
    )
}

/// The three Gaussian draws of a bobber whose entity random was created with `seed`.
#[must_use]
pub fn bobber_noise(seed: i64) -> [f64; 3] {
    let mut r = LegacyRandom::new(seed);
    [r.next_gaussian(), r.next_gaussian(), r.next_gaussian()]
}

/// The acceleration of a fireball or wither skull aimed along `dir` (the aimed constructor:
/// `dir / |dir| * 0.1`, the length a float square root; zero for a zero direction).
#[must_use]
pub fn aimed_power(dir: [f64; 3]) -> [f64; 3] {
    let d = f64::from(sqrt_f64_as_f32(
        dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2],
    ));
    if d == 0.0 {
        [0.0; 3]
    } else {
        [dir[0] / d * 0.1, dir[1] / d * 0.1, dir[2] / d * 0.1]
    }
}

/// The four random floats of a held-item drop, in draw order (angle, radius, then two for the
/// vertical term); all zero for the expected drop.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DropNoise(pub [f32; 4]);

impl DropNoise {
    /// No spread: the expected drop.
    pub const NONE: DropNoise = DropNoise([0.0; 4]);

    /// The draws of a player whose entity random was created with `seed`.
    #[must_use]
    pub fn from_seed(seed: i64) -> DropNoise {
        let mut r = LegacyRandom::new(seed);
        DropNoise([
            r.next_float(),
            r.next_float(),
            r.next_float(),
            r.next_float(),
        ])
    }
}

/// `PlayerEntity.dropItem(stack, false, _)`: the motion of an item the player drops from its hand
/// at rotation `yaw`, `pitch` (it starts at `x, eye_y - 0.3, z`, [`drop_y`]).
///
/// The random horizontal term reads `Math.cos` / `Math.sin` of the angle, which the JVM computes
/// with its own intrinsic; here they are Rust's `f64::cos` / `f64::sin`, which differ from it by
/// one unit in the last place for about 0.2 % of the angles (measured on x86-64 Linux), so a
/// replay with a known seed may be one unit off in x or z. [`DropNoise::NONE`], the expected
/// drop, is exact.
#[must_use]
pub fn drop_velocity(yaw: f32, pitch: f32, noise: DropNoise) -> [f64; 3] {
    let [r1, r2, r3, r4] = noise.0;
    let i = sin(pitch * DEG_TO_RAD);
    let j = cos(pitch * DEG_TO_RAD);
    let k = sin(yaw * DEG_TO_RAD);
    let l = cos(yaw * DEG_TO_RAD);
    let m = f64::from(r1 * core::f32::consts::TAU);
    let n = f64::from(0.02f32 * r2);
    [
        f64::from(-k * j * 0.3) + m.cos() * n,
        f64::from(-i * 0.3 + 0.1 + (r3 - r4) * 0.1),
        f64::from(l * j * 0.3) + m.sin() * n,
    ]
}

/// The motion of an item dropped in a random direction (`dropItem(stack, true, _)`: a death drop
/// or an inventory spill) for its two random floats.
#[must_use]
pub fn drop_velocity_random(noise: [f32; 2]) -> [f64; 3] {
    let f = noise[0] * 0.5;
    let g = noise[1] * core::f32::consts::TAU;
    [
        f64::from(-sin(g) * f),
        f64::from(0.2f32),
        f64::from(cos(g) * f),
    ]
}

/// Where a dropped item starts: below the eyes by 0.3 (`getEyeY() - 0.3F`).
#[must_use]
pub fn drop_y(eye_y: f64) -> f64 {
    eye_y - f64::from(0.3f32)
}