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
//! `Math.cos` / `Math.sin` as the HotSpot JVM on x86-64 computes them for the random angle of an
//! item a player drops from its hand: `nextFloat() * 2pi` as a float (every version: 1.8.9
//! `(float) Math.PI * 2.0F`, later `(float) (Math.PI * 2)`, the same float). `nextFloat()` is
//! `k / 2^24` for a 24-bit `k`, so the domain is 2^24 angles in `[0, 2pi)`.
//!
//! The JVM's intrinsics are not correctly rounded, and Rust's `f64::cos` / `f64::sin` come
//! from the platform's libm, so neither matches the other everywhere. Here the result is a
//! platform-independent reference (a double-double reduction by pi/2 and Taylor series, rounded
//! once; only `+`, `*` and the exactly rounded `mul_add`) corrected by an exception table taken
//! from the JVM itself (`jdk_drop_table.rs`, see the ignored test `jdk_drop_table`). Angles
//! outside the domain get the reference value.

#[allow(clippy::unreadable_literal)]
mod table {
    include!("jdk_drop_table.rs");
}

#[derive(Clone, Copy)]
struct Dd {
    hi: f64,
    lo: f64,
}

impl Dd {
    const fn of(x: f64) -> Dd {
        Dd { hi: x, lo: 0.0 }
    }

    fn neg(self) -> Dd {
        Dd {
            hi: -self.hi,
            lo: -self.lo,
        }
    }

    fn round(self) -> f64 {
        quick(self.hi, self.lo).hi
    }
}

fn two_sum(a: f64, b: f64) -> Dd {
    let s = a + b;
    let bb = s - a;
    Dd {
        hi: s,
        lo: (a - (s - bb)) + (b - bb),
    }
}

fn quick(a: f64, b: f64) -> Dd {
    let s = a + b;
    Dd {
        hi: s,
        lo: b - (s - a),
    }
}

fn add(a: Dd, b: Dd) -> Dd {
    let s = two_sum(a.hi, b.hi);
    let t = two_sum(a.lo, b.lo);
    let s2 = quick(s.hi, s.lo + t.hi);
    quick(s2.hi, s2.lo + t.lo)
}

fn mul(a: Dd, b: Dd) -> Dd {
    let p = a.hi * b.hi;
    let e = a.hi.mul_add(b.hi, -p);
    quick(p, e + (a.hi * b.lo + a.lo * b.hi))
}

fn div(a: Dd, d: f64) -> Dd {
    let q1 = a.hi / d;
    let p = q1 * d;
    let pe = q1.mul_add(d, -p);
    let r = ((a.hi - p) - pe) + a.lo;
    quick(q1, r / d)
}

/// pi/2 as three doubles (about 160 bits).
const PIO2: [f64; 3] = [
    f64::from_bits(0x3FF9_21FB_5444_2D18),
    f64::from_bits(0x3C91_A626_3314_5C07),
    f64::from_bits(0xB91F_1976_B7ED_8FBC),
];

/// `(sin, cos)` of `x` (finite, `|x| < 2^20`) as double-doubles.
fn sin_cos_dd(x: f64) -> (Dd, Dd) {
    // x - n * pi/2 with n the nearest multiple; n * PIO2[i] split exactly by fused products.
    let n = (x * (2.0 / core::f64::consts::PI)).round();
    let mut r = Dd::of(x);
    for p in PIO2 {
        let hi = n * p;
        let lo = n.mul_add(p, -hi);
        r = add(r, Dd { hi: -hi, lo: -lo });
    }
    let r2 = mul(r, r);
    // sin r = r - r^3/3! + ..., cos r = 1 - r^2/2! + ... (|r| <= pi/4: 30 terms are far below
    // the double-double's precision)
    let (mut ts, mut s) = (r, r);
    let (mut tc, mut c) = (Dd::of(1.0), Dd::of(1.0));
    for k in 1..30u32 {
        ts = div(mul(ts, r2), f64::from((2 * k) * (2 * k + 1))).neg();
        tc = div(mul(tc, r2), f64::from((2 * k - 1) * (2 * k))).neg();
        s = add(s, ts);
        c = add(c, tc);
    }
    match (n as i64).rem_euclid(4) {
        0 => (s, c),
        1 => (c, s.neg()),
        2 => (s.neg(), c.neg()),
        _ => (c.neg(), s),
    }
}

/// The reference `(sin, cos)` of `x`, each rounded once to a double.
pub(crate) fn sin_cos_reference(x: f64) -> (f64, f64) {
    let (s, c) = sin_cos_dd(x);
    (s.round(), c.round())
}

/// The table's correction of one function for drop index `k`: `+1`, `-1` (ulps) or 0.
fn correction(low: &[u16], buckets: &[u32], sign: &[u8], k: u32) -> i64 {
    let hi = (k >> 16) as usize;
    if hi + 1 >= buckets.len() {
        return 0;
    }
    let (start, end) = (buckets[hi] as usize, buckets[hi + 1] as usize);
    match low[start..end].binary_search(&((k & 0xFFFF) as u16)) {
        Ok(i) => {
            let j = start + i;
            if sign[j / 8] & (1 << (j % 8)) != 0 {
                1
            } else {
                -1
            }
        }
        Err(_) => 0,
    }
}

fn nudge(v: f64, d: i64) -> f64 {
    if d == 0 {
        v
    } else {
        f64::from_bits((v.to_bits() as i64 + d) as u64)
    }
}

/// `(Math.cos(a), Math.sin(a))` of HotSpot x86-64 for the drop angle `a = r * 2pi` of the
/// random float `r` (`nextFloat()`): exact for every `r = k / 2^24`; another `r` gets the
/// reference values.
pub(crate) fn drop_cos_sin(r: f32) -> (f64, f64) {
    let a = r * core::f32::consts::TAU;
    let (s, c) = sin_cos_reference(f64::from(a));
    let scaled = r * 16_777_216.0;
    if !(0.0..16_777_216.0).contains(&scaled) || scaled.fract() != 0.0 {
        return (c, s);
    }
    let k = scaled as u32;
    (
        nudge(
            c,
            correction(&table::COS_LOW, &table::COS_BUCKETS, &table::COS_SIGN, k),
        ),
        nudge(
            s,
            correction(&table::SIN_LOW, &table::SIN_BUCKETS, &table::SIN_SIGN, k),
        ),
    )
}

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

    #[test]
    fn reference_values() {
        assert_eq!(sin_cos_reference(0.0), (0.0, 1.0));
        let x = f64::from(1.5f32);
        let (s, c) = sin_cos_reference(x);
        assert!((s - x.sin()).abs() <= f64::EPSILON && (c - x.cos()).abs() <= f64::EPSILON);
        // The quadrants.
        for k in 0..64 {
            let x = f64::from(k as f32 * 0.1);
            let (s, c) = sin_cos_reference(x);
            assert!(
                (s - x.sin()).abs() < 1e-15 && (c - x.cos()).abs() < 1e-15,
                "{x}"
            );
        }
    }

    #[test]
    fn jvm_values() {
        // HotSpot x86-64 (`oracle/run.sh jdk-drop-trig`): k = 17621 is a cosine exception.
        let at = |k: u32| {
            let (c, s) = drop_cos_sin(k as f32 / 16_777_216.0);
            (c.to_bits(), s.to_bits())
        };
        assert_eq!(at(17_621), (0x3fef_ffd2_55de_af3c, 0x3f7b_07b3_4475_9ce6));
        assert_eq!(
            at(12_345_678),
            (0xbfb6_b6ef_923d_502f, 0xbfef_dfb0_71a4_54f0)
        );
        let (_, c) =
            sin_cos_reference(f64::from(17_621f32 / 16_777_216.0 * core::f32::consts::TAU));
        assert_eq!(c.to_bits().abs_diff(0x3fef_ffd2_55de_af3c), 1);
        // Off the nextFloat grid: the reference.
        let r = 0.123_456_79_f32;
        let (s, c) = sin_cos_reference(f64::from(r * core::f32::consts::TAU));
        assert_eq!(drop_cos_sin(r), (c, s));
    }

    #[test]
    fn tables_are_sorted() {
        for (low, buckets) in [
            (&table::COS_LOW[..], &table::COS_BUCKETS[..]),
            (&table::SIN_LOW[..], &table::SIN_BUCKETS[..]),
        ] {
            assert_eq!(*buckets.last().unwrap() as usize, low.len());
            for w in buckets.windows(2) {
                assert!(w[0] <= w[1]);
                let s = &low[w[0] as usize..w[1] as usize];
                assert!(s.windows(2).all(|p| p[0] < p[1]));
            }
        }
    }

    /// Regenerates `jdk_drop_table.rs`: `GHAST_JDK_DROP` names a file (or FIFO) holding, for
    /// every `k` from 0 to 2^24 - 1, the JVM's `Math.cos` then `Math.sin` of
    /// `(k / 2^24f) * (float) (2 pi)`, each 8 bytes little-endian (what `MC=26.1 oracle/run.sh
    /// jdk-drop-trig --out FILE` writes):
    ///
    /// ```sh
    /// mkfifo /tmp/drop.fifo
    /// MC=26.1 oracle/run.sh jdk-drop-trig --out /tmp/drop.fifo &
    /// GHAST_JDK_DROP=/tmp/drop.fifo cargo test --release -p ghast-physics --lib jdk_drop_table -- --ignored
    /// ```
    #[test]
    #[ignore = "needs the JVM stream (268 MB)"]
    fn jdk_drop_table() {
        use std::io::Read;
        let path = std::env::var("GHAST_JDK_DROP").expect("GHAST_JDK_DROP");
        let mut inp =
            std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(path).unwrap());
        let mut buf = [0u8; 16];
        let mut cos_ex: Vec<(u32, bool)> = Vec::new();
        let mut sin_ex: Vec<(u32, bool)> = Vec::new();
        for k in 0..(1u32 << 24) {
            inp.read_exact(&mut buf).expect("stream too short");
            let jvm_c = f64::from_le_bytes(buf[..8].try_into().unwrap());
            let jvm_s = f64::from_le_bytes(buf[8..].try_into().unwrap());
            let r = k as f32 / 16_777_216.0;
            let (s, c) = sin_cos_reference(f64::from(r * core::f32::consts::TAU));
            for (jvm, mine, ex) in [(jvm_c, c, &mut cos_ex), (jvm_s, s, &mut sin_ex)] {
                if jvm.to_bits() != mine.to_bits() {
                    let d = jvm.to_bits() as i64 - mine.to_bits() as i64;
                    assert!(d.abs() == 1, "k {k}: {d} ulps ({jvm} vs {mine})");
                    ex.push((k, d > 0));
                }
            }
        }
        eprintln!("exceptions: cos {}, sin {}", cos_ex.len(), sin_ex.len());
        let join = |v: Vec<String>| {
            v.chunks(16)
                .map(|c| format!("    {},\n", c.join(", ")))
                .collect::<String>()
        };
        let part = |name: &str, ex: &[(u32, bool)]| {
            let mut buckets = vec![0u32; 257];
            for &(k, _) in ex {
                buckets[(k >> 16) as usize + 1] += 1;
            }
            for i in 1..buckets.len() {
                buckets[i] += buckets[i - 1];
            }
            let mut sign = vec![0u8; ex.len().div_ceil(8)];
            for (j, &(_, plus)) in ex.iter().enumerate() {
                if plus {
                    sign[j / 8] |= 1 << (j % 8);
                }
            }
            format!(
                "/// `{name}`: start of each bucket of `k >> 16` in [`{name}_LOW`] (one more than \
                 buckets).\npub static {name}_BUCKETS: [u32; 257] = [\n{}];\n\n\
                 /// `{name}`: low 16 bits of the exceptional `k`, sorted within each bucket.\n\
                 pub static {name}_LOW: [u16; {}] = [\n{}];\n\n\
                 /// `{name}`: bit j set: exception j is one ulp above the reference, else below.\n\
                 pub static {name}_SIGN: [u8; {}] = [\n{}];\n",
                join(buckets.iter().map(ToString::to_string).collect()),
                ex.len(),
                join(ex.iter().map(|&(k, _)| (k & 0xFFFF).to_string()).collect()),
                sign.len(),
                join(sign.iter().map(ToString::to_string).collect()),
            )
        };
        let src = format!(
            "// @generated by the ignored test `jdk_drop_table` in `jdk_trig.rs` from the JVM's own \
             `Math.cos` / `Math.sin` (HotSpot x86-64);\n// do not edit.\n\n{}\n{}",
            part("COS", &cos_ex),
            part("SIN", &sin_ex)
        );
        let out = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/jdk_drop_table.rs");
        std::fs::write(out, src).unwrap();
    }
}