From 558d140fca600a78cbde8cf9b960fe6c04676cc3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:05:34 +0200 Subject: [PATCH 01/18] Compute Math.sin/cos/pow/log10 as HotSpot does on the host architecture Rust's float functions use the platform libm, and vanilla's own Math results differ between x86-64 (Intel stubs, close to glibc) and AArch64 (fdlibm, with sin/cos evaluated using fused multiply-adds). jmath picks the same implementation HotSpot uses on the machine, so options, the world border's alpha and RandomPos match vanilla on an Apple silicon Mac as well as on Linux. The vanilla protocol client no longer records the game-time sync sent every 20 ticks: whether one arrives before the first chunk batch depends on when the client joined. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + crates/horizon-client/src/border_render.rs | 2 +- crates/horizon-client/src/mobs/goals.rs | 8 +- crates/horizon-client/src/options_file.rs | 4 +- crates/horizon-core/Cargo.toml | 3 + crates/horizon-core/src/jmath.rs | 611 ++++++++++++++++++ crates/horizon-core/src/lib.rs | 1 + .../parity/VanillaProtocolClient.java | 7 +- 8 files changed, 631 insertions(+), 8 deletions(-) create mode 100644 crates/horizon-core/src/jmath.rs diff --git a/Cargo.lock b/Cargo.lock index 5a8da580f..b1fabec8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -700,6 +700,9 @@ dependencies = [ [[package]] name = "horizon-core" version = "0.1.0" +dependencies = [ + "libm", +] [[package]] name = "horizon-protocol" diff --git a/crates/horizon-client/src/border_render.rs b/crates/horizon-client/src/border_render.rs index 422989920..ff3e7c8b3 100644 --- a/crates/horizon-client/src/border_render.rs +++ b/crates/horizon-client/src/border_render.rs @@ -78,7 +78,7 @@ pub fn extract( || z > max_z + render_distance; if !deep_inside && !far_outside { let alpha = 1.0 - border.distance(x, z) / render_distance; - state.alpha = jclamp(alpha.powf(4.0), 0.0, 1.0); + state.alpha = jclamp(horizon_core::jmath::pow(alpha, 4.0), 0.0, 1.0); state.tint = status_color(border.status()); } else { state.alpha = 0.0; diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 4dcd401c1..ec3463f96 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1,7 +1,7 @@ //! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags, //! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`. use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo}; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{geometry::Vec3, jmath, random::RandomSource}; use std::sync::Arc; pub const MOVE: u8 = 1; @@ -208,8 +208,8 @@ impl Mob { let yrad = center + f64::from(2.0 * self.random.next_float() - 1.0) * max_rad; let dist = (min + self.random.next_double().sqrt() * (max - min)) * f64::from(std::f32::consts::SQRT_2); - let xt = -dist * yrad.sin(); - let zt = dist * yrad.cos(); + let xt = -dist * jmath::sin(yrad); + let zt = dist * jmath::cos(yrad); if xt.abs() > max || zt.abs() > max { return None; } @@ -932,7 +932,7 @@ impl Goal for RandomLookAround { } fn start(&mut self, m: &mut Mob, _: &mut Cx) { let r = std::f64::consts::TAU * m.random.next_double(); - self.rel = [r.cos(), r.sin()]; + self.rel = [jmath::cos(r), jmath::sin(r)]; self.time = 20 + m.random.next_int_bound(20).unwrap_or(0); } fn every_tick(&self) -> bool { diff --git a/crates/horizon-client/src/options_file.rs b/crates/horizon-client/src/options_file.rs index fd606fd62..5c14450ec 100644 --- a/crates/horizon-client/src/options_file.rs +++ b/crates/horizon-client/src/options_file.rs @@ -298,7 +298,7 @@ fn double_range(v: f64, lo: f64, hi: f64) -> Option { (v.total_cmp(&lo).is_ge() && v.total_cmp(&hi).is_le() && !v.is_nan()).then_some(v) } fn log_mouse(value: i32) -> f64 { - 10f64.powf(f64::from(value) / 100.0) + horizon_core::jmath::pow(10.0, f64::from(value) / 100.0) } fn unit_alt(json: &Json) -> Option { codec_double(json) @@ -366,7 +366,7 @@ impl Spec { } (Spec::Fov, V::Int(x)) => (30..=110).contains(x).then(|| v.clone()), (Spec::WheelSensitivity, V::Double(x)) => { - let i = floor_int(x.log10() * 100.0); + let i = floor_int(horizon_core::jmath::log10(*x) * 100.0); (-200..=100).contains(&i).then(|| V::Double(log_mouse(i))) } (Spec::Unit, V::Double(x)) => (*x >= 0.0 && *x <= 1.0).then(|| v.clone()), diff --git a/crates/horizon-core/Cargo.toml b/crates/horizon-core/Cargo.toml index 655472a35..97c9356b8 100644 --- a/crates/horizon-core/Cargo.toml +++ b/crates/horizon-core/Cargo.toml @@ -10,6 +10,9 @@ description = "Horizon simulation foundations for the pinned vanilla Java Editio # Records the call sites of LegacyRandom draws (mob AI parity debugging). rng-trace = [] +[dependencies] +libm = "=0.2.16" + [[bin]] name = "horizon-parity" path = "src/bin/parity.rs" diff --git a/crates/horizon-core/src/jmath.rs b/crates/horizon-core/src/jmath.rs new file mode 100644 index 000000000..90bb9abfe --- /dev/null +++ b/crates/horizon-core/src/jmath.rs @@ -0,0 +1,611 @@ +//! `java.lang.Math` as HotSpot computes it on the machine Horizon runs on. +//! +//! Rust's float functions call the platform's libm, and those round +//! differently: glibc, Apple's libm and fdlibm disagree in the last bit for +//! a few percent of arguments. Vanilla's own results differ between machines +//! too, because HotSpot replaces some `Math` methods with intrinsics: +//! +//! - `atan2`, `atan`, `asin`, `acos` and `hypot` are `StrictMath`'s (fdlibm) +//! everywhere. +//! - On x86-64, `sin`, `cos`, `tan`, `exp`, `log`, `log10` and `pow` are +//! Intel's libm stubs, which round like glibc for nearly every argument; +//! there they use the platform libm, as before. +//! - On AArch64 only `sin` and `cos` are intrinsics: fdlibm's kernels +//! evaluated with fused multiply-adds (`macroAssembler_aarch64_trig.cpp`). +//! Everything else is `StrictMath`. +//! +//! So these functions return what vanilla returns on the same machine, on +//! Linux and on an Apple silicon Mac alike. + +/// `Math.sin`. +pub fn sin(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + aarch64::sin(x) + } else { + x.sin() + } +} + +/// `Math.cos`. +pub fn cos(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + aarch64::cos(x) + } else { + x.cos() + } +} + +/// `Math.tan`. +pub fn tan(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + libm::tan(x) + } else { + x.tan() + } +} + +/// `Math.exp`. +pub fn exp(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + libm::exp(x) + } else { + x.exp() + } +} + +/// `Math.log`. +pub fn log(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + fdlibm::log(x) + } else { + x.ln() + } +} + +/// `Math.log10`. +pub fn log10(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + fdlibm::log10(x) + } else { + x.log10() + } +} + +/// `Math.pow`. +pub fn pow(x: f64, y: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + libm::pow(x, y) + } else { + x.powf(y) + } +} + +/// `Math.cbrt`. +pub fn cbrt(x: f64) -> f64 { + if cfg!(target_arch = "aarch64") { + fdlibm::cbrt(x) + } else { + x.cbrt() + } +} + +/// `Math.atan2`. +pub fn atan2(y: f64, x: f64) -> f64 { + libm::atan2(y, x) +} + +/// `Math.atan`. +pub fn atan(x: f64) -> f64 { + libm::atan(x) +} + +/// `Math.asin`. +pub fn asin(x: f64) -> f64 { + libm::asin(x) +} + +/// `Math.acos`. +pub fn acos(x: f64) -> f64 { + libm::acos(x) +} + +/// `Math.hypot`. +pub fn hypot(x: f64, y: f64) -> f64 { + fdlibm::hypot(x, y) +} + +fn hi(x: f64) -> i32 { + (x.to_bits() >> 32) as i32 +} + +fn with_hi(x: f64, high: i32) -> f64 { + f64::from_bits((x.to_bits() & 0xffff_ffff) | (u64::from(high as u32) << 32)) +} + +/// `java.lang.FdLibm` ports (`StrictMath`) of what the `libm` crate computes +/// differently. +#[allow(clippy::excessive_precision)] // fdlibm's constants, verbatim. +pub mod fdlibm { + use super::{hi, with_hi}; + + const TWO54: f64 = 1.80143985094819840000e+16; + + /// `FdLibm.Log`. + pub fn log(mut x: f64) -> f64 { + const LN2_HI: f64 = 6.93147180369123816490e-01; + const LN2_LO: f64 = 1.90821492927058770002e-10; + const LG1: f64 = 6.666666666666735130e-01; + const LG2: f64 = 3.999999999940941908e-01; + const LG3: f64 = 2.857142874366239149e-01; + const LG4: f64 = 2.222219843214978396e-01; + const LG5: f64 = 1.818357216161805012e-01; + const LG6: f64 = 1.531383769920937332e-01; + const LG7: f64 = 1.479819860511658591e-01; + let mut hx = hi(x); + let lx = x.to_bits() as u32; + let mut k = 0; + if hx < 0x0010_0000 { + if ((hx & 0x7fff_ffff) as u32 | lx) == 0 { + return -TWO54 / 0.0; + } + if hx < 0 { + return (x - x) / 0.0; + } + k -= 54; + x *= TWO54; + hx = hi(x); + } + if hx >= 0x7ff0_0000 { + return x + x; + } + k += (hx >> 20) - 1023; + hx &= 0x000f_ffff; + let i = (hx + 0x9_5f64) & 0x10_0000; + x = with_hi(x, hx | (i ^ 0x3ff0_0000)); + k += i >> 20; + let f = x - 1.0; + if (0x000f_ffff & (2 + hx)) < 3 { + if f == 0.0 { + if k == 0 { + return 0.0; + } + let dk = f64::from(k); + return dk * LN2_HI + dk * LN2_LO; + } + let r = f * f * (0.5 - 0.33333333333333333 * f); + if k == 0 { + return f - r; + } + let dk = f64::from(k); + return dk * LN2_HI - ((r - dk * LN2_LO) - f); + } + let s = f / (2.0 + f); + let dk = f64::from(k); + let z = s * s; + let mut i = hx - 0x6_147a; + let w = z * z; + let j = 0x6b851 - hx; + let t1 = w * (LG2 + w * (LG4 + w * LG6)); + let t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7))); + i |= j; + let r = t2 + t1; + if i > 0 { + let hfsq = 0.5 * f * f; + if k == 0 { + f - (hfsq - s * (hfsq + r)) + } else { + dk * LN2_HI - ((hfsq - (s * (hfsq + r) + dk * LN2_LO)) - f) + } + } else if k == 0 { + f - s * (f - r) + } else { + dk * LN2_HI - ((s * (f - r) - dk * LN2_LO) - f) + } + } + + /// `FdLibm.Log10`. + pub fn log10(mut x: f64) -> f64 { + const IVLN10: f64 = 4.34294481903251816668e-01; + const LOG10_2HI: f64 = 3.01029995663611771306e-01; + const LOG10_2LO: f64 = 3.69423907715893078616e-13; + let mut hx = hi(x); + let lx = x.to_bits() as u32; + let mut k = 0; + if hx < 0x0010_0000 { + if ((hx & 0x7fff_ffff) as u32 | lx) == 0 { + return -TWO54 / 0.0; + } + if hx < 0 { + return (x - x) / 0.0; + } + k -= 54; + x *= TWO54; + hx = hi(x); + } + if hx >= 0x7ff0_0000 { + return x + x; + } + k += (hx >> 20) - 1023; + let i = ((k as u32) >> 31) as i32; + hx = (hx & 0x000f_ffff) | ((0x3ff - i) << 20); + let y = f64::from(k + i); + x = with_hi(x, hx); + let z = y * LOG10_2LO + IVLN10 * log(x); + z + y * LOG10_2HI + } + + /// `FdLibm.Cbrt`. + pub fn cbrt(mut x: f64) -> f64 { + const B1: i32 = 715094163; + const B2: i32 = 696219795; + const C: f64 = 5.42857142857142815906e-01; + const D: f64 = -7.05306122448979611050e-01; + const E: f64 = 1.41428571428571436819e+00; + const F: f64 = 1.60714285714285720630e+00; + const G: f64 = 3.57142857142857150787e-01; + if x == 0.0 || !x.is_finite() { + return x; + } + let sign = if x < 0.0 { -1.0 } else { 1.0 }; + x = x.abs(); + let mut t = 0.0f64; + if x < f64::MIN_POSITIVE { + t = 18014398509481984.0; // 2^54 + t *= x; + t = with_hi(t, hi(t) / 3 + B2); + } else { + t = with_hi(t, hi(x) / 3 + B1); + } + let mut r = t * t / x; + let mut s = C + r * t; + t *= G + F / (s + E + D / s); + t = f64::from_bits(t.to_bits() & 0xffff_ffff_0000_0000); + t = with_hi(t, hi(t) + 1); + s = t * t; + r = x / s; + let w = t + t; + r = (r - t) / (w + r); + t += t * r; + sign * t + } + + /// `FdLibm.Hypot`. + pub fn hypot(x: f64, y: f64) -> f64 { + let mut a = x.abs(); + let mut b = y.abs(); + if !a.is_finite() || !b.is_finite() { + if a == f64::INFINITY || b == f64::INFINITY { + return f64::INFINITY; + } + return a + b; + } + if b > a { + std::mem::swap(&mut a, &mut b); + } + let mut ha = hi(a); + let mut hb = hi(b); + if ha - hb > 0x3c0_0000 { + return a + b; + } + let mut k = 0; + if a > f64::from_bits(0x5f30_0000_ffff_ffff) { + ha -= 0x2580_0000; + hb -= 0x2580_0000; + a *= f64::from_bits(0x1a70_0000_0000_0000); // 2^-600 + b *= f64::from_bits(0x1a70_0000_0000_0000); + k += 600; + } + if b < f64::from_bits(0x20b0_0000_0000_0000) { + // 2^-500 + if b < f64::MIN_POSITIVE { + if b == 0.0 { + return a; + } + let t1 = f64::from_bits(0x7fd0_0000_0000_0000); // 2^1022 + b *= t1; + a *= t1; + k -= 1022; + } else { + ha += 0x2580_0000; + hb += 0x2580_0000; + a *= f64::from_bits(0x6570_0000_0000_0000); // 2^600 + b *= f64::from_bits(0x6570_0000_0000_0000); + k -= 600; + } + } + let mut w = a - b; + if w > b { + let t1 = with_hi(0.0, ha); + let t2 = a - t1; + w = (t1 * t1 - (b * (-b) - t2 * (a + t1))).sqrt(); + } else { + a += a; + let y1 = with_hi(0.0, hb); + let y2 = b - y1; + let t1 = with_hi(0.0, ha + 0x0010_0000); + let t2 = a - t1; + w = (t1 * y1 - (w * (-w) - (t1 * y2 + t2 * b))).sqrt(); + } + if k != 0 { + f64::from_bits(((1023 + k) as u64) << 52) * w + } else { + w + } + } +} + +/// HotSpot's AArch64 `Math.sin` / `Math.cos` stubs +/// (`MacroAssembler::generate_dsin_dcos`): fdlibm with fused multiply-adds. +/// Exposed on every architecture so they can be tested anywhere. +#[allow(clippy::excessive_precision, clippy::unreadable_literal)] // HotSpot's tables, verbatim. +pub mod aarch64 { + use super::hi; + + const S: [f64; 6] = [ + -1.66666666666666324348e-01, + 8.33333333332248946124e-03, + -1.98412698298579493134e-04, + 2.75573137070700676789e-06, + -2.50507602534068634195e-08, + 1.58969099521155010221e-10, + ]; + const C: [f64; 6] = [ + 4.16666666666666019037e-02, + -1.38888888888741095749e-03, + 2.48015872894767294178e-05, + -2.75573143513906633035e-07, + 2.08757232129817482790e-09, + -1.13596475577881948265e-11, + ]; + const INVPIO2: f64 = 6.36619772367581382433e-01; + const PIO2_1: f64 = 1.57079632673412561417e+00; + const PIO2_1T: f64 = 6.07710050650619224932e-11; + const PIO2_2: f64 = 6.07710050630396597660e-11; + const PIO2_2T: f64 = 2.02226624879595063154e-21; + const PIO2_3: f64 = 2.02226624871116645580e-21; + const PIO2_3T: f64 = 8.47842766036889956997e-32; + const NPIO2_HW: [i32; 32] = [ + 0x3FF921FB, 0x400921FB, 0x4012D97C, 0x401921FB, 0x401F6A7A, 0x4022D97C, 0x4025FDBB, + 0x402921FB, 0x402C463A, 0x402F6A7A, 0x4031475C, 0x4032D97C, 0x40346B9C, 0x4035FDBB, + 0x40378FDB, 0x403921FB, 0x403AB41B, 0x403C463A, 0x403DD85A, 0x403F6A7A, 0x40407E4C, + 0x4041475C, 0x4042106C, 0x4042D97C, 0x4043A28C, 0x40446B9C, 0x404534AC, 0x4045FDBB, + 0x4046C6CB, 0x40478FDB, 0x404858EB, 0x404921FB, + ]; + + /// `generate_kernel_sin`. + fn kernel_sin(x: f64, y: f64, iy: bool) -> f64 { + let z = x * x; + let v = z * x; + let mut r = z.mul_add(S[5], S[4]); + r = z.mul_add(r, S[3]); + r = z.mul_add(r, S[2]); + r = z.mul_add(r, S[1]); + if !iy { + v.mul_add(z.mul_add(r, S[0]), x) + } else { + let t = (-v).mul_add(r, 0.5 * y); + let t = (-z).mul_add(t, y); + x + v.mul_add(S[0], t) + } + } + + /// `generate_kernel_cos`. `ix` is the high word of the *original* + /// argument: the stub reuses the register, so a reduced argument always + /// takes the `qx = 0.28125` branch. + fn kernel_cos(x: f64, y: f64, ix: i32) -> f64 { + let z = x * x; + let mut r = z.mul_add(C[5], C[4]); + r = z.mul_add(r, C[3]); + let xy = x * y; + r = z.mul_add(r, C[2]); + r = z.mul_add(r, C[1]); + let zz = z * z; + r = z.mul_add(r, C[0]); + if ix <= 0x3FD33333 { + let v = (-zz).mul_add(r, xy); + 1.0 - 0.5f64.mul_add(z, v) + } else { + let qx = if ix > 0x3fe90000 { + 0.28125 + } else { + f64::from_bits(u64::from((ix - 0x0020_0000) as u32) << 32) + }; + let zr_xy = zz.mul_add(r, -xy); + let h = 0.5f64.mul_add(z, -qx); + let a = 1.0 - qx; + a - (h - zr_xy) + } + } + + /// `generate__ieee754_rem_pio2` for |x| <= 2^19·π/2; `None` beyond. + fn rem_pio2(x: f64, ix: i32) -> Option<(i32, f64, f64)> { + if ix < 0x4002d97c { + return Some(if x.to_bits() as i64 >= 0 { + let z = x - PIO2_1; + if ix != 0x3ff921fb { + let y0 = z - PIO2_1T; + (1, y0, (z - y0) - PIO2_1T) + } else { + let z = z - PIO2_2; + let y0 = z - PIO2_2T; + (1, y0, (z - y0) - PIO2_2T) + } + } else { + let z = x + PIO2_1; + if ix != 0x3ff921fb { + let y0 = z + PIO2_1T; + (-1, y0, (z - y0) + PIO2_1T) + } else { + let z = z + PIO2_2; + let y0 = z + PIO2_2T; + (-1, y0, (z - y0) + PIO2_2T) + } + }); + } + if ix > 0x413921fb { + return None; + } + let t = x.abs(); + let fnv = t.mul_add(INVPIO2, 0.5).trunc(); + let n = fnv as i32; + let mut r = (-fnv).mul_add(PIO2_1, t); + let mut w = fnv * PIO2_1T; + let mut y0 = r - w; + if n > 32 || ix == NPIO2_HW[(n - 1) as usize] { + let j = ix >> 20; + let exponent = |y: f64| ((y.to_bits() << 1) >> 53) as i32; + if j - exponent(y0) > 16 { + let t = r; + let w2 = fnv * PIO2_2; + r = t - w2; + w = fnv.mul_add(PIO2_2T, w2 - (t - r)); + y0 = r - w; + if j - exponent(y0) > 49 { + let t = r; + let w3 = fnv * PIO2_3; + r = t - w3; + w = fnv.mul_add(PIO2_3T, w3 - (t - r)); + y0 = r - w; + } + } + } + let y1 = (r - y0) - w; + Some(if x > 0.0 { (n, y0, y1) } else { (-n, -y0, -y1) }) + } + + fn sin_cos(x: f64, is_cos: bool) -> f64 { + let ix = (hi(x) & 0x7fff_ffff) as i32; + if ix < 0x3e400000 { + return if is_cos { 1.0 } else { x }; + } + if ix <= 0x3fe921fb { + return if is_cos { + kernel_cos(x, 0.0, ix) + } else { + kernel_sin(x, 0.0, false) + }; + } + if ix >= 0x7ff00000 { + return f64::from_bits(0x7ff0_0000_0000_0001); + } + // Beyond 2^19·π/2 the stub's Payne–Hanek reduction isn't ported: + // StrictMath's is used instead. + let Some((n, y0, y1)) = rem_pio2(x, ix) else { + return if is_cos { libm::cos(x) } else { libm::sin(x) }; + }; + let (value, negate) = if (n & 1 == 1) != is_cos { + ( + kernel_cos(y0, y1, ix), + if is_cos { (n ^ (n >> 1)) & 1 } else { n & 2 }, + ) + } else { + ( + kernel_sin(y0, y1, true), + if is_cos { (n ^ (n >> 1)) & 1 } else { n & 2 }, + ) + }; + if negate != 0 { -value } else { value } + } + + /// `Math.sin` on AArch64 HotSpot. + pub fn sin(x: f64) -> f64 { + sin_cos(x, false) + } + + /// `Math.cos` on AArch64 HotSpot. + pub fn cos(x: f64) -> f64 { + sin_cos(x, true) + } +} + +#[cfg(test)] +mod tests { + use super::{aarch64, fdlibm}; + + fn check1(f: fn(f64) -> f64, (x, expected): (u64, u64)) { + assert_eq!(f(f64::from_bits(x)).to_bits(), expected, "{x:x}"); + } + + fn check2(f: fn(f64, f64) -> f64, (x, y, expected): (u64, u64, u64)) { + assert_eq!( + f(f64::from_bits(x), f64::from_bits(y)).to_bits(), + expected, + "{x:x} {y:x}" + ); + } + + #[test] + fn matches_hotspot_on_aarch64() { + // (argument bits, Math result bits) from HotSpot 25 on an Apple M4, each + // one where glibc rounds differently. + // sin + check1(aarch64::sin, (0x3fe63c5ab66b09f0, 0x3fe47d34215b54f7)); + check1(aarch64::sin, (0xc0569150fe105e6f, 0xbfe7bc19d65ab55c)); + check1(aarch64::sin, (0x4072c3f15b47b5d6, 0xbfef32be0f0a9124)); + check1(aarch64::sin, (0x3fee86c6ffce047e, 0x3fea1a47f46cbf28)); + // cos + check1(aarch64::cos, (0x3fbb10690eeadb00, 0x3fefd24375dbae28)); + check1(aarch64::cos, (0xc0496cc08a65245d, 0x3feab1a44a8022c4)); + check1(aarch64::cos, (0x40099262f89e73f8, 0xbfeff3aa148795ce)); + check1(aarch64::cos, (0x4001ce4e022387bc, 0xbfe37dd512be4d00)); + // log + check1(fdlibm::log, (0x40569150fe105e6f, 0x401202e102f27b78)); + check1(fdlibm::log, (0x3ff5dec70f518390, 0x3fd4009cda1f8856)); + check1(fdlibm::log, (0x3feb3d17325d493e, 0xbfc49ee8c4866f84)); + check1(fdlibm::log, (0x3fe735a40edf77ba, 0xbfd48e1816b18bf2)); + // log10 + check1(fdlibm::log10, (0x3ff5dec70f518390, 0x3fc15fb52aa5f051)); + check1(fdlibm::log10, (0x3feb3d17325d493e, 0xbfb1e933cae02f5f)); + check1(fdlibm::log10, (0x3fe735a40edf77ba, 0xbfc1da98cbb8974c)); + check1(fdlibm::log10, (0x3fe7febd9ca1bab0, 0xbfc000e8e3b0b56e)); + // cbrt + check1(fdlibm::cbrt, (0x401bb21f8568bd0c, 0x3ffe7ee30c7a56f9)); + check1(fdlibm::cbrt, (0x3fc59f3a45c8fb80, 0x3fe1b0791e0f8a74)); + check1(fdlibm::cbrt, (0xbfdd73cdc693ddab, 0xbfe8b4a6f43f1b73)); + check1(fdlibm::cbrt, (0xbfeb0715a8425e10, 0xbfee3f99498da6f6)); + // hypot + check2( + fdlibm::hypot, + (0xc0569150fe105e6f, 0xc0056b970bf3b41a, 0x405693db72f461a6), + ); + check2( + fdlibm::hypot, + (0x3fdc5999df9270f4, 0xc006c3ad990f72c0, 0x400709de26a1e40a), + ); + check2( + fdlibm::hypot, + (0x401bb21f8568bd0c, 0xbffeb93d1a2ef904, 0x401cbdbb623d20c3), + ); + check2( + fdlibm::hypot, + (0x4026d31c32ddb50b, 0xc00e7b2771d6867c, 0x40281027bb313aae), + ); + // pow + check2( + libm::pow, + (0x3fee04c313607ea6, 0xc00fd156138baf96, 0x3ff4a199ac2c8e9c), + ); + check2( + libm::pow, + (0x401bb21f8568bd0c, 0xbffeb93d1a2ef904, 0x3f98ecc16a60feee), + ); + check2( + libm::pow, + (0x407383ff427dadbd, 0x3ffdc5d178d00264, 0x40e56695c058d704), + ); + check2( + libm::pow, + (0x3fe0c95b66dd6030, 0xc00c9cfde259a3e6, 0x4024194449e9deca), + ); + // exp + check1(libm::exp, (0x3fdc5999df9270f4, 0x3ff8eacc53fdbf56)); + check1(libm::exp, (0x3fcffff502ecbd80, 0x3ff48b5c78bca894)); + check1(libm::exp, (0x3fc59f3a45c8fb80, 0x3ff2f1c6cb35728c)); + check1(libm::exp, (0x4056561bf10ba7f6, 0x47fdd21dc9013084)); + // tan + check1(libm::tan, (0x40023034f56881f0, 0xbff2e3f762ac9810)); + check1(libm::tan, (0xbfebf862877c88ec, 0xbff31f61e3e8539e)); + check1(libm::tan, (0xc00e37e234490564, 0xbfe79ca6eee66726)); + check1(libm::tan, (0xc075c085c04800b5, 0x3fea18b4a92fcf22)); + } +} diff --git a/crates/horizon-core/src/lib.rs b/crates/horizon-core/src/lib.rs index 79045910a..5b46ce2ef 100644 --- a/crates/horizon-core/src/lib.rs +++ b/crates/horizon-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod biome; pub mod carving; pub mod density; pub mod geometry; +pub mod jmath; pub mod noise; pub mod paletted; pub mod position; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index 3a21aaae2..468e0ee61 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -476,7 +476,12 @@ public final class VanillaProtocolClient { record("play", r.type + " " + json(p.reason())); break; } - if (ordered) { + // MinecraftServer.tickServer syncs the game time every 20 ticks + // (no clocks): whether one lands before the first chunk batch + // depends on when the client joined, so it isn't compared. + boolean periodicTime = packet instanceof net.minecraft.network.protocol.game.ClientboundSetTimePacket p + && p.clockUpdates().isEmpty(); + if (ordered && !periodicTime) { record("play-start", r.type + " " + summary(r)); } if (packet instanceof net.minecraft.network.protocol.game.ClientboundCommandsPacket p && counts.get(r.type) == 1) { From ab9109c7874c630b9cdd51339aaad64bdbf97269 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:06:48 +0200 Subject: [PATCH 02/18] Route world generation's and mob AI's Math calls through jmath Beardifier, density pow/log, Marsaglia's Gaussian, dripstone, ores, fancy trunks, icebergs, end spikes, strongholds, note pitches, sculk charge particles, the warden's and brains' weighted shuffles. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/animal_brain.rs | 2 +- crates/horizon-client/src/mobs/monster_brain.rs | 2 +- crates/horizon-client/src/mobs/villager_brain.rs | 4 ++-- crates/horizon-client/src/mobs/warden.rs | 4 ++-- crates/horizon-core/src/density/arithmetic.rs | 4 ++-- crates/horizon-core/src/density/beardifier.rs | 2 +- crates/horizon-core/src/density/interval.rs | 2 +- crates/horizon-core/src/random.rs | 2 +- crates/horizon-world/src/level/redstone.rs | 2 +- crates/horizon-world/src/level/sculk.rs | 3 ++- crates/horizon-world/src/worldgen/dripstone.rs | 6 +++--- crates/horizon-world/src/worldgen/end_spike.rs | 4 ++-- crates/horizon-world/src/worldgen/iceberg.rs | 10 +++++++--- crates/horizon-world/src/worldgen/ore_feature.rs | 5 ++++- .../horizon-world/src/worldgen/structure/stronghold.rs | 5 ++++- crates/horizon-world/src/worldgen/tree/trunk.rs | 9 +++++---- tools/parity_hosts.json | 7 +------ 17 files changed, 40 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9edf2accf..cf7862773 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -742,7 +742,7 @@ impl Gate { // current order, then a stable sort. for k in &mut self.kids { let r = self.random.next_float(); - k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32)); } self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); for k in &mut self.kids { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index c770858a6..bc2cfe705 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -550,7 +550,7 @@ impl RunOne { // order, then a stable sort. for k in &mut self.kids { let r = self.random.next_float(); - k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32)); } self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); for k in &mut self.kids { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 4d94ca2bb..63a112d0a 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -1101,7 +1101,7 @@ impl Gate { // current order, then a stable sort. for k in &mut self.kids { let r = self.random.next_float(); - k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32)); } self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); } @@ -2392,7 +2392,7 @@ impl B { } => { for k in kids.iter_mut() { let r = random.next_float(); - k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32)); } kids.sort_by(|a, b| a.2.total_cmp(&b.2)); for k in kids.iter_mut() { diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 11394a011..44544a4f8 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -1061,8 +1061,8 @@ fn attack(m: &mut Mob, target: Who, cx: &mut Cx) { fn run_one(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { let now = i64::from(m.age); // ShufflingList.shuffle: each entry sorts by -ln(random) / weight. - let stroll_key = -f64::from(m.random.next_float()).ln() / 2.0; - let pause_key = -f64::from(m.random.next_float()).ln(); + let stroll_key = -horizon_core::jmath::log(f64::from(m.random.next_float())) / 2.0; + let pause_key = -horizon_core::jmath::log(f64::from(m.random.next_float())); let pause_first = pause_key < stroll_key; let order = if pause_first { [false, true] diff --git a/crates/horizon-core/src/density/arithmetic.rs b/crates/horizon-core/src/density/arithmetic.rs index 296a071e8..f82b96ce2 100644 --- a/crates/horizon-core/src/density/arithmetic.rs +++ b/crates/horizon-core/src/density/arithmetic.rs @@ -8,7 +8,7 @@ pub(super) fn java_power(base: f64, exponent: f64) -> f64 { } else if exponent.is_nan() || (base.abs() == 1.0 && exponent.is_infinite()) { f64::NAN } else { - base.powf(exponent) + crate::jmath::pow(base, exponent) } } @@ -83,7 +83,7 @@ impl UnaryOp { Self::Square => value * value, Self::Cube => value * value * value, Self::Sqrt => (value as f64).sqrt() as f32, - Self::Log => (value as f64).ln() as f32, + Self::Log => crate::jmath::log(value as f64) as f32, Self::PowerBase(base) => java_power(base, value as f64) as f32, Self::PowerExponent(exponent) => java_power(value as f64, exponent) as f32, Self::Reciprocal => 1.0 / value, diff --git a/crates/horizon-core/src/density/beardifier.rs b/crates/horizon-core/src/density/beardifier.rs index 225f74714..73b94a066 100644 --- a/crates/horizon-core/src/density/beardifier.rs +++ b/crates/horizon-core/src/density/beardifier.rs @@ -208,7 +208,7 @@ fn kernel() -> &'static [f32; 13824] { let x = ((i / 24) % 24) as f64 - 12.; let y = (i % 24) as f64 - 12. + 0.5; let squared = (x * x + y * y) + z * z; - std::f64::consts::E.powf(-squared / 16.) as f32 + crate::jmath::pow(std::f64::consts::E, -squared / 16.) as f32 }) }) } diff --git a/crates/horizon-core/src/density/interval.rs b/crates/horizon-core/src/density/interval.rs index 0375dba6d..0e2652fe1 100644 --- a/crates/horizon-core/src/density/interval.rs +++ b/crates/horizon-core/src/density/interval.rs @@ -189,7 +189,7 @@ impl Interval { Ok(Self::NAI) } else { self.maximum(Self::exact(0.0)?) - .map_monotonic(|v| (v as f64).ln() as f32) + .map_monotonic(|v| crate::jmath::log(v as f64) as f32) } } pub fn power(self, exponent: Self) -> Self { diff --git a/crates/horizon-core/src/random.rs b/crates/horizon-core/src/random.rs index 89de3e1f1..609cf59be 100644 --- a/crates/horizon-core/src/random.rs +++ b/crates/horizon-core/src/random.rs @@ -300,7 +300,7 @@ pub fn marsaglia_polar(cache: &mut Option, mut next_double: impl FnMut() -> if radius >= 1.0 || radius == 0.0 { continue; } - let multiplier = (-2.0 * radius.ln() / radius).sqrt(); + let multiplier = (-2.0 * crate::jmath::log(radius) / radius).sqrt(); *cache = Some(y * multiplier); return x * multiplier; } diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index 6e4722844..92f9059e5 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -1092,7 +1092,7 @@ impl Sim<'_, L> { let pitch = if mob_head { 1.0 } else { - 2f64.powf(f64::from(note - 12) / 12.0) as f32 + horizon_core::jmath::pow(2.0, f64::from(note - 12) / 12.0) as f32 }; let sound = match instrument.as_str() { "custom_head" => "minecraft:ui.button.click".to_owned(), diff --git a/crates/horizon-world/src/level/sculk.rs b/crates/horizon-world/src/level/sculk.rs index a831f2151..46073cf5e 100644 --- a/crates/horizon-world/src/level/sculk.rs +++ b/crates/horizon-world/src/level/sculk.rs @@ -315,7 +315,8 @@ impl Sim<'_, L> { if charge > 0 && let Some(faces) = faces { - let particles = ((f64::from(charge) + 1.0).ln() as f32 / 2.3) as i32 + 1; + let particles = + (horizon_core::jmath::log(f64::from(charge) + 1.0) as f32 / 2.3) as i32 + 1; let data = (particles << 6) + pack_faces(&faces); self.level_event(3006, pos, data); } diff --git a/crates/horizon-world/src/worldgen/dripstone.rs b/crates/horizon-world/src/worldgen/dripstone.rs index 2358bd723..8b67e0eca 100644 --- a/crates/horizon-world/src/worldgen/dripstone.rs +++ b/crates/horizon-world/src/worldgen/dripstone.rs @@ -545,9 +545,9 @@ fn speleothem_height(distance: f64, radius: f64, scale: f64, bluntness: f64) -> distance }; let r = distance / radius * 0.384; - let part1 = 0.75 * r.powf(1.3333333333333333); - let part2 = r.powf(0.6666666666666666); - let part3 = 0.3333333333333333 * r.ln(); + let part1 = 0.75 * horizon_core::jmath::pow(r, 1.3333333333333333); + let part2 = horizon_core::jmath::pow(r, 0.6666666666666666); + let part3 = 0.3333333333333333 * horizon_core::jmath::log(r); let height = (scale * (part1 - part2 - part3)).max(0.0); height / 0.384 * radius } diff --git a/crates/horizon-world/src/worldgen/end_spike.rs b/crates/horizon-world/src/worldgen/end_spike.rs index a2c00ee08..e76982853 100644 --- a/crates/horizon-world/src/worldgen/end_spike.rs +++ b/crates/horizon-world/src/worldgen/end_spike.rs @@ -38,8 +38,8 @@ pub fn spikes_for_seed(seed: i64) -> Vec { 2.0 * (-std::f64::consts::PI + (std::f64::consts::PI / 10.0) * f64::from(i)); let size = sizes[i as usize]; EndSpike { - center_x: (42.0 * angle.cos()).floor() as i32, - center_z: (42.0 * angle.sin()).floor() as i32, + center_x: (42.0 * horizon_core::jmath::cos(angle)).floor() as i32, + center_z: (42.0 * horizon_core::jmath::sin(angle)).floor() as i32, radius: 2 + size / 3, height: 76 + size * 3, guarded: size == 1 || size == 2, diff --git a/crates/horizon-world/src/worldgen/iceberg.rs b/crates/horizon-world/src/worldgen/iceberg.rs index 2bfeff29a..3a7409ad3 100644 --- a/crates/horizon-world/src/worldgen/iceberg.rs +++ b/crates/horizon-world/src/worldgen/iceberg.rs @@ -29,7 +29,7 @@ fn ceil(v: f32) -> i32 { f64::from(v).ceil() as i32 } fn pow2(v: i32) -> f64 { - f64::from(v).powf(2.0) + horizon_core::jmath::pow(f64::from(v), 2.0) } impl IcebergFeature { pub(crate) fn decode( @@ -380,7 +380,11 @@ impl IcebergFeature { fn signed_ellipse(xo: i32, zo: i32, origin: [i32; 3], a: i32, c: i32, angle: f64) -> f64 { let dx = f64::from(xo - origin[0]); let dz = f64::from(zo - origin[2]); - ((dx * angle.cos() - dz * angle.sin()) / f64::from(a)).powf(2.0) - + ((dx * angle.sin() + dz * angle.cos()) / f64::from(c)).powf(2.0) + let (sin, cos) = ( + horizon_core::jmath::sin(angle), + horizon_core::jmath::cos(angle), + ); + horizon_core::jmath::pow((dx * cos - dz * sin) / f64::from(a), 2.0) + + horizon_core::jmath::pow((dx * sin + dz * cos) / f64::from(c), 2.0) - 1.0 } diff --git a/crates/horizon-world/src/worldgen/ore_feature.rs b/crates/horizon-world/src/worldgen/ore_feature.rs index c4cbe447e..9d723ae40 100644 --- a/crates/horizon-world/src/worldgen/ore_feature.rs +++ b/crates/horizon-world/src/worldgen/ore_feature.rs @@ -155,7 +155,10 @@ impl OreFeature { let spread_xy = self.size as f32 / 8.0; let max_radius = ((self.size as f32 / 16.0 * 2.0 + 1.0) / 2.0).ceil() as i32; let (ox, oz) = (f64::from(origin[0]), f64::from(origin[2])); - let (sin, cos) = (f64::from(dir).sin(), f64::from(dir).cos()); + let (sin, cos) = ( + horizon_core::jmath::sin(f64::from(dir)), + horizon_core::jmath::cos(f64::from(dir)), + ); let spread = f64::from(spread_xy); let x0 = ox + sin * spread; let x1 = ox - sin * spread; diff --git a/crates/horizon-world/src/worldgen/structure/stronghold.rs b/crates/horizon-world/src/worldgen/structure/stronghold.rs index 95fcd679c..eb31e0627 100644 --- a/crates/horizon-world/src/worldgen/structure/stronghold.rs +++ b/crates/horizon-world/src/worldgen/structure/stronghold.rs @@ -30,7 +30,10 @@ pub fn ring_positions( let dist = f64::from(4 * distance + distance * circle * 6) + (random.next_double() - 0.5) * (f64::from(distance) * 2.5); let round = |v: f64| (v + 0.5).floor() as i64 as i32; - let (x, z) = (round(angle.cos() * dist), round(angle.sin() * dist)); + let (x, z) = ( + round(horizon_core::jmath::cos(angle) * dist), + round(horizon_core::jmath::sin(angle) * dist), + ); let mut search = random.fork(); let (cx, cz) = ((x * 16 + 8) >> 2, (z * 16 + 8) >> 2); let mut found = 0; diff --git a/crates/horizon-world/src/worldgen/tree/trunk.rs b/crates/horizon-world/src/worldgen/tree/trunk.rs index b88e88bfc..741f0e2a7 100644 --- a/crates/horizon-world/src/worldgen/tree/trunk.rs +++ b/crates/horizon-world/src/worldgen/tree/trunk.rs @@ -690,8 +690,9 @@ impl TrunkPlacer { let height = tree_height + 2; let trunk_height = (f64::from(height) * 0.618).floor() as i32; Self::place_below_trunk(run, tree, tb::offset(origin, 0, -1, 0))?; - let clusters_per_y = - 1.min((1.382 + (1.0 * f64::from(height) / 13.0).powf(2.0)).floor() as i32); + let clusters_per_y = 1.min( + (1.382 + horizon_core::jmath::pow(1.0 * f64::from(height) / 13.0, 2.0)).floor() as i32, + ); let trunk_top = origin[1].wrapping_add(trunk_height); let mut relative_y = height - 5; // (attachment position, branch base y) @@ -704,8 +705,8 @@ impl TrunkPlacer { let radius = 1.0 * f64::from(shape) * (f64::from(run.random.next_float()) + 0.328); let angle = f64::from(run.random.next_float() * 2.0f32) * std::f64::consts::PI; - let x = radius * angle.sin() + 0.5; - let z = radius * angle.cos() + 0.5; + let x = radius * horizon_core::jmath::sin(angle) + 0.5; + let z = radius * horizon_core::jmath::cos(angle) + 0.5; let check_start = tb::offset(origin, x.floor() as i32, relative_y - 1, z.floor() as i32); let check_end = tb::offset(check_start, 0, 5, 0); diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 5347c9257..4d5bd1bcd 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -9,12 +9,7 @@ "python": "/opt/homebrew/bin/python3.13", "rsync": "/opt/homebrew/bin/rsync", "jobs": 14, - "exclude": { - "options": "Rust's f64::powf uses the platform libm, which rounds differently on macOS", - "chunk_generation": "one ocean ruined portal differs on macOS (platform float math)", - "world_border_render": "the wall's alpha differs by one ulp on macOS (platform float math)", - "mob_ai": "mob movement differs on macOS (platform float math in random positions)" - } + "exclude": {} }, "thinkpad": { "ssh": "thinkpad", From 6aa875c6c2a037d61cb59e2ae7cc0afc3bed01b5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:12:59 +0200 Subject: [PATCH 03/18] Compute the breeze's long-jump vector with jmath; run every harness on the Mac The Mac mini no longer excludes options, chunk_generation, world_border_render and mob_ai: their float maths now matches vanilla's on Apple silicon. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/breeze.rs | 10 +++++----- docs/parity-workflow.md | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/mobs/breeze.rs b/crates/horizon-client/src/mobs/breeze.rs index 4a8484835..5d78fa8ab 100644 --- a/crates/horizon-client/src/mobs/breeze.rs +++ b/crates/horizon-client/src/mobs/breeze.rs @@ -6,7 +6,7 @@ use super::{ anim::{Poses, State}, keyframes::Animation, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{geometry::Vec3, jmath, random::RandomSource}; use std::collections::HashMap; // `variant3` is the pose, `variant` the pose the animations last saw, @@ -96,9 +96,9 @@ fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option Option`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 3 and only those under 800 MB. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. -Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. On macOS, `options` and `chunk_generation` differ because Rust's float functions (`f64::powf` and the like) use the platform libm, which rounds differently from glibc; every other harness gave the same result on the Mac as on Linux. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop. +Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop. ### Shards and Rust scopes From 19d4146f04473e9775b1c769a37503d98894f772 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:16:04 +0200 Subject: [PATCH 04/18] Draw player list heads from players' skins as vanilla does Profiles' textures properties are unpacked as authlib does and looked up as SkinManager does (signatures, the local player, allowed texture URLs, downloads), skins are fetched and processed as SkinTextureDownloader does and shown from atlas slots. The tab_list harness now runs a real SkinManager and compares processLegacySkin over 400 PNGs. Co-Authored-By: Claude Opus 5.5 --- .../examples/skin_image_fixture.rs | 32 ++ .../examples/tab_list_fixture.rs | 30 +- crates/horizon-client/src/game.rs | 10 + crates/horizon-client/src/game/remote.rs | 91 +++- crates/horizon-client/src/hud.rs | 12 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/skins.rs | 442 ++++++++++++++++++ .../parity/VanillaSkinImageOracle.java | 47 ++ .../parity/VanillaTabListOracle.java | 83 +++- tools/test_tab_list_parity.py | 116 ++++- 10 files changed, 851 insertions(+), 13 deletions(-) create mode 100644 crates/horizon-client/examples/skin_image_fixture.rs create mode 100644 crates/horizon-client/src/skins.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSkinImageOracle.java diff --git a/crates/horizon-client/examples/skin_image_fixture.rs b/crates/horizon-client/examples/skin_image_fixture.rs new file mode 100644 index 000000000..9373fb1f5 --- /dev/null +++ b/crates/horizon-client/examples/skin_image_fixture.rs @@ -0,0 +1,32 @@ +//! Headless transport for the skin half of the player list parity gate: +//! decodes each base64 PNG and runs `horizon_client::skins::process_legacy_skin`, +//! writing the RGBA result in base64, or "refused". +#![forbid(unsafe_code)] +use std::{ + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [inputs, output] = args.as_slice() else { + return Err("usage: skin_image_fixture INPUTS OUTPUT".into()); + }; + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let png = horizon_client::skins::base64_decode(line).ok_or("bad base64")?; + let result = horizon_client::hud::decode_bytes(&png) + .ok() + .and_then(|(w, h, rgba)| horizon_client::skins::process_legacy_skin(w, h, &rgba)); + match result { + Some(rgba) => writeln!(out, "{}", horizon_client::lan::base64(&rgba))?, + None => writeln!(out, "refused")?, + } + } + Ok(()) +} diff --git a/crates/horizon-client/examples/tab_list_fixture.rs b/crates/horizon-client/examples/tab_list_fixture.rs index 3a9ad16a9..aca50e204 100644 --- a/crates/horizon-client/examples/tab_list_fixture.rs +++ b/crates/horizon-client/examples/tab_list_fixture.rs @@ -2,7 +2,8 @@ //! scoreboard (teams, `list` objective, scores), listed players, header and //! footer, replays its frames through `horizon_client::tab_list` and writes //! the draw calls in vanilla's GuiGraphicsExtractor terms (text as styled -//! runs, faces as skin blits). +//! runs, faces as skin blits), each face's skin chosen by +//! `horizon_client::skins` from the profile's `textures` property. #![forbid(unsafe_code)] use horizon_client::{ component, @@ -10,6 +11,7 @@ use horizon_client::{ hud_layout::GuiDraw, lang, scoreboard::{NumberFormat, RenderType, Scoreboard}, + skins, tab_list::{self, TabInputs, TabList, TabPlayer}, text::Text, }; @@ -92,6 +94,12 @@ fn main() -> Result<()> { format(&c["objective"]["numberFormat"]), ); } + let uris: Vec<&str> = c["validUris"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); let mut players = Vec::new(); let mut upside = Vec::new(); for p in c["players"].as_array().into_iter().flatten() { @@ -108,6 +116,26 @@ fn main() -> Result<()> { player.display_name = (!p["displayName"].is_null()).then(|| p["displayName"].clone()); player.list_order = p["listOrder"].as_i64().unwrap_or(0) as i32; player.show_hat = p["showHat"].as_bool().unwrap_or(true); + if let Some(t) = p.get("textures").filter(|t| !t.is_null()) { + let signature = match t["signature"].as_str() { + None => skins::Signature::Unsigned, + Some("valid") => skins::Signature::Signed, + Some(_) => skins::Signature::Invalid, + }; + let textures = skins::unpack(t["value"].as_str().unwrap_or(""), signature, &uris); + let local = c["local"].as_str() == p["uuid"].as_str(); + let download = |_, url: &str| { + let hash = skins::texture_hash(url).unwrap_or_default(); + match c["downloads"][&hash].as_str() { + Some("pending") => skins::Download::Pending, + Some("fail") => skins::Download::Failed, + _ => skins::Download::Ready, + } + }; + if let Some(skin) = skins::lookup(&textures, !local, download) { + player.skin = skin; + } + } players.push(player); } let mut list = TabList::default(); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f86435c9b..2b4521e34 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -743,6 +743,10 @@ struct Game<'a> { dragon_model: Option, /// Map textures waiting for the next HUD batch to upload them. map_patches: Vec, + /// Player skin downloads, and which skin each atlas skin slot holds + /// (least recently shown first). + skin_downloads: horizon_client::skins::Downloader, + skin_slots: Vec<(String, usize)>, cart_models: minecarts::CartModels, /// The boat the player rides. riding: Option, @@ -8375,6 +8379,12 @@ pub fn run() -> Result<()> { breath_clouds: Vec::new(), dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), map_patches: Vec::new(), + skin_downloads: horizon_client::skins::Downloader::new( + std::env::current_dir() + .unwrap_or_default() + .join("assets/skins"), + ), + skin_slots: Vec::new(), cart_models: minecarts::CartModels::load(&root), riding: None, ender_items: vec![None; 27], diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 83c132430..91b99e473 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -105,6 +105,8 @@ pub(super) struct Remote { /// `ClientPacketListener.playerInfoMap` as player-list entries, and /// which of them are listed. tab_players: HashMap, + /// Each listed profile's unpacked `textures` property. + skin_textures: HashMap, listed: std::collections::HashSet, /// `ClientboundLoginPacket.onlineMode`: the player list shows heads. online_mode: bool, @@ -234,6 +236,7 @@ impl Game<'_> { action_bar: None, players: HashMap::new(), tab_players: HashMap::new(), + skin_textures: HashMap::new(), listed: Default::default(), online_mode: false, level_players: HashMap::new(), @@ -1120,6 +1123,21 @@ impl Game<'_> { r.tab_players.entry(e.uuid).or_insert_with(|| { horizon_client::tab_list::TabPlayer::new(e.uuid, name.clone()) }); + if let Some(t) = e.properties.iter().find(|p| p.name == "textures") + { + // Without the services' profile property keys a + // signature can't be checked; a signed property + // counts as genuine. + use horizon_client::skins::{self, Signature}; + let signature = if t.signature.is_some() { + Signature::Signed + } else { + Signature::Unsigned + }; + let textures = + skins::unpack(&t.value, signature, &skins::TEXTURE_URIS); + r.skin_textures.entry(e.uuid).or_insert(textures); + } } } } @@ -1162,6 +1180,7 @@ impl Game<'_> { for u in p.uuids { r.players.remove(&u); r.tab_players.remove(&u); + r.skin_textures.remove(&u); r.listed.remove(&u); } } @@ -1327,17 +1346,41 @@ impl Game<'_> { _ => {} } } - /// The player list's view of the connection: the listed players, online - /// mode, and which players are in the level with an upside-down name. + /// The player list's view of the connection: the listed players (with + /// their downloaded skins once ready), online mode, and which players + /// are in the level with an upside-down name. pub(super) fn remote_tab_players( - &self, + &mut self, ) -> Option<(Vec, bool, Vec)> { let r = self.remote.as_ref()?; - let players: Vec<_> = r + let mut players: Vec<_> = r .listed .iter() .filter_map(|u| r.tab_players.get(u).cloned()) .collect(); + for p in &mut players { + let Some(textures) = r.skin_textures.get(&p.uuid) else { + continue; + }; + // PlayerInfo.createSkinLookup: only the local player's own skin + // may be unsigned. + let downloads = &mut self.skin_downloads; + let skin = horizon_client::skins::lookup(textures, p.uuid != r.profile, |kind, url| { + downloads.state(kind, url) + }); + if let Some(skin) = skin { + p.skin = skin; + } + } + for (location, rgba) in self.skin_downloads.take_ready() { + self.store_skin(location, rgba); + } + for p in &mut players { + if p.skin.starts_with("skins/") && !self.show_skin(&p.skin) { + p.skin = horizon_client::tab_list::default_skin(p.uuid).to_owned(); + } + } + let r = self.remote.as_ref()?; let upside_down = players .iter() .filter(|p| { @@ -1348,6 +1391,46 @@ impl Game<'_> { .collect(); Some((players, r.online_mode, upside_down)) } + /// Puts a downloaded skin in an atlas skin slot: a free one, else the + /// least recently shown. + fn store_skin(&mut self, location: String, rgba: Vec) { + use horizon_client::hud::SKIN_SLOTS; + let slot = if self.skin_slots.len() < SKIN_SLOTS { + self.skin_slots.len() + } else { + let (old, slot) = self.skin_slots.remove(0); + self.res.atlas.sprites.remove(&old); + slot + }; + let Some(rect) = self + .res + .atlas + .sprites + .get(&format!("horizon/skin{slot}")) + .copied() + else { + return; + }; + let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + self.map_patches.push(horizon_client::font::Patch { + x: (rect.u0 * w).round() as u32, + y: (rect.v0 * h).round() as u32, + width: 64, + height: 64, + rgba, + }); + self.res.atlas.sprites.insert(location.clone(), rect); + self.skin_slots.push((location, slot)); + } + /// Whether a downloaded skin is in the atlas, marking it recently shown. + fn show_skin(&mut self, location: &str) -> bool { + let Some(i) = self.skin_slots.iter().position(|e| e.0 == location) else { + return false; + }; + let e = self.skin_slots.remove(i); + self.skin_slots.push(e); + true + } /// ChatType decoration: `chat.translation_key` with sender/content parameters. fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { let Some(r) = self.remote.as_ref() else { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index a3996b7c6..a61f3045c 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -31,8 +31,14 @@ pub struct HudAtlas { pub const GLYPH_ROWS: u32 = 512; /// 128x128 atlas slots for map textures. pub const MAP_SLOTS: usize = 16; +/// Atlas slots for downloaded player skins (`skins/`), 64x64 each. +pub const SKIN_SLOTS: usize = 32; pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { - let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?)); + decode_bytes(&fs::read(path)?) +} +/// A PNG in memory as RGBA pixels. +pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec)> { + let mut decoder = png::Decoder::new(std::io::Cursor::new(data)); decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); let mut reader = decoder.read_info()?; let mut bytes = vec![0; reader.output_buffer_size().ok_or("image too large")?]; @@ -194,6 +200,10 @@ impl HudAtlas { for i in 0..MAP_SLOTS { images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4])); } + // Downloaded skins (game/scoreboard.rs) likewise. + for i in 0..SKIN_SLOTS { + images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4])); + } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); let width = 4096u32; let mut placements = Vec::with_capacity(images.len()); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1f8893cd4..fcc60c69c 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -95,6 +95,7 @@ pub mod server; pub mod settings; pub mod shadows; pub mod signs; +pub mod skins; pub mod snbt; pub mod sound_engine; pub mod sound_events; diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs new file mode 100644 index 000000000..acacf7520 --- /dev/null +++ b/crates/horizon-client/src/skins.rs @@ -0,0 +1,442 @@ +//! Player skins from profile `textures` properties: authlib's +//! `MinecraftServicesSessionService.unpackTextures`, vanilla's +//! `SkinManager` lookup (which texture a player shows, and when the default +//! one) and `SkinTextureDownloader.processLegacySkin`. + +/// `Property.hasSignature` and the services key check, as authlib's +/// `SignatureState`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Signature { + Unsigned, + Signed, + Invalid, +} + +/// `MinecraftProfileTextures`: the texture URLs a profile names. Empty when +/// the payload doesn't decode or names a URL outside the allowed domains. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Textures { + pub skin: Option, + pub cape: Option, + pub elytra: Option, + pub signed: bool, +} + +/// The `getTexture` endpoint's valid URIs from Minecraft services discovery. +pub const TEXTURE_URIS: [&str; 2] = [ + "https://textures.minecraft.net/texture/{textureId}", + "http://textures.minecraft.net/texture/{textureId}", +]; + +/// `java.util.Base64.getDecoder().decode`. +pub fn base64_decode(text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len() / 4 * 3); + let (mut bits, mut shift) = (0u32, 18i32); + let bytes: Vec = text.chars().collect(); + let mut i = 0; + while i < bytes.len() { + let c = bytes[i]; + i += 1; + let b = match c { + 'A'..='Z' => c as u32 - 'A' as u32, + 'a'..='z' => c as u32 - 'a' as u32 + 26, + '0'..='9' => c as u32 - '0' as u32 + 52, + '+' => 62, + '/' => 63, + '=' => { + if shift == 6 && (i == bytes.len() || bytes[i] != '=') || shift == 18 { + return None; + } + if shift == 6 { + i += 1; + } + break; + } + _ => return None, + }; + bits |= b << shift; + shift -= 6; + if shift < 0 { + out.extend([(bits >> 16) as u8, (bits >> 8) as u8, bits as u8]); + shift = 18; + bits = 0; + } + } + match shift { + 6 => out.push((bits >> 16) as u8), + 0 => out.extend([(bits >> 16) as u8, (bits >> 8) as u8]), + 12 => return None, + _ => {} + } + (i >= bytes.len()).then_some(out) +} + +/// `unpackTextures(property)`: the textures of a `textures` property's +/// base64 JSON payload. +pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Textures { + let empty = Textures::default(); + let Some(json) = base64_decode(value) + .map(|b| String::from_utf8_lossy(&b).into_owned()) + .and_then(|s| serde_json::from_str::(&s).ok()) + else { + return empty; + }; + let Some(textures) = json.get("textures").and_then(|t| t.as_object()) else { + return empty; + }; + if textures.is_empty() { + return empty; + } + let mut out = Textures { + signed: signature == Signature::Signed, + ..empty.clone() + }; + for (kind, texture) in textures { + let Some(url) = texture.get("url").and_then(|u| u.as_str()) else { + return empty; + }; + let allowed = valid_uris + .iter() + .any(|u| url.starts_with(&u.replace("{textureId}", ""))); + if !allowed { + return empty; + } + let slot = match kind.as_str() { + "SKIN" => &mut out.skin, + "CAPE" => &mut out.cape, + "ELYTRA" => &mut out.elytra, + _ => continue, + }; + *slot = Some(url.to_owned()); + } + out +} + +/// `MinecraftProfileTexture.getHash`: the base name of the URL's path. +pub fn texture_hash(url: &str) -> Option { + let rest = url.split_once("://")?.1; + let path = &rest[rest.find('/').unwrap_or(rest.len())..]; + let path = &path[..path.find(['?', '#']).unwrap_or(path.len())]; + let name = &path[path.rfind(['/', '\\']).map_or(0, |i| i + 1)..]; + Some(name[..name.rfind('.').unwrap_or(name.len())].to_owned()) +} + +/// `SkinManager.TextureCache.registerTexture`: the texture id of a skin, +/// `skins/` and the SHA-1 of its hash's UTF-16 code units. +pub fn skin_location(hash: &str) -> String { + let units: Vec = hash.encode_utf16().flat_map(u16::to_le_bytes).collect(); + let digest = sha1(&units); + let mut out = String::from("skins/"); + for b in digest { + out.push_str(&format!("{b:02x}")); + } + out +} + +/// Where a texture download stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Download { + Ready, + Pending, + Failed, +} + +/// `MinecraftProfileTexture.Type`: which texture cache a download is in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Skin, + Cape, + Elytra, +} + +/// `SkinManager.createLookup(profile, requireSecure).get()`: the skin +/// texture a player shows, or `None` for their default skin. `download` +/// tells how the skin, cape and elytra texture downloads stand. +pub fn lookup( + textures: &Textures, + require_secure: bool, + mut download: impl FnMut(Kind, &str) -> Download, +) -> Option { + let mut skin = None; + let mut state = Download::Ready; + let urls = [ + (Kind::Skin, &textures.skin), + (Kind::Cape, &textures.cape), + (Kind::Elytra, &textures.elytra), + ]; + for (kind, url) in urls { + let Some(url) = url else { continue }; + // registerTexture computes the hash first; a bad URL fails the lookup. + let hash = texture_hash(url)?; + if kind == Kind::Skin { + skin = Some(skin_location(&hash)); + } + match download(kind, url) { + Download::Failed => return None, + Download::Pending => state = Download::Pending, + Download::Ready => {} + } + } + if state != Download::Ready || require_secure && !textures.signed { + return None; + } + skin +} + +/// `SkinTextureDownloader.processLegacySkin` on RGBA pixels: 64x32 skins +/// get the 64x64 layout, and the opaque parts lose their alpha. `None` for +/// any other size (the download fails). +pub fn process_legacy_skin(width: u32, height: u32, rgba: &[u8]) -> Option> { + if width != 64 || height != 32 && height != 64 { + return None; + } + let legacy = height == 32; + let mut img = vec![0u8; 64 * 64 * 4]; + let n = rgba.len().min(img.len()); + img[..n].copy_from_slice(&rgba[..n]); + let at = |x: i32, y: i32| ((y * 64 + x) * 4) as usize; + if legacy { + let rects = [ + (4, 16, 16, 32, 4, 4), + (8, 16, 16, 32, 4, 4), + (0, 20, 24, 32, 4, 12), + (4, 20, 16, 32, 4, 12), + (8, 20, 8, 32, 4, 12), + (12, 20, 16, 32, 4, 12), + (44, 16, -8, 32, 4, 4), + (48, 16, -8, 32, 4, 4), + (40, 20, 0, 32, 4, 12), + (44, 20, -8, 32, 4, 12), + (48, 20, -16, 32, 4, 12), + (52, 20, -8, 32, 4, 12), + ]; + for (sx, sy, ox, oy, w, h) in rects { + for y in 0..h { + for x in 0..w { + let (s, d) = (at(sx + x, sy + y), at(sx + ox + w - 1 - x, sy + oy + y)); + let p: [u8; 4] = img[s..s + 4].try_into().unwrap(); + img[d..d + 4].copy_from_slice(&p); + } + } + } + } + let no_alpha = |img: &mut Vec, x0: i32, y0: i32, x1: i32, y1: i32| { + for x in x0..x1 { + for y in y0..y1 { + img[at(x, y) + 3] = 255; + } + } + }; + no_alpha(&mut img, 0, 0, 32, 16); + if legacy { + // doNotchTransparencyHack: a fully opaque hat layer is cleared. + let opaque = (32..64).all(|x| (0..32).all(|y| img[at(x, y) + 3] >= 128)); + if opaque { + for x in 32..64 { + for y in 0..32 { + img[at(x, y) + 3] = 0; + } + } + } + } + no_alpha(&mut img, 0, 16, 64, 32); + no_alpha(&mut img, 16, 48, 48, 64); + Some(img) +} + +/// `SkinTextureDownloader`: fetches textures on background threads, from +/// the local cache (`/<2 hex>/`) or over HTTP, keeping each one +/// by kind and hash as vanilla's `TextureCache`s do. Plain HTTP only: an +/// `https` texture that isn't cached fails, and the player keeps their +/// default skin. +pub struct Downloader { + root: std::path::PathBuf, + states: std::collections::HashMap<(Kind, String), Download>, + done: std::sync::mpsc::Receiver<((Kind, String), Option>)>, + send: std::sync::mpsc::Sender<((Kind, String), Option>)>, + ready: Vec<(String, Vec)>, +} +impl Downloader { + pub fn new(root: std::path::PathBuf) -> Self { + let (send, done) = std::sync::mpsc::channel(); + Self { + root, + states: Default::default(), + done, + send, + ready: Vec::new(), + } + } + /// How the download of `url` stands, starting it the first time. + pub fn state(&mut self, kind: Kind, url: &str) -> Download { + while let Ok((key, image)) = self.done.try_recv() { + let state = match image { + Some(rgba) => { + if key.0 == Kind::Skin { + self.ready.push((skin_location(&key.1), rgba)); + } + Download::Ready + } + None => Download::Failed, + }; + self.states.insert(key, state); + } + let Some(hash) = texture_hash(url) else { + return Download::Failed; + }; + let key = (kind, hash); + if let Some(state) = self.states.get(&key) { + return *state; + } + self.states.insert(key.clone(), Download::Pending); + let digest: String = skin_location(&key.1)["skins/".len()..].to_owned(); + let file = self + .root + .join(if digest.len() > 2 { &digest[..2] } else { "xx" }) + .join(&digest); + let (url, send) = (url.to_owned(), self.send.clone()); + std::thread::spawn(move || { + let bytes = std::fs::read(&file).ok().or_else(|| { + let body = http_get(&url)?; + let _ = std::fs::create_dir_all(file.parent()?); + let _ = std::fs::write(&file, &body); + Some(body) + }); + let image = bytes + .and_then(|b| crate::hud::decode_bytes(&b).ok()) + .and_then(|(w, h, rgba)| match kind { + Kind::Skin => process_legacy_skin(w, h, &rgba), + _ => Some(rgba), + }); + let _ = send.send((key, image)); + }); + Download::Pending + } + /// Skins that finished since the last call: texture id and 64x64 RGBA. + pub fn take_ready(&mut self) -> Vec<(String, Vec)> { + std::mem::take(&mut self.ready) + } +} + +/// A plain HTTP/1.1 GET; the body of a 2xx answer. +fn http_get(url: &str) -> Option> { + use std::io::{Read, Write}; + let rest = url.strip_prefix("http://")?; + let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + let path = if path.is_empty() { "/" } else { path }; + let path = &path[..path.find('#').unwrap_or(path.len())]; + let host = authority.split(':').next()?; + let address = if authority.contains(':') { + authority.to_owned() + } else { + format!("{authority}:80") + }; + let timeout = std::time::Duration::from_secs(15); + let addr = std::net::ToSocketAddrs::to_socket_addrs(&address) + .ok()? + .next()?; + let mut stream = std::net::TcpStream::connect_timeout(&addr, timeout).ok()?; + stream.set_read_timeout(Some(timeout)).ok()?; + write!( + stream, + "GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: Java\r\n\r\n" + ) + .ok()?; + let mut response = Vec::new(); + stream.take(16 << 20).read_to_end(&mut response).ok()?; + let split = response.windows(4).position(|w| w == b"\r\n\r\n")?; + let head = String::from_utf8_lossy(&response[..split]).to_ascii_lowercase(); + let mut body = response[split + 4..].to_vec(); + let status: u32 = head.split_whitespace().nth(1)?.parse().ok()?; + if status / 100 != 2 { + return None; + } + if head.contains("transfer-encoding: chunked") { + let (mut out, mut at) = (Vec::new(), 0); + loop { + let end = at + body[at..].windows(2).position(|w| w == b"\r\n")?; + let line = String::from_utf8_lossy(&body[at..end]); + let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?; + if size == 0 { + break; + } + out.extend_from_slice(body.get(end + 2..end + 2 + size)?); + at = end + 4 + size; + } + body = out; + } + Some(body) +} + +/// SHA-1 (FIPS 180-4). +pub fn sha1(data: &[u8]) -> [u8; 20] { + let mut h: [u32; 5] = [ + 0x6745_2301, + 0xEFCD_AB89, + 0x98BA_DCFE, + 0x1032_5476, + 0xC3D2_E1F0, + ]; + let mut msg = data.to_vec(); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend((data.len() as u64 * 8).to_be_bytes()); + for block in msg.chunks_exact(64) { + let mut w = [0u32; 80]; + for (i, word) in block.chunks_exact(4).enumerate() { + w[i] = u32::from_be_bytes(word.try_into().unwrap()); + } + for i in 16..80 { + w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1); + } + let [mut a, mut b, mut c, mut d, mut e] = h; + for (i, wi) in w.iter().enumerate() { + let (f, k) = match i { + 0..=19 => ((b & c) | (!b & d), 0x5A82_7999), + 20..=39 => (b ^ c ^ d, 0x6ED9_EBA1), + 40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC), + _ => (b ^ c ^ d, 0xCA62_C1D6), + }; + let t = a + .rotate_left(5) + .wrapping_add(f) + .wrapping_add(e) + .wrapping_add(k) + .wrapping_add(*wi); + e = d; + d = c; + c = b.rotate_left(30); + b = a; + a = t; + } + for (x, y) in h.iter_mut().zip([a, b, c, d, e]) { + *x = x.wrapping_add(y); + } + } + let mut out = [0u8; 20]; + for (i, x) in h.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&x.to_be_bytes()); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sha1_and_base64() { + let hex: String = sha1(b"abc").iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(hex, "a9993e364706816aba3e25717850c26c9cd0d89d"); + assert_eq!(base64_decode("aGk=").unwrap(), b"hi"); + assert_eq!(base64_decode("aGk").unwrap(), b"hi"); + assert!(base64_decode("a").is_none()); + assert!(base64_decode("aGk=x").is_none()); + assert_eq!( + texture_hash("http://textures.minecraft.net/texture/abc.png?x=1").unwrap(), + "abc" + ); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSkinImageOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSkinImageOracle.java new file mode 100644 index 000000000..0ecdfe047 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSkinImageOracle.java @@ -0,0 +1,47 @@ +package dev.horizonlab.parity; + +import com.mojang.blaze3d.platform.NativeImage; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.Base64; +import net.minecraft.client.renderer.texture.SkinTextureDownloader; + +/** + * Decodes downloaded skin PNGs as vanilla does (NativeImage.read) and runs + * SkinTextureDownloader.processLegacySkin on them: 64x32 skins get the 64x64 + * layout, opaque parts lose their alpha, other sizes are refused. + * + * Input lines: base64 PNG. Output lines: base64 RGBA pixels of the result, + * or "refused". + */ +public final class VanillaSkinImageOracle { + public static void main(String[] args) throws Exception { + Method process = SkinTextureDownloader.class.getDeclaredMethod("processLegacySkin", NativeImage.class, String.class); + process.setAccessible(true); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + String result; + try { + var image = (NativeImage) process.invoke(null, NativeImage.read(Base64.getDecoder().decode(line)), "case"); + var pixels = new byte[image.getWidth() * image.getHeight() * 4]; + for (int y = 0, i = 0; y < image.getHeight(); y++) { + for (int x = 0; x < image.getWidth(); x++) { + int argb = image.getPixel(x, y); + pixels[i++] = (byte) (argb >> 16); + pixels[i++] = (byte) (argb >> 8); + pixels[i++] = (byte) argb; + pixels[i++] = (byte) (argb >>> 24); + } + } + image.close(); + result = Base64.getEncoder().encodeToString(pixels); + } catch (java.lang.reflect.InvocationTargetException e) { + result = "refused"; + } + out.append(result).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java index 006928728..b48d45041 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java @@ -2,6 +2,22 @@ package dev.horizonlab.parity; import com.google.gson.*; import com.mojang.authlib.GameProfile; +import com.mojang.authlib.minecraft.MinecraftProfileTexture; +import com.mojang.authlib.properties.Property; +import com.mojang.authlib.properties.PropertyMap; +import com.mojang.authlib.services.MinecraftServicesDiscoveryService; +import com.mojang.authlib.services.MinecraftServicesSessionService; +import com.mojang.authlib.services.ServicesKeyInfo; +import com.mojang.authlib.services.ServicesKeySet; +import com.mojang.authlib.services.response.discovery.Discovery; +import com.mojang.authlib.services.response.discovery.DiscoveryResponse; +import com.mojang.authlib.services.response.discovery.Endpoint; +import com.mojang.authlib.services.response.discovery.Endpoints; +import java.util.concurrent.CompletableFuture; +import net.minecraft.client.renderer.texture.SkinTextureDownloader; +import net.minecraft.client.resources.SkinManager; +import net.minecraft.core.ClientAsset; +import net.minecraft.server.Services; import com.mojang.renderpearl.api.pipeline.RenderPipeline; import com.mojang.serialization.JsonOps; import java.lang.reflect.*; @@ -47,6 +63,9 @@ import net.minecraft.world.scores.criteria.ObjectiveCriteria; * Visibility changes clear the heart states as setVisible does (without * the narration). * + * Profiles may carry a signed or unsigned `textures` property; a real + * SkinManager (see skinManager) decides each face's texture. + * * Input lines: case JSON. Output lines: {case, frames:[[draws]...]} or {case, error}. */ public final class VanillaTabListOracle { @@ -106,6 +125,47 @@ public final class VanillaTabListOracle { }; } + /** + * A real SkinManager over a real MinecraftServicesSessionService whose + * discovery lists the case's texture URIs and whose profile property key + * accepts the signature "valid". Downloads succeed, fail or never finish + * by texture hash, as the case says. + */ + static SkinManager skinManager(JsonObject c) throws Exception { + var uris = new ArrayList(); + for (var u : c.getAsJsonArray("validUris")) uris.add(u.getAsString()); + var endpoints = new Endpoints(Map.of("getTexture", new Endpoint(null, uris))); + var response = new DiscoveryResponse("prod", "minecraft", new Discovery("minecraft", Endpoints.empty(), Endpoints.empty(), Endpoints.empty(), endpoints, Endpoints.empty())); + var dc = MinecraftServicesDiscoveryService.class.getDeclaredConstructor(java.net.Proxy.class, boolean.class, java.util.function.Supplier.class); + dc.setAccessible(true); + var discovery = dc.newInstance(java.net.Proxy.NO_PROXY, false, (java.util.function.Supplier) () -> response); + var key = (ServicesKeyInfo) Proxy.newProxyInstance(ServicesKeyInfo.class.getClassLoader(), new Class[] {ServicesKeyInfo.class}, + (proxy, method, a) -> switch (method.getName()) { + case "validateProperty" -> "valid".equals(((Property) a[0]).signature()); + case "keyBitCount" -> 4096; + default -> throw new UnsupportedOperationException(method.getName()); + }); + ServicesKeySet keys = type -> List.of(key); + var sc = MinecraftServicesSessionService.class.getDeclaredConstructor(ServicesKeySet.class, java.net.Proxy.class, MinecraftServicesDiscoveryService.class); + sc.setAccessible(true); + var session = sc.newInstance(keys, java.net.Proxy.NO_PROXY, discovery); + var downloads = c.getAsJsonObject("downloads"); + var downloader = new SkinTextureDownloader(java.net.Proxy.NO_PROXY, null, Runnable::run) { + @Override + public CompletableFuture downloadAndRegisterSkin(Identifier textureId, Path localCopy, String url, boolean processLegacySkin) { + String hash = new MinecraftProfileTexture(url, Map.of()).getHash(); + String state = downloads.has(hash) ? downloads.get(hash).getAsString() : "ok"; + return switch (state) { + case "ok" -> CompletableFuture.completedFuture(new ClientAsset.DownloadedTexture(textureId, url)); + case "pending" -> new CompletableFuture<>(); + default -> CompletableFuture.failedFuture(new java.io.IOException("download failed")); + }; + } + }; + var services = new Services(session, keys, null, null, null); + return new SkinManager(Path.of("skins"), services, downloader, Runnable::run); + } + /** Records GuiGraphicsExtractor calls. */ public static final class Capture extends GuiGraphicsExtractor { private Capture() { super(null, null, 0, 0); } @@ -219,18 +279,35 @@ public final class VanillaTabListOracle { var player = alloc(LocalPlayer.class); put(player, LocalPlayer.class, "connection", connection); put(mc, Minecraft.class, "player", player); + var user = alloc(net.minecraft.client.User.class); + put(user, net.minecraft.client.User.class, "uuid", c.get("local").isJsonNull() ? new UUID(0, 0) : UUID.fromString(c.get("local").getAsString())); + put(mc, Minecraft.class, "user", user); + var skins = skinManager(c); + put(mc, Minecraft.class, "skinManager", skins); for (var p : c.getAsJsonArray("players")) { var o = p.getAsJsonObject(); var uuid = UUID.fromString(o.get("uuid").getAsString()); - var profile = new GameProfile(uuid, o.get("name").getAsString()); + var properties = com.google.common.collect.LinkedHashMultimap.create(); + if (o.has("textures") && !o.get("textures").isJsonNull()) { + var t = o.getAsJsonObject("textures"); + var sig = t.get("signature"); + properties.put("textures", sig.isJsonNull() + ? new Property("textures", t.get("value").getAsString()) + : new Property("textures", t.get("value").getAsString(), sig.getAsString())); + } + var profile = new GameProfile(uuid, o.get("name").getAsString(), new PropertyMap(properties)); + // Let the lookup's unpacking and downloads run before the first frame, + // as they would have by the time a player list shows. + try { + skins.get(profile).get(1, java.util.concurrent.TimeUnit.SECONDS); + } catch (java.util.concurrent.TimeoutException pending) { + } var info = new PlayerInfo(profile, false); put(info, PlayerInfo.class, "gameMode", GameType.byId(o.get("gameMode").getAsInt())); put(info, PlayerInfo.class, "latency", o.get("latency").getAsInt()); if (!o.get("displayName").isJsonNull()) info.setTabListDisplayName(component(o.get("displayName"))); info.setTabListOrder(o.get("listOrder").getAsInt()); info.setShowHat(o.get("showHat").getAsBoolean()); - var skin = net.minecraft.client.resources.DefaultPlayerSkin.get(uuid); - put(info, PlayerInfo.class, "skinLookup", (java.util.function.Supplier) () -> skin); listed.add(info); if (o.get("inLevel").getAsBoolean()) { var entity = alloc(RemotePlayer.class); diff --git a/tools/test_tab_list_parity.py b/tools/test_tab_list_parity.py index 495049948..713da626c 100644 --- a/tools/test_tab_list_parity.py +++ b/tools/test_tab_list_parity.py @@ -4,7 +4,8 @@ The Java oracle (VanillaTabListOracle) runs vanilla's own PlayerTabOverlay.extractRenderState, frame after frame, on a stand-in client whose connection lists the case's players (game mode, latency, display name, -list order, hat layer, online mode for heads), whose level holds some of +list order, hat layer, online mode for heads, skins from each profile's signed or +unsigned `textures` property through a real SkinManager), whose level holds some of them (upside-down Dinnerbone and Grumm) and whose real Scoreboard has the case's teams (colour, prefix, suffix), `list` objective (integer or hearts, number formats) and scores, with the header, footer, row background option @@ -12,9 +13,16 @@ and Hud ticks. It records every fill, text (as styled runs), sprite and face blit. `examples/tab_list_fixture` lays out the same frames with `horizon_client::tab_list`; the ordered call lists must agree. +Downloaded skin images are compared too: VanillaSkinImageOracle decodes +PNGs as NativeImage does and runs SkinTextureDownloader.processLegacySkin; +`examples/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. + test_tab_list_parity.py [--count N] [--detail N] """ import argparse +import base64 +import struct +import zlib import json import os import random @@ -68,6 +76,45 @@ def number_format(rng): return {'type': 'fixed', 'value': component(rng, 1)} +TEXTURE_URIS = ['https://textures.minecraft.net/texture/{textureId}', 'http://textures.minecraft.net/texture/{textureId}'] + + +def textures_property(rng, name, hashes): + """A `textures` profile property: base64 JSON naming skin, cape and + elytra URLs (some outside the allowed domains or malformed), signed + validly, invalidly or not at all.""" + def url(): + h = rng.choice(hashes) + return rng.choice([ + 'http://textures.minecraft.net/texture/' + h, 'https://textures.minecraft.net/texture/' + h, + 'http://textures.minecraft.net/texture/' + h + '.png', 'https://textures.minecraft.net/texture/' + h + '?v=2', + 'https://evil.example.net/texture/' + h, 'http://textures.minecraft.net.evil/texture/' + h, + 'http://textures.minecraft.net/texture/a/b/' + h + '#frag']) + textures = {} + if rng.random() < 0.9: + textures['SKIN'] = {'url': url()} + if rng.random() < 0.4: + textures['SKIN']['metadata'] = {'model': 'slim'} + if rng.random() < 0.25: + textures['CAPE'] = {'url': url()} + if rng.random() < 0.08: + textures['ELYTRA'] = {'url': url()} + if rng.random() < 0.03: + textures['SKIN'] = {} + payload = {'timestamp': rng.randint(0, 2**41), 'profileId': uuid.UUID(int=rng.getrandbits(128)).hex, + 'profileName': name, 'textures': textures} + if rng.random() < 0.2: + payload['signatureRequired'] = True + text = rng.choice([json.dumps(payload)] * 12 + ['not json', 'null', '', '{"textures": {}}', '[1, 2]']) + value = base64.b64encode(text.encode()).decode() + kind = rng.random() + if kind < 0.05: + value = value.rstrip('=') + elif kind < 0.08: + value = rng.choice(['%%%', 'abc', 'YQ==YQ==', value + '!']) + return {'value': value, 'signature': rng.choice([None, 'valid', 'valid', 'invalid'])} + + def cases(count): rng = random.Random(0x544142) out = [] @@ -79,6 +126,7 @@ def cases(count): rng.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') for _ in range(rng.randint(1, 16))) if name.lower() not in {x.lower() for x in names}: names.append(name) + hashes = [''.join(rng.choice('0123456789abcdef') for _ in range(64)) for _ in range(rng.randint(1, 12))] players = [] for name in names: players.append({ @@ -88,7 +136,9 @@ def cases(count): 'displayName': component(rng, rng.randint(1, 2)) if rng.random() < 0.2 else None, 'listOrder': rng.choice([0, 0, 0, 1, -1, 5, 2147483647, -2147483648]), 'showHat': rng.random() < 0.8, 'inLevel': rng.random() < 0.5, + 'textures': textures_property(rng, name, hashes) if rng.random() < 0.75 else None, }) + downloads = {h: rng.choice(['ok'] * 20 + ['fail'] * 3 + ['pending']) for h in hashes if rng.random() < 0.9} teams = [] for t in range(rng.choice([0, 0, 1, 2, 4])): members = [p['name'] for p in players if rng.random() < 0.3] @@ -125,7 +175,45 @@ def cases(count): out.append({'width': rng.choice([427, 320, 480, 640, 961, 160, 90, 300]), 'onlineMode': rng.random() < 0.7, 'backgroundForChatOnly': rng.random() < 0.8, 'opacity': rng.choice([0.5, 0.0, 1.0, 0.37]), 'header': header, 'footer': footer, 'teams': teams, 'objective': objective, 'players': players, - 'frames': frames}) + 'frames': frames, 'downloads': downloads, + 'local': rng.choice(players)['uuid'] if rng.random() < 0.3 else None, + 'validUris': rng.choice([TEXTURE_URIS] * 6 + [TEXTURE_URIS[:1], []])}) + return out + + +def png(width, height, color_type, depth, rows): + """A PNG of the given colour type (0 grey, 2 RGB, 4 grey+alpha, 6 RGBA).""" + def chunk(kind, data): + return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) + raw = b''.join(b'\0' + row for row in rows) + return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, depth, color_type, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b'')) + + +def skin_images(count): + """Downloaded skins: 64x32 legacy and 64x64 ones in every 8-bit colour + type (and 16-bit RGBA), with opaque, clear and mixed hat layers, and a + few sizes vanilla refuses.""" + rng = random.Random(0x534B494E) + out = [] + for _ in range(count): + width, height = rng.choice([(64, 32)] * 5 + [(64, 64)] * 5 + [(32, 32), (64, 48), (128, 64), (64, 128), (1, 1)]) + color_type, depth = rng.choice([(6, 8)] * 6 + [(2, 8), (0, 8), (4, 8), (6, 16)]) + channels = {0: 1, 2: 3, 4: 2, 6: 4}[color_type] + alpha = rng.choice(['opaque', 'clear', 'mixed', 'random']) + rows = [] + for y in range(height): + row = bytearray() + for x in range(width): + px = [rng.randrange(256) for _ in range(channels)] + if color_type in (4, 6): + a = {'opaque': rng.randint(128, 255), 'clear': 0, 'mixed': rng.choice([0, 255, 127, 128]), + 'random': rng.randrange(256)}[alpha] + px[-1] = a + for v in px: + row += bytes([v, rng.randrange(256)]) if depth == 16 else bytes([v]) + rows.append(bytes(row)) + out.append(base64.b64encode(png(width, height, color_type, depth, rows)).decode()) return out @@ -133,6 +221,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', type=int, default=1000) parser.add_argument('--detail', type=int, default=3) + parser.add_argument('--images', type=int, default=400) args = parser.parse_args() lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() @@ -149,11 +238,30 @@ def main(): if result.returncode: print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, - *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle'))], 'compile-java') + *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle', 'VanillaSkinImageOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'tab_list_fixture', '--', resources, inputs, build / 'rust.jsonl'], 'rust') + images = build / 'skins.txt'; images.write_text(''.join(i + '\n' for i in skin_images(args.images))) + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSkinImageOracle', + images, build / 'vanilla-skins.txt'], 'vanilla-skins') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'skin_image_fixture', '--', + images, build / 'rust-skins.txt'], 'rust-skins') + vanilla_skins = (build / 'vanilla-skins.txt').read_text().splitlines() + rust_skins = (build / 'rust-skins.txt').read_text().splitlines() + assert len(vanilla_skins) == len(rust_skins) == args.images + skin_bad = [i for i, (a, b) in enumerate(zip(vanilla_skins, rust_skins)) if a != b] + for i in skin_bad[:args.detail]: + a, b = vanilla_skins[i], rust_skins[i] + if 'refused' in (a, b): + print(f'SKIN MISMATCH image {i}: vanilla {a[:20]}, horizon {b[:20]}') + else: + a, b = base64.b64decode(a), base64.b64decode(b) + k = next(k for k in range(min(len(a), len(b))) if a[k] != b[k]) // 4 + print(f'SKIN MISMATCH image {i}: pixel ({k % 64}, {k // 64}) vanilla {a[k*4:k*4+4].hex()} horizon {b[k*4:k*4+4].hex()}') + print(f'{args.images - len(skin_bad)}/{args.images} processed skin images match ' + f'({sum(v == "refused" for v in vanilla_skins)} refused)') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) @@ -175,7 +283,7 @@ def main(): print(f' frame {i}, call {k} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}') print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} player lists match ({frames} frames, {calls} calls); ' f'{len(errors)} oracle errors') - if bad or errors: + if bad or errors or skin_bad: sys.exit(1) print('tab list parity ok') From 585a41acfaf28de09e2463a2357d3a841e45c160 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:17:04 +0200 Subject: [PATCH 05/18] Satisfy clippy in the SHA-1 helper Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/skins.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index acacf7520..ef8d575c3 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -383,10 +383,10 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { msg.push(0); } msg.extend((data.len() as u64 * 8).to_be_bytes()); - for block in msg.chunks_exact(64) { + for block in msg.as_chunks::<64>().0 { let mut w = [0u32; 80]; - for (i, word) in block.chunks_exact(4).enumerate() { - w[i] = u32::from_be_bytes(word.try_into().unwrap()); + for (i, word) in block.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*word); } for i in 16..80 { w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1); From a9fa46fd0ad5859af1837ab7705dbf27102077a3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:40:13 +0200 Subject: [PATCH 06/18] Run the copper golem on CopperGolemAi's brain and compare its chest sorting The golem's goals are replaced by vanilla's brain (core and idle activities, the transport cooldown, look-at-player-sometimes, stroll or wait), and TransportItemsBetweenContainers moves into the library: nearest wanted chest in chunk and block entity map order, queueing behind golems with a chest open, the 60-tick interaction with its states, sounds and opener counts, picking up and putting down (with vanilla's overcounting), visited and unreachable positions. Weathering draws from the level random after the living tick; the spin sound is client-local. mob_ai gains seven copper golem scenarios that print each golem's state, hand and opened chest and every chest's contents and openers; all match vanilla. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 104 ++- crates/horizon-client/src/game.rs | 5 +- .../horizon-client/src/game/copper_golems.rs | 762 +++------------- crates/horizon-client/src/game/creatures.rs | 6 + crates/horizon-client/src/mobs.rs | 24 + crates/horizon-client/src/mobs/ai.rs | 11 +- .../horizon-client/src/mobs/animal_brain.rs | 227 ++++- .../horizon-client/src/mobs/copper_golem.rs | 172 ++-- .../src/mobs/transport_items.rs | 827 ++++++++++++++++++ crates/horizon-client/src/mobs/world.rs | 32 + crates/horizon-client/src/world.rs | 4 + .../horizonlab/parity/VanillaMobAiOracle.java | 54 +- tools/test_mob_ai_parity.py | 31 +- 13 files changed, 1495 insertions(+), 764 deletions(-) create mode 100644 crates/horizon-client/src/mobs/transport_items.rs diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 729ac88f1..528f7e540 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -10,7 +10,7 @@ use horizon_client::{ chunk::{Chunk, HEIGHT, MIN_Y}, collisions, containers::{BlockEntity, CreakingHeart}, - items::Items, + items::{ItemStack, Items}, light::{LightTables, light_chunk}, mobs::{ Damage, MobType, creaking, @@ -87,7 +87,9 @@ fn parse(text: &str) -> Vec { } } "origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()], - "fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()), + "fill" | "block" | "chest" => { + s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()) + } "heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()), "hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())), "player" => { @@ -559,6 +561,14 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { if m.species() == Species::Villager { let _ = write!(out, "\tvx {}", villager(m)); } + if m.species() == Species::CopperGolem { + let held = horizon_client::mobs::transport_items::held(m).map_or("-".into(), stack); + let opened = m + .extra + .opened_chest + .map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2])); + let _ = write!(out, "\tcg {} {held} {opened}", m.extra.variant3); + } out.push('\n'); } @@ -696,8 +706,23 @@ fn main() -> horizon_client::Result<()> { } for b in &s.blocks { let n = |i: usize| b[i].parse::().unwrap(); - if b[0] == "block" { + if b[0] == "block" || b[0] == "chest" { world.set(n(1), n(2), n(3), state(registry, &b[4]))?; + if b[0] == "chest" { + // chest X Y Z STATE SLOTS: item*count or - per slot. + let mut slots = vec![None; 27]; + for (k, item) in b.get(5).map_or("", String::as_str).split(',').enumerate() { + if let Some((id, count)) = item.split_once('*') { + slots[k] = Some(ItemStack::new( + &format!("minecraft:{id}"), + count.parse().unwrap(), + )); + } + } + world + .block_entities + .insert((n(1), n(2), n(3)), BlockEntity::Chest(slots)); + } } else { let st = state(registry, &b[7]); for x in n(1).min(n(4))..=n(1).max(n(4)) { @@ -766,6 +791,14 @@ fn main() -> horizon_client::Result<()> { "tame" => m.extra.tame = true, x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(), x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(), + x if x.starts_with("hand=") => { + let (id, count) = x[5..].split_once('*').unwrap(); + let stack = + ItemStack::new(&format!("minecraft:{id}"), count.parse().unwrap()); + horizon_client::mobs::transport_items::set_held(&mut m, Some(stack)); + } + // Set once the brain exists (below). + x if x.starts_with("cooldown=") => {} "leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player), x if x.starts_with("leashto=") => { let n: u32 = x[8..].parse().unwrap(); @@ -794,6 +827,12 @@ fn main() -> horizon_client::Result<()> { if horizon_client::mobs::animal_brain::kind_of(&m).is_some() { horizon_client::mobs::animal_brain::init(&mut m, spec.seed); } + if let Some(c) = spec.flags.iter().find_map(|f| f.strip_prefix("cooldown=")) { + horizon_client::mobs::animal_brain::set_transport_cooldown( + &mut m, + c.parse().unwrap(), + ); + } mobs.push(m); } let mut player = s.player.map(|p| { @@ -854,6 +893,7 @@ fn main() -> horizon_client::Result<()> { world_seed: 0, // FlatLevelSource.getSeaLevel. sea_level: -63, + items: Some(&items), } }; } @@ -964,6 +1004,36 @@ fn main() -> horizon_client::Result<()> { &mut born, s.time, ); + // What a copper golem did to chests, before the next mob ticks. + for e in &events[from.min(events.len())..] { + match e { + MobEvent::ChestOpen { chest, open } => { + let o = world + .chest_openers + .entry((chest[0], chest[1], chest[2])) + .or_insert((0, 0.0)); + if *open { + o.0 += 1; + o.1 = o.1.max(3.0); + } else { + o.0 -= 1; + if o.0 == 0 { + o.1 = 0.0; + } + } + } + MobEvent::ChestSlot { chest, slot, stack } => { + if let Some(e) = world + .block_entities + .get_mut(&(chest[0], chest[1], chest[2])) + && let Some(sl) = e.slots_mut().get_mut(*slot) + { + *sl = stack.clone(); + } + } + _ => {} + } + } // ServerLevel ticks entities one after another: the ones // after this mob see it as it is now. if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { @@ -1033,6 +1103,34 @@ fn main() -> horizon_client::Result<()> { for (at, h) in &hearts { print_heart(&mut out, t, registry, &world, *at, h, &scratch); } + for b in s.blocks.iter().filter(|b| b[0] == "chest") { + let n = |i: usize| b[i].parse::().unwrap(); + let key = (n(1), n(2), n(3)); + let Some(e) = world.block_entities.get(&key) else { + continue; + }; + let mut slots: Vec = e + .slots() + .iter() + .map(|s| s.as_ref().map_or("-".into(), stack)) + .collect(); + while slots.last().is_some_and(|s| s == "-") { + slots.pop(); + } + let count = world.chest_openers.get(&key).map_or(0, |o| o.0); + let _ = writeln!( + out, + "{t} chest {},{},{} {} {count}", + key.0 - s.origin[0], + key.1, + key.2 - s.origin[1], + if slots.is_empty() { + "-".into() + } else { + slots.join(",") + } + ); + } for line in traces { let _ = writeln!(out, "{line}"); } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2b4521e34..ed93ebf36 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -755,8 +755,6 @@ struct Game<'a> { ender_open: Option<(i32, i32, i32)>, /// Block entity data of broken blocks waiting for their dropped item. pending: spill::Pending, - /// The chest each copper golem has open (`CopperGolem.openedChestPos`). - golem_openers: HashMap, /// Item entities spawned and block entities removed while the block /// behaviour ran (spilled contents, popped resources). spill: spill::Spill, @@ -2816,7 +2814,7 @@ impl Game<'_> { self.spawn_loaded_entities(); if running { self.tick_mobs()?; - self.tick_copper_golems(); + self.recheck_golem_openers(); self.tick_experience(); } self.tick_lan(); @@ -8390,7 +8388,6 @@ pub fn run() -> Result<()> { ender_items: vec![None; 27], ender_open: None, pending: Default::default(), - golem_openers: HashMap::new(), spill: Default::default(), recipe_ui: Default::default(), mount_menu: Default::default(), diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 209b2078d..59cc3c8b7 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -1,177 +1,151 @@ -//! Copper golems on the game side: `TransportItemsBetweenContainers` (carry -//! items from copper chests to ordinary chests), weathering and turning into -//! statues, and the hand-over, waxing, scraping and shearing interactions. +//! Copper golems on the game side: what their brain (`mobs::transport_items`) +//! does to chests (opener counts, the lid block events, slots), the openers +//! recheck, turning into statues, and the hand-over, waxing, scraping and +//! shearing interactions. use super::Game; use horizon_client::{ - containers::BlockEntity, items::ItemStack, - mobs::{Mob, Species, copper_golem as cg, goals::should_panic}, + mobs::{ + Mob, Species, + transport_items::{held, set_held}, + }, }; use horizon_core::random::RandomSource; use horizon_world::chunk::BlockState; -type Key = (i32, i32, i32); -/// `TransportItemState`. -const TRAVELLING: i32 = 0; -const QUEUING: i32 = 1; -const INTERACTING: i32 = 2; -/// `ContainerInteractionState` (0 = none). -const PICKUP_ITEM: i32 = 1; -const PICKUP_NO_ITEM: i32 = 2; -const PLACE_ITEM: i32 = 3; -const PLACE_NO_ITEM: i32 = 4; -/// Positions that were unreachable are kept in `positions` with this offset. -const UNREACHABLE: i32 = 1 << 20; -/// `TransportItemsBetweenContainers.VISITED_POSITIONS_MEMORY_TIME`. -const MEMORY_TICKS: i32 = 6000; - -/// Whether a block is a copper chest (the pick-up sources). -pub(super) fn is_copper_chest(name: &str) -> bool { - name.ends_with("copper_chest") -} -/// The held stack (`getMainHandItem`). -pub(super) fn held(m: &Mob) -> Option<&ItemStack> { - m.extra.items.first().and_then(Option::as_ref) -} -/// `setItemInHand(MAIN_HAND, ..)`, keeping the rendered copy in step. -pub(super) fn set_held(m: &mut Mob, stack: Option) { - let stack = stack.filter(|s| s.count > 0); - m.extra.main_hand = stack.as_ref().map(|s| s.item.clone()); - m.extra.ints[1] = stack.as_ref().map_or(0, |s| s.count as i32); - if m.extra.items.is_empty() { - m.extra.items.push(None); - } - m.extra.items[0] = stack; -} -fn visited(m: &Mob) -> Vec<[i32; 3]> { - m.extra - .positions - .iter() - .filter(|p| p[1] < UNREACHABLE) - .copied() - .collect() -} -fn blocked_list(m: &Mob) -> impl Iterator + '_ { - m.extra.positions.iter().map(|p| { - if p[1] >= UNREACHABLE { - [p[0], p[1] - UNREACHABLE, p[2]] - } else { - *p - } - }) -} -fn chest_center(h: [i32; 3]) -> [f64; 3] { - [ - f64::from(h[0]) + 0.5, - f64::from(h[1]) + 0.5, - f64::from(h[2]) + 0.5, - ] -} -/// The copper golem state the model, sounds and animations follow. -fn set_state(m: &mut Mob, state: u8) { - m.extra.variant3 = state; -} +/// `ContainerOpenersCounter.CHECK_TICK_DELAY`. +const RECHECK_TICKS: i64 = 5; impl Game<'_> { - pub(super) fn tick_copper_golems(&mut self) { - let ids: Vec = self - .mobs - .iter() - .filter(|m| m.species() == Species::CopperGolem && m.alive() && !m.removed) - .map(|m| m.id) - .collect(); - for id in ids { - let Some(i) = self.mobs.iter().position(|m| m.id == id) else { + /// A copper golem opened or closed a chest half: the counter changes and + /// the clients see the block event (`openerCountChanged`). + pub(super) fn golem_chest_open(&mut self, chest: [i32; 3], open: bool) { + let key = (chest[0], chest[1], chest[2]); + let entry = self.world.chest_openers.entry(key).or_insert((0, 0.0)); + if open { + entry.0 += 1; + entry.1 = entry.1.max(3.0); + } else { + entry.0 -= 1; + if entry.0 == 0 { + entry.1 = 0.0; + } + } + let count = entry.0; + if count <= 0 { + self.world.chest_openers.remove(&key); + } + self.block_entity_event(chest, 1, count.max(0)); + } + /// A copper golem took from or filled a chest slot. + pub(super) fn golem_chest_slot( + &mut self, + chest: [i32; 3], + slot: usize, + stack: Option, + ) { + if let Some(e) = self + .world + .block_entities + .get_mut(&(chest[0], chest[1], chest[2])) + && let Some(s) = e.slots_mut().get_mut(slot) + { + *s = stack; + } + } + /// `ContainerOpenersCounter.recheckOpeners` every five ticks: the golems + /// whose opened chest is this one, within its range plus 4; when none + /// is left the chest closes (a double chest the golem left open). + pub(super) fn recheck_golem_openers(&mut self) { + if self.world.game_time % RECHECK_TICKS != 0 { + return; + } + let open: Vec<(i32, i32, i32)> = self.world.chest_openers.keys().copied().collect(); + for key in open { + let p = [key.0, key.1, key.2]; + let other = self.chest_other_half(key).map(|o| [o.0, o.1, o.2]); + let range = self.world.chest_openers.get(&key).map_or(0.0, |o| o.1) + 4.0; + let area = horizon_core::geometry::Aabb::new( + horizon_core::geometry::Vec3::new( + f64::from(p[0]) - range, + f64::from(p[1]) - range, + f64::from(p[2]) - range, + ), + horizon_core::geometry::Vec3::new( + f64::from(p[0]) + 1.0 + range, + f64::from(p[1]) + 1.0 + range, + f64::from(p[2]) + 1.0 + range, + ), + ); + let count = self + .mobs + .iter() + .filter(|m| { + m.species() == Species::CopperGolem + && !m.removed + && m.extra + .opened_chest + .is_some_and(|o| o == p || Some(o) == other) + && m.bounds().intersects(area) + }) + .count() as i32; + let before = self.world.chest_openers.get(&key).map_or(0, |o| o.0); + if count == before { continue; - }; - let mut m = self.mobs[i].clone(); - self.copper_golem_step(&mut m); - if let Some(i) = self.mobs.iter().position(|x| x.id == id) { - self.mobs[i] = m; } - } - let alive: std::collections::HashSet = self.mobs.iter().map(|m| m.id).collect(); - self.golem_openers.retain(|id, _| alive.contains(id)); - } - fn copper_golem_step(&mut self, m: &mut Mob) { - if self.golem_weathering(m) { - return; - } - // CountDownCooldownTicks(TRANSPORT_ITEMS_COOLDOWN_TICKS). - if m.extra.scratch[3] > 0 { - m.extra.scratch[3] -= 1; - } - // The visited positions fade after 6000 ticks. - if m.extra.ints[2] > 0 && m.age as i32 >= m.extra.ints[2] { - m.extra.positions.clear(); - m.extra.ints[2] = 0; - } - let running = m.extra.scratch[3] <= 0 && !should_panic(m) && m.extra.leash.is_none(); - if !running { - if m.extra.home.is_some() || m.extra.scratch[0] != TRAVELLING { - self.golem_on_start_travelling(m); - m.extra.point = None; - m.ai.nav.stop(); + if count == 0 { + self.world.chest_openers.remove(&key); + self.golem_chest_sound(p, false); + } else if let Some(o) = self.world.chest_openers.get_mut(&key) { + o.0 = count; } - return; - } - let invalid = self.golem_update_invalid_target(m); - if m.extra.home.is_none() { - self.golem_on_start_travelling(m); - return; - } - if invalid { - return; - } - if m.extra.scratch[0] == QUEUING { - self.golem_on_queuing(m); - } - if m.extra.scratch[0] == TRAVELLING { - self.golem_on_travel(m); - } - if m.extra.scratch[0] == INTERACTING { - self.golem_on_reached(m); + self.block_entity_event(p, 1, count); } } - // ---- weathering ------------------------------------------------------- - /// `CopperGolem.updateWeathering`; true when it turned into a statue. - fn golem_weathering(&mut self, m: &mut Mob) -> bool { - let now = self.world.game_time; - let next = m.extra.vector[0] as i64; - if next == -2 { - return false; - } - // updateWeathering draws from the level random. - let r = &mut self.world.random; - let mut interval = || 504_000 + i64::from(r.next_int_bound(48_001).unwrap_or(0)); - if next == -1 { - m.extra.vector[0] = (now + interval()) as f64; - return false; - } - let fully = m.extra.variant >= 3; - if now >= next && !fully { - let new = cg::weather_next(m.extra.variant); - m.extra.variant = new; - m.extra.vector[0] = if new >= 3 { - 0.0 - } else { - (next + interval()) as f64 - }; - } - if fully && self.golem_can_turn_to_statue(m) { - self.golem_turn_to_statue(m); - return true; - } - false - } - fn golem_can_turn_to_statue(&mut self, m: &mut Mob) -> bool { - let p = [ - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, + /// `ChestBlockEntity.playSound` for a chest the recheck closed. + fn golem_chest_sound(&mut self, p: [i32; 3], open: bool) { + let name = self + .res + .facts + .get(self.world.block(p[0], p[1], p[2])) + .name + .clone(); + let base = name + .trim_start_matches("minecraft:") + .trim_start_matches("waxed_"); + let kind = if !base.ends_with("copper_chest") { + "chest" + } else if base.starts_with("weathered") { + "copper_chest_weathered" + } else if base.starts_with("oxidized") { + "copper_chest_oxidized" + } else { + "copper_chest" + }; + let side = if open { "open" } else { "close" }; + let at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, ]; - let at = self.world.block(p[0], p[1], p[2]); - self.res.facts.is_air(at) && self.world.random.next_float() <= 0.0058 + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play( + &format!("minecraft:block.{kind}.{side}"), + Some(at), + 0.5, + pitch, + ); + } + /// `CopperGolem.turnToStatue`, which its weathering asked for. + pub(super) fn golem_become_statue(&mut self, id: u32) { + let Some(i) = self.mobs.iter().position(|m| m.id == id) else { + return; + }; + let mut m = self.mobs[i].clone(); + self.golem_turn_to_statue(&mut m); + if let Some(i) = self.mobs.iter().position(|x| x.id == id) { + self.mobs[i] = m; + } } fn golem_turn_to_statue(&mut self, m: &mut Mob) { let pos = [ @@ -202,7 +176,7 @@ impl Game<'_> { return; } self.golem_drop_equipment(m); - self.golem_release(m); + m.extra.opened_chest = None; if m.extra.leash.is_some() { self.break_leash(m.id, true, false); m.extra.leash = None; @@ -229,450 +203,6 @@ impl Game<'_> { self.spawn_at_location(at, 0.0, antenna); } } - // ---- containers ------------------------------------------------------- - /// The block entities of the container at a chest, in slot order. - fn golem_container(&self, key: Key) -> Vec { - let Some(other) = self.chest_other_half(key) else { - return vec![key]; - }; - let right = self - .res - .assets - .registry - .state(self.world.block(key.0, key.1, key.2)) - .and_then(|s| s.properties.get("type")) - .is_some_and(|t| t == "right"); - if right { - vec![key, other] - } else { - vec![other, key] - } - } - fn golem_block_name(&self, key: Key) -> std::sync::Arc { - self.res - .facts - .get(self.world.block(key.0, key.1, key.2)) - .name - .clone() - } - fn golem_chest_blocked(&self, keys: &[Key]) -> bool { - keys.iter().any(|k| { - let above = self.world.block(k.0, k.1 + 1, k.2); - self.res.behaviours.facts(above).flags - & horizon_world::level::data::state_flags::CONDUCTOR - != 0 - }) - } - fn golem_slots(&self, keys: &[Key]) -> Vec> { - keys.iter() - .filter_map(|k| self.world.block_entities.get(k)) - .flat_map(|e| e.slots().to_vec()) - .collect() - } - fn golem_slot_mut(&mut self, keys: &[Key], mut n: usize) -> Option<&mut Option> { - for k in keys { - let len = self.world.block_entities.get(k)?.slots().len(); - if n < len { - return self.world.block_entities.get_mut(k)?.slots_mut().get_mut(n); - } - n -= len; - } - None - } - fn golem_max_stack(&self, stack: &ItemStack) -> u32 { - self.res - .items - .get(&stack.item) - .map_or(64, |i| i.max_stack) - .max(1) - } - /// `pickupItemFromContainer`: up to 16 of the first non-empty slot. - fn golem_pick_up(&mut self, keys: &[Key]) -> Option { - let slots = self.golem_slots(keys); - let (n, stack) = slots - .iter() - .enumerate() - .find_map(|(n, s)| s.as_ref().map(|s| (n, s.clone())))?; - let take = stack.count.min(16); - let slot = self.golem_slot_mut(keys, n)?; - let mut out = stack; - out.count = take; - match slot { - Some(s) if s.count > take => s.count -= take, - _ => *slot = None, - } - Some(out) - } - /// `addItemsToContainer`: the part that did not fit. - fn golem_put_down(&mut self, keys: &[Key], mut stack: ItemStack) -> Option { - let max = self.golem_max_stack(&stack); - let slots = self.golem_slots(keys); - for (n, existing) in slots.iter().enumerate() { - match existing { - None => { - if let Some(slot) = self.golem_slot_mut(keys, n) { - *slot = Some(stack); - } - return None; - } - Some(e) - if e.item == stack.item - && e.damage == stack.damage - && e.extra == stack.extra - && e.count < max => - { - let room = max - e.count; - let add = room.min(stack.count); - if let Some(Some(s)) = self.golem_slot_mut(keys, n) { - s.count += add; - } - // Vanilla subtracts the whole room, which empties the stack - // when it fitted. - stack.count = stack.count.saturating_sub(room); - if stack.count == 0 { - return None; - } - } - _ => {} - } - } - Some(stack) - } - /// Whether any other golem or a player has the chest open. - fn golem_chest_busy(&self, m: &Mob, keys: &[Key]) -> bool { - self.golem_openers - .iter() - .any(|(id, k)| *id != m.id && keys.contains(k)) - || self.container.is_some_and(|c| keys.contains(&c)) - } - // ---- the behaviour ---------------------------------------------------- - fn golem_wanted_block(&self, m: &Mob, key: Key) -> bool { - let name = self.golem_block_name(key); - if held(m).is_none() { - is_copper_chest(&name) - } else { - matches!(&*name, "minecraft:chest" | "minecraft:trapped_chest") - } - } - fn golem_update_invalid_target(&mut self, m: &mut Mob) -> bool { - if self.golem_has_valid_target(m) { - return false; - } - self.golem_stop_targeting(m); - match self.golem_find_target(m) { - Some(t) => { - m.extra.home = Some([t.0, t.1, t.2]); - self.golem_on_start_travelling(m); - self.golem_set_visited(m, [t.0, t.1, t.2]); - } - None => self.golem_enter_cooldown(m), - } - true - } - fn golem_has_valid_target(&mut self, m: &mut Mob) -> bool { - let Some(h) = m.extra.home else { return false }; - let key = (h[0], h[1], h[2]); - let valid = self.golem_wanted_block(m, key) - && matches!( - self.world.block_entities.get(&key), - Some(BlockEntity::Chest(_)) - ) - && !self.golem_chest_blocked(&self.golem_container(key)); - if !valid { - return false; - } - if m.extra.scratch[0] != TRAVELLING { - return true; - } - if self.golem_valid_travelling_path(m, h) { - return true; - } - self.golem_mark_unreachable(m, h); - false - } - /// `hasValidTravellingPath`, without the line-of-sight clip. - fn golem_valid_travelling_path(&mut self, m: &mut Mob, h: [i32; 3]) -> bool { - let w = self.mob_world_base(&[]); - let path = match &m.ai.nav.path { - Some(p) => Some(p.clone()), - None => m.create_path_to(&w, h, 0), - }; - let from = match path.as_ref().and_then(|p| p.end()) { - Some(n) => [ - f64::from(n.x) + 0.5, - f64::from(n.y) + m.kind.height / 2.0, - f64::from(n.z) + 0.5, - ], - None => [ - m.position.x, - m.position.y + m.kind.height / 2.0, - m.position.z, - ], - }; - let reach = golem_within(m, self.golem_range(m), from, h); - (path.is_none() && !reach) || reach - } - fn golem_range(&self, m: &Mob) -> f64 { - if m.ai.nav.path.as_ref().is_some_and(|p| p.is_done()) { - 1.0 - } else { - 0.5 - } - } - fn golem_find_target(&self, m: &Mob) -> Option { - let bx = m.position.x.floor() as i32; - let by = m.position.y.floor() as i32; - let bz = m.position.z.floor() as i32; - let skip: Vec<[i32; 3]> = blocked_list(m).collect(); - let mut best: Option<(f64, Key)> = None; - for (key, entity) in &self.world.block_entities { - if !matches!(entity, BlockEntity::Chest(_)) { - continue; - } - if (key.0 - bx).abs() > 32 || (key.1 - by).abs() > 8 || (key.2 - bz).abs() > 32 { - continue; - } - let center = chest_center([key.0, key.1, key.2]); - let d = (center[0] - m.position.x).powi(2) - + (center[1] - m.position.y).powi(2) - + (center[2] - m.position.z).powi(2); - if best.is_some_and(|(b, _)| d >= b) { - continue; - } - if !self.golem_wanted_block(m, *key) { - continue; - } - let keys = self.golem_container(*key); - if keys.iter().any(|k| skip.contains(&[k.0, k.1, k.2])) { - continue; - } - if self.golem_chest_blocked(&keys) { - continue; - } - best = Some((d, *key)); - } - best.map(|b| b.1) - } - fn golem_set_visited(&mut self, m: &mut Mob, h: [i32; 3]) { - let mut list = visited(m); - if !list.contains(&h) { - list.push(h); - } - if list.len() > 10 { - self.golem_enter_cooldown(m); - return; - } - m.extra.positions.retain(|p| p[1] >= UNREACHABLE); - m.extra.positions.extend(list); - m.extra.ints[2] = m.age as i32 + MEMORY_TICKS; - } - fn golem_mark_unreachable(&mut self, m: &mut Mob, h: [i32; 3]) { - m.extra.positions.retain(|p| *p != h); - let marked = [h[0], h[1] + UNREACHABLE, h[2]]; - if !m.extra.positions.contains(&marked) { - m.extra.positions.push(marked); - } - let count = m - .extra - .positions - .iter() - .filter(|p| p[1] >= UNREACHABLE) - .count(); - if count > 50 { - self.golem_enter_cooldown(m); - } else { - m.extra.ints[2] = m.age as i32 + MEMORY_TICKS; - } - } - fn golem_stop_targeting(&mut self, m: &mut Mob) { - m.extra.scratch[1] = 0; - m.extra.home = None; - m.extra.point = None; - m.ai.nav.stop(); - } - fn golem_clear_memories(&mut self, m: &mut Mob) { - self.golem_stop_targeting(m); - m.extra.positions.clear(); - } - fn golem_enter_cooldown(&mut self, m: &mut Mob) { - self.golem_stop_targeting(m); - m.extra.scratch[3] = 140; - m.extra.positions.clear(); - } - /// `onStartTravelling` and the golem's own consumer. - fn golem_on_start_travelling(&mut self, m: &mut Mob) { - self.golem_release(m); - set_state(m, cg::IDLE); - m.extra.scratch[0] = TRAVELLING; - m.extra.scratch[2] = 0; - m.extra.scratch[1] = 0; - } - /// `clearOpenedChestPos` (and so `stopOpen` at the next recheck). - fn golem_release(&mut self, m: &Mob) { - if let Some(key) = self.golem_openers.remove(&m.id) { - let keys = self.golem_container(key); - if !self.golem_chest_busy(m, &keys) { - self.golem_chest_sound(key, false); - } - } - } - fn golem_chest_sound(&mut self, key: Key, open: bool) { - let name = self.golem_block_name(key); - let base = name - .trim_start_matches("minecraft:") - .trim_start_matches("waxed_"); - let kind = if base.starts_with("weathered") { - "copper_chest_weathered" - } else if base.starts_with("oxidized") { - "copper_chest_oxidized" - } else if base.ends_with("copper_chest") { - "copper_chest" - } else { - "chest" - }; - let side = if open { "open" } else { "close" }; - let at = chest_center([key.0, key.1, key.2]); - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play( - &format!("minecraft:block.{kind}.{side}"), - Some(at), - 0.5, - pitch, - ); - } - fn golem_on_queuing(&mut self, m: &mut Mob) { - let Some(h) = m.extra.home else { return }; - let keys = self.golem_container((h[0], h[1], h[2])); - if !self.golem_chest_busy(m, &keys) { - m.extra.scratch[0] = TRAVELLING; - m.extra.point = Some(chest_center(h)); - } - } - fn golem_on_travel(&mut self, m: &mut Mob) { - let Some(h) = m.extra.home else { return }; - let key = (h[0], h[1], h[2]); - let keys = self.golem_container(key); - let center = [ - m.position.x, - m.position.y + m.kind.height / 2.0, - m.position.z, - ]; - if golem_within(m, 3.0, center, h) && self.golem_chest_busy(m, &keys) { - // startQueuing. - m.extra.point = None; - m.ai.nav.stop(); - m.extra.scratch[0] = QUEUING; - } else if golem_within(m, self.golem_range(m), center, h) { - // startOnReachedTargetInteraction. - let slots = self.golem_slots(&keys); - let state = if held(m).is_none() { - if slots.iter().any(Option::is_some) { - PICKUP_ITEM - } else { - PICKUP_NO_ITEM - } - } else if slots.iter().all(Option::is_none) - || slots - .iter() - .flatten() - .any(|s| held(m).is_some_and(|h| h.item == s.item)) - { - PLACE_ITEM - } else { - PLACE_NO_ITEM - }; - m.extra.scratch[2] = state; - m.extra.scratch[0] = INTERACTING; - } else { - m.extra.point = Some(chest_center(h)); - } - } - fn golem_on_reached(&mut self, m: &mut Mob) { - let Some(h) = m.extra.home else { return }; - let key = (h[0], h[1], h[2]); - let center = [ - m.position.x, - m.position.y + m.kind.height / 2.0, - m.position.z, - ]; - if !golem_within(m, 2.0, center, h) { - self.golem_on_start_travelling(m); - return; - } - m.extra.scratch[1] += 1; - let ticks = m.extra.scratch[1]; - // onTargetInteraction: stand still, and the reached interaction. - m.extra.point = None; - m.ai.nav.stop(); - let (state, sound) = match m.extra.scratch[2] { - PICKUP_ITEM => (cg::GETTING_ITEM, Some("entity.copper_golem.no_item_get")), - PICKUP_NO_ITEM => ( - cg::GETTING_NO_ITEM, - Some("entity.copper_golem.no_item_no_get"), - ), - PLACE_ITEM => (cg::DROPPING_ITEM, Some("entity.copper_golem.item_drop")), - PLACE_NO_ITEM => ( - cg::DROPPING_NO_ITEM, - Some("entity.copper_golem.item_no_drop"), - ), - _ => (cg::IDLE, None), - }; - if m.extra.scratch[2] != 0 { - if ticks == 1 { - let keys = self.golem_container(key); - if !self.golem_chest_busy(m, &keys) { - self.golem_chest_sound(key, true); - } - self.golem_openers.insert(m.id, key); - set_state(m, state); - } - if ticks == 9 - && let Some(sound) = sound - { - let at = [m.position.x, m.position.y, m.position.z]; - self.audio - .play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0); - } - if ticks == 60 { - self.golem_release(m); - } - } - if ticks >= 60 { - let keys = self.golem_container(key); - if held(m).is_none() { - if self.golem_slots(&keys).iter().any(Option::is_some) { - // pickUpItems. - let stack = self.golem_pick_up(&keys); - set_held(m, stack); - self.golem_clear_memories(m); - } else { - self.golem_stop_targeting(m); - } - } else if self.golem_slots(&keys).iter().all(Option::is_none) - || self - .golem_slots(&keys) - .iter() - .flatten() - .any(|s| held(m).is_some_and(|h| h.item == s.item)) - { - // putDownItem. - let stack = held(m) - .cloned() - .unwrap_or_else(|| ItemStack::new("minecraft:air", 0)); - let left = self.golem_put_down(&keys, stack); - let emptied = left.is_none(); - set_held(m, left); - if emptied { - self.golem_clear_memories(m); - } else { - self.golem_stop_targeting(m); - } - } else { - self.golem_stop_targeting(m); - } - self.golem_on_start_travelling(m); - } - } // ---- interactions ----------------------------------------------------- /// `CopperGolem.mobInteract`; true when handled. pub(super) fn interact_copper_golem(&mut self, index: usize, item: &str) -> bool { @@ -743,7 +273,7 @@ impl Game<'_> { if is_axe && self.mobs[index].extra.variant > 0 { let m = &mut self.mobs[index]; m.extra.vector[0] = -1.0; - m.extra.variant = cg::weather_previous(m.extra.variant); + m.extra.variant = horizon_client::mobs::copper_golem::weather_previous(m.extra.variant); self.audio .play("minecraft:item.axe.scrape", Some(at), 1.0, 1.0); self.damage_held_tool(); @@ -762,25 +292,3 @@ impl Game<'_> { }) } } -/// `isWithinTargetDistance`: the golem's box centred on `from` against the -/// chest's collision box inflated by `distance` (and half a block vertically). -fn golem_within(m: &Mob, distance: f64, from: [f64; 3], h: [i32; 3]) -> bool { - let hw = m.kind.width / 2.0; - let hh = m.kind.height / 2.0; - let lo = [ - f64::from(h[0]) + 0.0625 - distance, - f64::from(h[1]) - 0.5, - f64::from(h[2]) + 0.0625 - distance, - ]; - let hi = [ - f64::from(h[0]) + 0.9375 + distance, - f64::from(h[1]) + 0.875 + 0.5, - f64::from(h[2]) + 0.9375 + distance, - ]; - from[0] + hw > lo[0] - && from[0] - hw < hi[0] - && from[1] + hh > lo[1] - && from[1] - hh < hi[1] - && from[2] + hw > lo[2] - && from[2] - hw < hi[2] -} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index bd958893f..a7946e1ed 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -328,6 +328,7 @@ impl Game<'_> { world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: self.mob_teams(), + items: Some(&self.res.items), difficulty: self.local_difficulty( self.player .as_ref() @@ -755,6 +756,11 @@ impl Game<'_> { } } }, + MobEvent::ChestOpen { chest, open } => self.golem_chest_open(chest, open), + MobEvent::ChestSlot { chest, slot, stack } => { + self.golem_chest_slot(chest, slot, stack) + } + MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob), MobEvent::Gift { target, item } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target) && m.saddle_item().is_none() diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 9e0f55097..5bf61ace9 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -57,6 +57,7 @@ pub mod species; pub mod sulfur_cube; pub mod tame; pub mod trader; +pub mod transport_items; pub mod undead; pub mod vex; pub mod villager; @@ -520,6 +521,8 @@ pub struct Extra { pub counter: i32, pub counter2: i32, pub home: Option<[i32; 3]>, + /// A copper golem's `openedChestPos`. + pub opened_chest: Option<[i32; 3]>, pub point: Option<[f64; 3]>, pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). @@ -636,6 +639,22 @@ pub struct Mob { #[derive(Clone, Debug)] pub enum MobEvent { Sound(&'static str, [f64; 3], f32, f32), + /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the + /// chest's opener count goes up or down (interaction range 3). + ChestOpen { + chest: [i32; 3], + open: bool, + }, + /// `CopperGolem.turnToStatue`. + BecomeStatue { + mob: u32, + }, + /// A copper golem took from or filled a chest slot. + ChestSlot { + chest: [i32; 3], + slot: usize, + stack: Option, + }, /// `OfferFlowerGoal.stop`: the item goes to the target's antenna (saddle) /// slot if it is empty, as a guaranteed drop. Gift { @@ -927,6 +946,8 @@ pub struct Seen { pub hurt_by: Option<(Who, i32)>, /// A raider in an active raid. pub active_raid: bool, + /// A copper golem's `openedChestPos` (`ContainerUser.hasContainerOpen`). + pub opened_chest: Option<[i32; 3]>, /// A villager's reputation of the player (`getPlayerReputation`). pub player_rep: i32, /// `isPushable` and pushed by others (`Entity.push(Entity)` moves it). @@ -981,6 +1002,7 @@ impl Mob { delay: m.extra.ints[5], hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), active_raid: raider::has_active_raid(m), + opened_chest: m.extra.opened_chest, player_rep: match (villager, player) { (true, Some(uuid)) => villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)), _ => 0, @@ -1137,6 +1159,8 @@ pub struct MobWorld<'a> { pub sea_level: i32, /// The scoreboard teams of the player and the mobs (collision rules). pub teams: Teams, + /// Item data (max stack sizes), when the host has it. + pub items: Option<&'a crate::items::Items>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 9c825d61b..903e0f437 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -370,6 +370,10 @@ pub fn tick( m.update_walk_animation(); m.anim.end_tick(m.ai.swinging); tick_swing(m); + if m.species() == Species::CopperGolem { + // CopperGolem.tick: updateWeathering after the living tick. + super::copper_golem::update_weathering(m, w, level_random, events); + } true } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -797,7 +801,10 @@ fn server_ai_step( } // Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's // only while it is a ghastling), then updateActivity. - if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() { + if m.species() == Species::Sniffer + || m.species() == Species::HappyGhast && m.is_baby() + || m.species() == Species::CopperGolem + { super::animal_brain::tick(m, w, level_random, events); } { @@ -1276,6 +1283,8 @@ pub fn step_sound( S::CamelHusk => Some(("entity.camel_husk.step", 0.4, 1.0)), S::Camel => Some(("entity.camel.step", 1.0, 1.0)), S::IronGolem => Some(("entity.iron_golem.step", 1.0, 1.0)), + // CopperGolem.playStepSound: its oxidation level's step. + S::CopperGolem => Some((super::copper_golem::sound(m, "step"), 1.0, 1.0)), S::Strider if m.fluids.in_lava => Some(("entity.strider.step_lava", 1.0, 1.0)), S::Strider => Some(("entity.strider.step", 1.0, 1.0)), S::Warden => Some(("entity.warden.step", 10.0, 1.0)), diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9edf2accf..c3bafd68f 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -192,6 +192,10 @@ pub struct Memories { pub sniffer_sniffing_target: Slot<[i32; 3]>, pub sniffer_happy: Slot, pub sniff_cooldown: Slot<()>, + pub gaze_cooldown_ticks: Slot, + pub transport_items_cooldown_ticks: Slot, + pub visited_block_positions: Slot>, + pub unreachable_transport_block_positions: Slot>, } impl Memories { fn tick(&mut self) { @@ -216,6 +220,10 @@ impl Memories { self.sniffer_sniffing_target.tick(); self.sniffer_happy.tick(); self.sniff_cooldown.tick(); + self.gaze_cooldown_ticks.tick(); + self.transport_items_cooldown_ticks.tick(); + self.visited_block_positions.tick(); + self.unreachable_transport_block_positions.tick(); } } @@ -246,6 +254,8 @@ pub enum Kind { Sniffer, /// A happy ghast (the brain ticks while it is a ghastling). Ghastling, + /// `CopperGolemAi`. + CopperGolem, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -273,6 +283,7 @@ impl Kind { Sensor::AdultAnyType, Sensor::Players, ], + Kind::CopperGolem => &[Sensor::Living, Sensor::HurtBy], } } } @@ -302,10 +313,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { .as_deref_mut() .expect("the animal brain is built before it is used") } -fn mem(m: &mut Mob) -> &mut Memories { +pub(super) fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } -fn mem_ref(m: &Mob) -> Option<&Memories> { +pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -315,6 +326,7 @@ pub fn kind_of(m: &Mob) -> Option { Species::Sniffer => Some(Kind::Sniffer), // Every happy ghast has the brain; only the ghastling's ticks. Species::HappyGhast => Some(Kind::Ghastling), + Species::CopperGolem => Some(Kind::CopperGolem), _ => None, } } @@ -324,6 +336,10 @@ pub fn kind_of(m: &Mob) -> Option { /// The gates shuffle with a random seeded with `shuffle_seed`. pub fn init(m: &mut Mob, shuffle_seed: i64) { let Some(kind) = kind_of(m) else { return }; + // The copper golem's constructor: TRANSPORT_ITEMS_COOLDOWN_TICKS of + // nextInt(60, 100). + let cooldown = + (kind == Kind::CopperGolem).then(|| 60 + m.random.next_int_bound(40).unwrap_or(0)); let sensors = kind .sensors() .iter() @@ -339,10 +355,27 @@ pub fn init(m: &mut Mob, shuffle_seed: i64) { b.list = match kind { Kind::Sniffer => sniffer_package(shuffle_seed), Kind::Ghastling => ghastling_package(shuffle_seed), + Kind::CopperGolem => copper_golem_package(shuffle_seed), }; + if let Some(c) = cooldown { + b.mem.transport_items_cooldown_ticks.set(c); + } m.extra.animal_brain = Some(Box::new(b)); } +/// A copper golem's `TRANSPORT_ITEMS_COOLDOWN_TICKS`, or none for 0. +pub fn set_transport_cooldown(m: &mut Mob, ticks: i32) { + if m.extra.animal_brain.is_none() { + return; + } + let slot = &mut mem(m).transport_items_cooldown_ticks; + if ticks > 0 { + slot.set(ticks); + } else { + slot.clear(); + } +} + /// The happy ghast grew up (`adultGhastSetup`): every running behaviour /// stops (`Brain.stopAll`) and the memories are cleared; the brain no /// longer ticks. @@ -434,6 +467,7 @@ fn update_activity(m: &mut Mob) { let order: &[Act] = match b.kind { Kind::Sniffer => &[Act::Dig, Act::Sniff, Act::Idle], Kind::Ghastling => &[Act::Panic, Act::Idle], + Kind::CopperGolem => &[Act::Idle], }; for &a in order { let ok = match a { @@ -727,6 +761,8 @@ struct Gate { running: bool, random: LegacyRandom, kids: Vec<(B, i32, f64)>, + /// The gate's memory requirements. + when: Option bool>, } impl Gate { fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self { @@ -734,9 +770,19 @@ impl Gate { running: false, random: LegacyRandom::new(seed), kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + when: None, } } + fn when(mut self, f: fn(&Memories) -> bool) -> Self { + self.when = Some(f); + self + } fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if let Some(f) = self.when + && !f(mem(m)) + { + return false; + } self.running = true; // ShufflingList.shuffle: a fresh weight for each entry in the // current order, then a stable sort. @@ -780,6 +826,7 @@ enum B { AnimalPanic { t: Timed, fly: bool, + speed: f32, }, MoveToTargetSink { t: Timed, @@ -819,6 +866,8 @@ enum B { running: bool, fly: bool, speed: f32, + /// Horizontal and vertical range (land strolls). + range: (i32, i32), }, /// `BabyFollowAdult.create(3..16, 1.1, memory, true)`: the nearest /// visible player or adult. @@ -827,6 +876,15 @@ enum B { player: bool, }, Gate(Box), + /// `CountDownCooldownTicks(GAZE_COOLDOWN_TICKS)` and + /// `(TRANSPORT_ITEMS_COOLDOWN_TICKS)`. + CountDownGaze(Timed), + CountDownTransport(Timed), + /// `SetEntityLookTargetSometimes.create(PLAYER, 6, 40..80)`: running, + /// and the ticker's ticks until the next start. + LookAtPlayerSometimes(bool, i32), + /// `TransportItemsBetweenContainers`. + Transport(Box), } impl B { @@ -845,7 +903,11 @@ impl B { | B::Searching(t) | B::Scenting(t) | B::Sniffing(t) - | B::DoNothing(t) => t.running, + | B::DoNothing(t) + | B::CountDownGaze(t) + | B::CountDownTransport(t) => t.running, + B::Transport(x) => x.running, + B::LookAtPlayerSometimes(running, _) => *running, B::WalkToLookTarget { running, .. } | B::LookAtPlayer(running) | B::Stroll { running, .. } @@ -869,7 +931,10 @@ impl B { | B::Searching(t) | B::Scenting(t) | B::Sniffing(t) - | B::DoNothing(t) => t.running = false, + | B::DoNothing(t) + | B::CountDownGaze(t) + | B::CountDownTransport(t) => t.running = false, + B::Transport(x) => x.running = false, B::MoveToTargetSink { t, path, .. } => { t.running = false; *path = None; @@ -889,6 +954,7 @@ impl B { self, B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } ) @@ -897,6 +963,7 @@ impl B { match self { B::WalkToLookTarget { running, .. } | B::LookAtPlayer(running) + | B::LookAtPlayerSometimes(running, _) | B::Stroll { running, .. } | B::FollowAdult { running, .. } => *running = on, _ => {} @@ -975,6 +1042,21 @@ impl B { t.begin(cx); true } + B::CountDownGaze(t) => { + if !mem(m).gaze_cooldown_ticks.present() { + return false; + } + t.begin(cx); + true + } + B::CountDownTransport(t) => { + if !mem(m).transport_items_cooldown_ticks.present() { + return false; + } + t.begin(cx); + true + } + B::Transport(x) => x.try_start(m, cx), B::MakeLove { t, spawn_at } => { let mm = mem(m); if !mm.visible_mobs.present() @@ -1116,6 +1198,7 @@ impl B { } B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } => unreachable!("one-shots trigger"), } @@ -1155,7 +1238,33 @@ impl B { mem(m).look_target.set(Tracker::entity(t, true)); true } - B::Stroll { fly, speed, .. } => { + B::LookAtPlayerSometimes(_, ref mut ticks) => { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let w = cx.w; + let found = find_closest(m, w, |m, who| { + who == Who::Player + && w.target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 36.0) + }); + let Some(t) = found else { return false }; + // Ticker.tickDownAndCheck (UniformInt 40..80 on the level random). + if *ticks == 0 { + *ticks = 40 + cx.lr.next_int_bound(41).unwrap_or(0) - 1; + return false; + } + *ticks -= 1; + if *ticks != 0 { + return false; + } + mem(m).look_target.set(Tracker::entity(t, true)); + true + } + B::Stroll { + fly, speed, range, .. + } => { if mem(m).walk_target.present() { return false; } @@ -1163,7 +1272,7 @@ impl B { let view = m.view_vector(); m.air_and_water_random_pos(cx.w, 10, 7, -2, view[0], view[2]) } else { - m.land_random_pos(cx.w, 10, 7) + m.land_random_pos(cx.w, range.0, range.1) }; mem(m) .walk_target @@ -1226,7 +1335,7 @@ impl B { m.ai.jump = true; } } - B::AnimalPanic { t, fly } => { + B::AnimalPanic { t, fly, speed } => { if t.timed_out(now) { self.do_stop(m, cx); return; @@ -1234,7 +1343,7 @@ impl B { if m.ai.nav.is_done() { let pos = panic_pos(m, cx.w, *fly); if let Some(p) = pos { - mem(m).walk_target.set(WalkTarget::point(p, 2.0, 0)); + mem(m).walk_target.set(WalkTarget::point(p, *speed, 0)); } } } @@ -1280,6 +1389,21 @@ impl B { _ => self.do_stop(m, cx), } } + B::CountDownGaze(_) => { + let v = mem(m).gaze_cooldown_ticks.value(); + match v { + Some(v) if v > 0 => mem(m).gaze_cooldown_ticks.set(v - 1), + _ => self.do_stop(m, cx), + } + } + B::CountDownTransport(_) => { + let v = mem(m).transport_items_cooldown_ticks.value(); + match v { + Some(v) if v > 0 => mem(m).transport_items_cooldown_ticks.set(v - 1), + _ => self.do_stop(m, cx), + } + } + B::Transport(x) => x.tick_or_stop(m, cx), B::MakeLove { spawn_at, .. } => { let Some(partner) = mem(m).breed_target.value() else { self.do_stop(m, cx); @@ -1422,6 +1546,7 @@ impl B { } B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } => {} } @@ -1461,6 +1586,15 @@ impl B { t.running = false; mem(m).temptation_cooldown_ticks.clear(); } + B::CountDownGaze(t) => { + t.running = false; + mem(m).gaze_cooldown_ticks.clear(); + } + B::CountDownTransport(t) => { + t.running = false; + mem(m).transport_items_cooldown_ticks.clear(); + } + B::Transport(x) => x.do_stop(m, cx), B::MakeLove { t, spawn_at } => { t.running = false; let mm = mem(m); @@ -1536,6 +1670,7 @@ impl B { } B::WalkToLookTarget { .. } | B::LookAtPlayer(_) + | B::LookAtPlayerSometimes(..) | B::Stroll { .. } | B::FollowAdult { .. } => {} } @@ -1653,7 +1788,7 @@ fn follow_temptation_close(m: &mut Mob) -> f64 { 3.5 } } - Kind::Ghastling => 3.0, + Kind::Ghastling | Kind::CopperGolem => 3.0, } } fn can_mate_with(m: &Mob, w: &MobWorld, partner: Who) -> bool { @@ -1777,6 +1912,7 @@ fn sniffer_package(seed: i64) -> Vec { B::AnimalPanic { t: Timed::new(100, 120), fly: false, + speed: 2.0, }, ), e( @@ -1815,6 +1951,7 @@ fn sniffer_package(seed: i64) -> Vec { running: false, fly: false, speed: 1.0, + range: (10, 7), }, 1, ), @@ -1825,6 +1962,59 @@ fn sniffer_package(seed: i64) -> Vec { l } /// `HappyGhastAi.getActivities`, in `availableBehaviorsByPriority` order. +/// `CopperGolemAi.getActivities`, in tick order: the core behaviours take +/// priorities 0 to 5 in turn (`ActivityData.create(CORE, 0, ..)`), the idle +/// ones 0, 1 and 2. +fn copper_golem_package(seed: i64) -> Vec { + let e = |act: Act, b: B| Entry { act, b }; + vec![ + // Priority 0. + e( + Act::Core, + B::AnimalPanic { + t: Timed::new(100, 120), + fly: false, + speed: 1.5, + }, + ), + e(Act::Idle, B::Transport(Box::default())), + // Priority 1. + e(Act::Core, B::LookAtTargetSink(Timed::new(45, 90))), + e(Act::Idle, B::LookAtPlayerSometimes(false, 0)), + // Priority 2: RunOne(stroll or do nothing) while there is no walk + // target and the transport cools down. + e(Act::Core, move_to_target_sink(150, 250)), + e( + Act::Idle, + B::Gate(Box::new( + Gate::run_one( + seed, + vec![ + ( + B::Stroll { + running: false, + fly: false, + speed: 1.0, + range: (2, 2), + }, + 1, + ), + (B::DoNothing(Timed::new(30, 60)), 1), + ], + ) + .when(|mm| { + !mm.walk_target.present() && mm.transport_items_cooldown_ticks.present() + }), + )), + ), + // Priority 3 is InteractWithDoor, which only acts on doors along the + // path; these golems pass none. + // Priorities 4 and 5. + e(Act::Core, B::CountDownGaze(Timed::new(60, 60))), + e(Act::Core, B::CountDownTransport(Timed::new(60, 60))), + ] +} + fn ghastling_package(seed: i64) -> Vec { let e = |act: Act, b: B| Entry { act, b }; vec![ @@ -1836,6 +2026,7 @@ fn ghastling_package(seed: i64) -> Vec { B::AnimalPanic { t: Timed::new(100, 120), fly: true, + speed: 2.0, }, ), e( @@ -1875,6 +2066,7 @@ fn ghastling_package(seed: i64) -> Vec { running: false, fly: true, speed: 1.0, + range: (10, 7), }, 1, ), @@ -2000,6 +2192,23 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { slot!("sniffer_happy", mm.sniffer_happy, |b: &bool| b.to_string()); slot!("sniff_cooldown", mm.sniff_cooldown, |_: &()| "u" .to_string()); + slot!("gaze_cooldown_ticks", mm.gaze_cooldown_ticks, |t: &i32| t + .to_string()); + slot!( + "transport_items_cooldown_ticks", + mm.transport_items_cooldown_ticks, + |t: &i32| t.to_string() + ); + slot!( + "visited_block_positions", + mm.visited_block_positions, + |l: &Vec<[i32; 3]>| format!("n{}", l.len()) + ); + slot!( + "unreachable_transport_block_positions", + mm.unreachable_transport_block_positions, + |l: &Vec<[i32; 3]>| format!("n{}", l.len()) + ); if b.kind == Kind::Sniffer && !m.extra.positions.is_empty() { put( "sniffer_explored_positions", diff --git a/crates/horizon-client/src/mobs/copper_golem.rs b/crates/horizon-client/src/mobs/copper_golem.rs index de037016c..398022485 100644 --- a/crates/horizon-client/src/mobs/copper_golem.rs +++ b/crates/horizon-client/src/mobs/copper_golem.rs @@ -1,12 +1,10 @@ -//! Copper golems (`CopperGolem`, `CopperGolemAi`): they carry items from -//! copper chests to chests (see `game::copper_golems` for the container side -//! of `TransportItemsBetweenContainers`), play the chest interaction -//! animations, spin their heads when idle, oxidise over time and finally turn -//! into statues. +//! Copper golems (`CopperGolem`): their brain (`CopperGolemAi`, in +//! `animal_brain`) carries items from copper chests to chests +//! (`transport_items`); here the chest interaction animations, the idle head +//! spin, and weathering until they turn into statues. use super::{ Mob, MobEvent, MobWorld, anim::{Poses, State}, - goals::{Cx, Goal, JUMP, LOOK, MOVE, Panic, goal_clone}, keyframes::Animation, }; use horizon_core::random::RandomSource; @@ -15,11 +13,10 @@ use std::collections::HashMap; // Copper golem state: `variant` the weathering (0 unaffected .. 3 oxidized), // `variant3` the `CopperGolemState`, `main_hand` with `ints[1]` the carried // stack, the saddle slot the antenna (`EQUIPMENT_SLOT_ANTENNA`), `vector[0]` -// the next weathering tick (-1 unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest -// being served with `positions` the visited chests, `point` where it walks, -// `scratch` = [transport phase, ticks since reaching the target, interaction -// state, transport cooldown ticks]. AnimationState slots: idle (0), getting an -// item (1), getting nothing (2), dropping an item (3), dropping nothing (4). +// the next weathering tick (-1 unset, -2 waxed), `ints[0]` the idle animation +// start tick, `opened_chest` the `openedChestPos`. AnimationState slots: idle +// (0), getting an item (1), getting nothing (2), dropping an item (3), +// dropping nothing (4). pub const IDLE: u8 = 0; pub const GETTING_ITEM: u8 = 1; pub const GETTING_NO_ITEM: u8 = 2; @@ -34,12 +31,6 @@ pub fn register(m: &mut Mob) { m.persistent = true; // nextWeatheringTick starts unset (-1); waxed is -2. m.extra.vector[0] = -1.0; - m.extra.scratch[3] = 60 + m.random.next_int_bound(40).unwrap_or(0); - let g = &mut m.ai.goals; - g.add(0, Panic::new(1.5)); - g.add(1, Serve); - g.add(2, super::goals::LookAtPlayer::new(6.0).probability(0.02)); - g.add(3, Idle::default()); } /// `CopperGolemOxidationLevels`: the body and eye textures. pub fn texture(m: &Mob) -> String { @@ -77,101 +68,6 @@ pub fn sound(m: &Mob, what: &str) -> &'static str { _ => "entity.copper_golem.step", } } -/// `CopperGolemAi`'s transport behaviour is running a target. -fn serving(m: &Mob) -> bool { - m.extra.home.is_some() -} -/// `TransportItemsBetweenContainers` walking and looking at its chest, and -/// standing still while interacting with it. -#[derive(Clone, Debug)] -struct Serve; -impl Goal for Serve { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE | LOOK - } - fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - serving(m) && !m.ai.panicking - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.can_use(m, cx) - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - let Some(h) = m.extra.home else { return }; - m.look_at([ - f64::from(h[0]) + 0.5, - f64::from(h[1]) + 0.5, - f64::from(h[2]) + 0.5, - ]); - match m.extra.point { - Some(p) => { - if m.ai.nav.is_done() || m.age.is_multiple_of(10) { - let block = [ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ]; - let path = m.create_path_to(cx.w, block, 0); - m.nav_move_to_path(path, 1.0); - } - } - None => { - // stopInPlace. - m.ai.nav.stop(); - m.velocity.x = 0.0; - m.velocity.z = 0.0; - } - } - } - fn stop(&mut self, m: &mut Mob, _: &mut Cx) { - m.ai.nav.stop(); - } -} -/// The idle `RunOne`: `RandomStroll.stroll(1.0, 2, 2)` or `DoNothing(30, 60)`, -/// only while the transport cooldown runs. -#[derive(Clone, Debug, Default)] -struct Idle { - wait: i32, - stroll: bool, -} -impl Goal for Idle { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE | JUMP - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if serving(m) || m.extra.scratch[3] <= 0 || !m.ai.nav.is_done() { - return false; - } - if m.random.next_int_bound(2).unwrap_or(0) == 0 { - let Some(p) = m.land_random_pos(cx.w, 2, 2) else { - return false; - }; - self.stroll = true; - m.nav_move_to(cx.w, p, 1.0); - } else { - self.stroll = false; - self.wait = 30 + m.random.next_int_bound(30).unwrap_or(0); - } - true - } - fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - if serving(m) { - return false; - } - if self.stroll { - !m.ai.nav.is_done() - } else { - self.wait > 0 - } - } - fn tick(&mut self, _: &mut Mob, _: &mut Cx) { - self.wait -= 1; - } - fn stop(&mut self, m: &mut Mob, _: &mut Cx) { - m.ai.nav.stop(); - } -} /// `CopperGolem.setupAnimationStates` (client) and the sound of the head spin. pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { let age = m.age as f32; @@ -191,11 +87,14 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { if m.extra.ints[0] == tick { st[0].start(age); } else if m.extra.ints[0] == 0 { - m.extra.ints[0] = tick + 200 + m.random.next_int_bound(40).unwrap_or(0); + // The client entity's own random, not the server's. + let mut r = + horizon_core::random::LegacyRandom::new(i64::from(m.id) ^ i64::from(tick)); + m.extra.ints[0] = tick + 200 + r.next_int_bound(40).unwrap_or(0); } if tick == m.extra.ints[0] + 10 { let at = [m.position.x, m.position.y, m.position.z]; - events.push(MobEvent::Sound(sound(m, "spin"), at, 1.0, 1.0)); + events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0)); m.extra.ints[0] = 0; } } @@ -208,6 +107,51 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { _ => {} } } +/// `CopperGolem.updateWeathering` on the level random: the first tick sets +/// the next weathering tick, which advances the weather state; once +/// oxidized, a golem on an air block may turn into a statue +/// (`MobEvent::BecomeStatue`, done by the host). +pub fn update_weathering( + m: &mut Mob, + w: &MobWorld, + lr: &mut impl RandomSource, + events: &mut Vec, +) { + if !m.alive() || m.removed { + return; + } + let now = w.game_time; + let next = m.extra.vector[0] as i64; + if next == -2 { + return; + } + let interval = |r: &mut dyn FnMut() -> i32| 504_000 + i64::from(r()); + let mut draw = || lr.next_int_bound(48_001).unwrap_or(0); + if next == -1 { + m.extra.vector[0] = (now + interval(&mut draw)) as f64; + return; + } + let fully = m.extra.variant >= 3; + if now >= next && !fully { + let new = weather_next(m.extra.variant); + m.extra.variant = new; + m.extra.vector[0] = if new >= 3 { + 0.0 + } else { + (next + interval(&mut draw)) as f64 + }; + } + if fully { + let p = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if w.facts.is_air(w.world.block(p[0], p[1], p[2])) && lr.next_float() <= 0.0058 { + events.push(MobEvent::BecomeStatue { mob: m.id }); + } + } +} /// `CopperGolemModel.setupAnim`. pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap) { p.xrot("head", s.x_rot.to_radians()); diff --git a/crates/horizon-client/src/mobs/transport_items.rs b/crates/horizon-client/src/mobs/transport_items.rs new file mode 100644 index 000000000..934e59695 --- /dev/null +++ b/crates/horizon-client/src/mobs/transport_items.rs @@ -0,0 +1,827 @@ +//! `TransportItemsBetweenContainers` as the copper golem's brain runs it +//! (`CopperGolemAi`): find the nearest wanted chest (a copper chest with +//! nothing in hand, a chest or trapped chest holding something), walk to it, +//! queue while another golem has it open, open it for 60 ticks and take up +//! to 16 items or put the carried stack down, remembering visited and +//! unreachable chests. +//! +//! The chests are read from the world; what changes them comes out as +//! [`MobEvent::ChestOpen`] and [`MobEvent::ChestSlot`] for the host to apply +//! before the next mob ticks. +use super::{ + Mob, MobEvent, MobWorld, + animal_brain::{Bx, Tracker, WalkTarget, mem, mem_ref}, + copper_golem as cg, +}; +use crate::{containers::BlockEntity, items::ItemStack}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; +use horizon_world::java_hash_map::{JavaHashMap, JavaKey}; + +/// `TransportItemState`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum State { + Travelling, + Queuing, + Interacting, +} +/// `ContainerInteractionState`. +#[allow(clippy::enum_variant_names)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Interaction { + PickupItem, + PickupNoItem, + PlaceItem, + PlaceNoItem, +} + +/// `TransportItemTarget`: the chest and its block state when it was chosen. +#[derive(Clone, Debug)] +struct Target { + pos: [i32; 3], + name: String, + /// The halves of the container in slot order (the right half first). + halves: Vec<[i32; 3]>, +} + +#[derive(Clone, Debug)] +pub(super) struct Transport { + pub(super) running: bool, + end: i64, + target: Option, + state: State, + interaction: Option, + ticks: i32, +} +impl Default for Transport { + fn default() -> Self { + Self { + running: false, + end: 0, + target: None, + state: State::Travelling, + interaction: None, + ticks: 0, + } + } +} + +/// The golem's held stack (`getMainHandItem`). +pub fn held(m: &Mob) -> Option<&ItemStack> { + m.extra.items.first().and_then(Option::as_ref) +} +/// `setItemSlot(MAINHAND, ..)`, keeping the rendered copy in step. +pub fn set_held(m: &mut Mob, stack: Option) { + let stack = stack.filter(|s| s.count > 0); + m.extra.main_hand = stack.as_ref().map(|s| s.item.clone()); + m.extra.ints[1] = stack.as_ref().map_or(0, |s| s.count as i32); + if m.extra.items.is_empty() { + m.extra.items.push(None); + } + m.extra.items[0] = stack; +} + +fn name_at(w: &MobWorld, p: [i32; 3]) -> String { + w.facts + .get(w.world.block(p[0], p[1], p[2])) + .name + .to_string() +} +fn is_chest_block(name: &str) -> bool { + matches!(name, "minecraft:chest" | "minecraft:trapped_chest") || name.ends_with("copper_chest") +} +/// `CopperGolemAi.TRANSPORT_ITEM_SOURCE_BLOCK` / `_DESTINATION_BLOCK`. +fn wanted(w: &MobWorld, m: &Mob, name: &str) -> bool { + if held(m).is_none() { + w.has_tag("minecraft:copper_chests", name) || w.has_tag("copper_chests", name) + } else { + matches!(name, "minecraft:chest" | "minecraft:trapped_chest") + } +} +/// `ChestBlock.getConnectedBlockPos`: the other half of a double chest. +fn connected(w: &MobWorld, p: [i32; 3]) -> Option<[i32; 3]> { + let kind = w.prop(p[0], p[1], p[2], "type")?; + if kind == "single" { + return None; + } + let facing = w.prop(p[0], p[1], p[2], "facing")?; + // LEFT: facing.getClockWise(), else getCounterClockWise(). + let order = ["north", "east", "south", "west"]; + let i = order.iter().position(|f| *f == facing)?; + let dir = order[if kind == "left" { + (i + 1) % 4 + } else { + (i + 3) % 4 + }]; + let (dx, dz) = match dir { + "north" => (0, -1), + "south" => (0, 1), + "east" => (1, 0), + _ => (-1, 0), + }; + Some([p[0] + dx, p[1], p[2] + dz]) +} +/// `ChestBlock.isChestBlockedAt` (a cat sitting on it aside): a redstone +/// conductor above. +fn blocked(w: &MobWorld, p: [i32; 3]) -> bool { + let above = w.world.block(p[0], p[1] + 1, p[2]); + w.data.state(above).flags & super::data::REDSTONE_CONDUCTOR != 0 +} +/// `ChestBlock.getContainer(.., false)`: the chest's halves in slot order, +/// none when either half is blocked. +fn container(w: &MobWorld, p: [i32; 3]) -> Option> { + if blocked(w, p) { + return None; + } + let mut halves = vec![p]; + if let Some(other) = connected(w, p) { + let same = w.world.block(other[0], other[1], other[2]) == w.world.block(p[0], p[1], p[2]) + || name_at(w, other) == name_at(w, p) + && w.prop(other[0], other[1], other[2], "facing") + == w.prop(p[0], p[1], p[2], "facing") + && w.prop(other[0], other[1], other[2], "type") + .is_some_and(|t| t != "single") + && w.prop(other[0], other[1], other[2], "type") != w.prop(p[0], p[1], p[2], "type"); + if same + && matches!( + w.world.block_entities.get(&(other[0], other[1], other[2])), + Some(BlockEntity::Chest(_)) + ) + { + if blocked(w, other) { + return None; + } + if w.prop(p[0], p[1], p[2], "type") == Some("right") { + halves.push(other); + } else { + halves.insert(0, other); + } + } + } + Some(halves) +} +fn slots(w: &MobWorld, halves: &[[i32; 3]]) -> Vec> { + halves + .iter() + .filter_map(|h| w.world.block_entities.get(&(h[0], h[1], h[2]))) + .flat_map(|e| e.slots().to_vec()) + .collect() +} +/// Where slot `n` of the container is: the half and its own slot. +fn slot_at(w: &MobWorld, halves: &[[i32; 3]], mut n: usize) -> Option<([i32; 3], usize)> { + for h in halves { + let len = w + .world + .block_entities + .get(&(h[0], h[1], h[2]))? + .slots() + .len(); + if n < len { + return Some((*h, n)); + } + n -= len; + } + None +} +fn max_stack(w: &MobWorld, s: &ItemStack) -> u32 { + w.items + .and_then(|i| i.get(&s.item)) + .map_or(64, |i| i.max_stack) + .max(1) +} + +/// `BlockPos` keys in a chunk's block entity map. +#[derive(PartialEq, Eq)] +struct PosKey([i32; 3]); +impl JavaKey for PosKey { + fn java_hash(&self) -> i32 { + // Vec3i.hashCode. + (self.0[1].wrapping_add(self.0[2].wrapping_mul(31))) + .wrapping_mul(31) + .wrapping_add(self.0[0]) + } + fn tie_break(&self, _: &Self) -> std::cmp::Ordering { + std::cmp::Ordering::Less + } +} + +/// `AABB.ofSize(center, ..)` of the mob's box, and whether the chest's +/// collision box grown by `distance` (and 0.5 up and down) reaches it. +fn within(w: &MobWorld, m: &Mob, distance: f64, t: &Target, from: [f64; 3]) -> bool { + let size = m.bounds().size(); + let moved = Aabb::new( + Vec3::new( + from[0] - size.x / 2.0, + from[1] - size.y / 2.0, + from[2] - size.z / 2.0, + ), + Vec3::new( + from[0] + size.x / 2.0, + from[1] + size.y / 2.0, + from[2] + size.z / 2.0, + ), + ); + // getCollisionShape of the state the target was chosen with: the block + // there now (the target is dropped once it changes). + let Some(shape) = w.collision_bounds(t.pos) else { + return false; + }; + let p = Vec3::new( + f64::from(t.pos[0]), + f64::from(t.pos[1]), + f64::from(t.pos[2]), + ); + shape + .inflate(Vec3::new(distance, 0.5, distance)) + .move_by(p) + .intersects(moved) +} +fn center(m: &Mob) -> [f64; 3] { + [ + m.position.x, + m.position.y + m.bounds().size().y / 2.0, + m.position.z, + ] +} +fn finished_path(m: &Mob) -> bool { + m.ai.nav.path.as_ref().is_some_and(|p| p.is_done()) +} +/// `getInteractionRange`. +fn range(m: &Mob) -> f64 { + if finished_path(m) { 1.0 } else { 0.5 } +} +/// `stopInPlace`. +fn stop_in_place(m: &mut Mob) { + m.nav_stop(); + m.ai.xxa = 0.0; + m.ai.yya = 0.0; + m.ai.speed = 0.0; + m.velocity.x = 0.0; + m.velocity.z = 0.0; +} +/// `ContainerOpenersCounter.getEntitiesWithContainerOpen`: the golems with +/// either half of the chest open, within the counter's interaction range +/// plus 4. +fn openers(w: &MobWorld, m: &Mob, p: [i32; 3]) -> usize { + let area = opener_area(w, p); + let me = usize::from(has_open(w, m, p)); + me + w + .others + .iter() + .filter(|s| { + s.id != m.id && s.alive && holds(w, s.opened_chest, p) && s.bounds.intersects(area) + }) + .count() +} +/// `CopperGolem.hasContainerOpen`: its opened chest is `p` or `p`'s other half. +fn holds(w: &MobWorld, opened: Option<[i32; 3]>, p: [i32; 3]) -> bool { + opened.is_some_and(|o| o == p || connected(w, o) == Some(p)) +} +/// Whether the counter at `p` lists this golem. +fn has_open(w: &MobWorld, m: &Mob, p: [i32; 3]) -> bool { + holds(w, m.extra.opened_chest, p) && m.bounds().intersects(opener_area(w, p)) +} +fn opener_area(w: &MobWorld, p: [i32; 3]) -> Aabb { + let range = w + .world + .chest_openers + .get(&(p[0], p[1], p[2])) + .map_or(0.0, |o| o.1) + + 4.0; + Aabb::new( + Vec3::new( + f64::from(p[0]) - range, + f64::from(p[1]) - range, + f64::from(p[2]) - range, + ), + Vec3::new( + f64::from(p[0]) + 1.0 + range, + f64::from(p[1]) + 1.0 + range, + f64::from(p[2]) + 1.0 + range, + ), + ) +} +/// `ChestBlockEntity.startOpen` / `stopOpen` by a golem (interaction range +/// 3): the opener count changes and the first opener or the last closer +/// plays the chest's sound (`ChestBlockEntity.playSound`, at the middle of +/// a double chest from its right half, none from its left). +fn open_or_close(cx: &mut Bx, p: [i32; 3], open: bool) { + let w = cx.w; + let count = w + .world + .chest_openers + .get(&(p[0], p[1], p[2])) + .map_or(0, |o| o.0); + let sounds = if open { count == 0 } else { count == 1 }; + if sounds + && let Some(kind) = w.prop(p[0], p[1], p[2], "type") + && kind != "left" + { + let mut at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]; + if kind == "right" + && let Some(o) = connected(w, p) + { + at[0] += f64::from(o[0] - p[0]) * 0.5; + at[2] += f64::from(o[2] - p[2]) * 0.5; + } + let name = name_at(w, p); + let base = name + .trim_start_matches("minecraft:") + .trim_start_matches("waxed_"); + let sound = match (base.ends_with("copper_chest"), base.split('_').next(), open) { + (false, _, true) => "block.chest.open", + (false, _, false) => "block.chest.close", + (true, Some("weathered"), true) => "block.copper_chest_weathered.open", + (true, Some("weathered"), false) => "block.copper_chest_weathered.close", + (true, Some("oxidized"), true) => "block.copper_chest_oxidized.open", + (true, Some("oxidized"), false) => "block.copper_chest_oxidized.close", + (true, _, true) => "block.copper_chest.open", + (true, _, false) => "block.copper_chest.close", + }; + let pitch = cx.lr.next_float() * 0.1 + 0.9; + cx.events.push(MobEvent::Sound(sound, at, 0.5, pitch)); + } + cx.events.push(MobEvent::ChestOpen { chest: p, open }); +} + +impl Transport { + /// `Behavior.tryStart`: no transport cooldown, not panicking, not + /// leashed; the duration draw, then `start`. + pub(super) fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + let mm = mem(m); + if mm.transport_items_cooldown_ticks.present() || mm.is_panicking.present() { + return false; + } + if m.extra.leash.is_some() { + return false; + } + self.running = true; + self.end = cx.now + i64::from(cx.lr.next_int_bound(1).unwrap_or(0)) + 60; + m.ai.nav.below_surface = true; + true + } + pub(super) fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + let mm = mem(m); + let can_still = !mm.transport_items_cooldown_ticks.present() + && !mm.is_panicking.present() + && m.extra.leash.is_none(); + if !can_still { + self.do_stop(m, cx); + return; + } + self.tick(m, cx); + } + pub(super) fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + self.running = false; + self.on_start_travelling(m, cx); + m.ai.nav.below_surface = false; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Bx) { + let updated = self.update_invalid_target(m, cx); + let Some(target) = self.target.clone() else { + // `this.stop(..)`: the stop effects, the behaviour still running. + self.on_start_travelling(m, cx); + m.ai.nav.below_surface = false; + return; + }; + if updated { + return; + } + if self.state == State::Queuing && !self.another_interacting(m, cx.w, &target) { + self.state = State::Travelling; + self.walk_towards(m); + } + if self.state == State::Travelling { + let c = center(m); + if within(cx.w, m, 3.0, &target, c) && self.another_interacting(m, cx.w, &target) { + stop_in_place(m); + self.state = State::Queuing; + } else if within(cx.w, m, range(m), &target, c) { + self.interaction = Some(reached_interaction(m, cx.w, &target.halves)); + self.state = State::Interacting; + } else { + self.walk_towards(m); + } + } + if self.state == State::Interacting { + self.on_reached(m, cx, &target); + } + } + fn update_invalid_target(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if self.has_valid_target(m, cx) { + return false; + } + self.stop_targeting(m); + match self.find_target(m, cx.w) { + Some(t) => { + let pos = t.pos; + self.target = Some(t); + self.on_start_travelling(m, cx); + self.set_visited(m, pos); + } + None => self.enter_cooldown(m), + } + true + } + fn has_valid_target(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + let Some(t) = self.target.clone() else { + return false; + }; + let w = cx.w; + let unchanged = matches!( + w.world.block_entities.get(&(t.pos[0], t.pos[1], t.pos[2])), + Some(BlockEntity::Chest(_)) + ) && is_chest_block(&name_at(w, t.pos)); + if !(wanted(w, m, &t.name) && unchanged) || blocked(w, t.pos) { + return false; + } + if self.state != State::Travelling { + return true; + } + if self.valid_travelling_path(m, w, &t) { + return true; + } + self.mark_unreachable(m, t.pos); + false + } + fn valid_travelling_path(&mut self, m: &mut Mob, w: &MobWorld, t: &Target) -> bool { + let path = match &m.ai.nav.path { + Some(p) => Some(p.clone()), + None => m.create_path_to(w, t.pos, 0), + }; + let from = match path.as_ref().and_then(|p| p.end()) { + Some(n) => [f64::from(n.x) + 0.5, f64::from(n.y), f64::from(n.z) + 0.5], + None => [m.position.x, m.position.y, m.position.z], + }; + let from = [from[0], from[1] + m.bounds().size().y / 2.0, from[2]]; + let reach = within(w, m, range(m), t, from); + (path.is_none() && !reach) || reach && sees_a_side(w, t.pos, from) + } + fn find_target(&self, m: &Mob, w: &MobWorld) -> Option { + let bx = m.position.x.floor() as i32; + let by = m.position.y.floor() as i32; + let bz = m.position.z.floor() as i32; + let (h, v): (i32, i32) = if m.extra.mount.is_some() { + (1, 1) + } else { + (32, 8) + }; + let visited = mem_list(m, false); + let unreachable = mem_list(m, true); + let (cx, cz) = (bx >> 4, bz >> 4); + let r = h.div_euclid(16) + 1; + // Each chunk's block entities in their HashMap's order. + let mut by_chunk: std::collections::HashMap<(i32, i32), Vec<[i32; 3]>> = Default::default(); + for (k, e) in &w.world.block_entities { + if matches!(e, BlockEntity::Chest(_)) { + by_chunk + .entry((k.0 >> 4, k.2 >> 4)) + .or_default() + .push([k.0, k.1, k.2]); + } + } + let mut best: Option<(f64, Target)> = None; + for z in cz - r..=cz + r { + for x in cx - r..=cx + r { + let Some(list) = by_chunk.get_mut(&(x, z)) else { + continue; + }; + list.sort(); + let mut map: JavaHashMap = JavaHashMap::default(); + for p in list.iter() { + map.put(PosKey(*p), ()); + } + for (key, _) in map.entries() { + let p = key.0; + let d = (f64::from(p[0]) + 0.5 - m.position.x).powi(2) + + (f64::from(p[1]) + 0.5 - m.position.y).powi(2) + + (f64::from(p[2]) + 0.5 - m.position.z).powi(2); + if best.as_ref().map_or(f64::from(f32::MAX), |b| b.0) <= d { + continue; + } + // The search box: the mob's block grown by h, v, h. + let inside = (bx - h..bx + 1 + h).contains(&p[0]) + && (by - v..by + 1 + v).contains(&p[1]) + && (bz - h..bz + 1 + h).contains(&p[2]); + if !inside { + continue; + } + let Some(halves) = container(w, p) else { + continue; + }; + let name = name_at(w, p); + let seen = + std::iter::once(p) + .chain(connected(w, p).filter(|o| { + w.world.block_entities.contains_key(&(o[0], o[1], o[2])) + })) + .any(|q| visited.contains(&q) || unreachable.contains(&q)); + if wanted(w, m, &name) && !seen { + best = Some(( + d, + Target { + pos: p, + name, + halves, + }, + )); + } + } + } + } + best.map(|b| b.1) + } + /// `isAnotherMobInteractingWithTarget`: either half has an opener. + fn another_interacting(&self, m: &Mob, w: &MobWorld, t: &Target) -> bool { + let mut chests = vec![t.pos]; + if let Some(o) = connected(w, t.pos) + && w.world.block_entities.contains_key(&(o[0], o[1], o[2])) + { + chests.push(o); + } + chests.iter().any(|p| openers(w, m, *p) > 0) + } + fn walk_towards(&self, m: &mut Mob) { + if let Some(t) = &self.target { + // BehaviorUtils.setWalkAndLookTargetMemories(body, pos, 1, 0). + let mm = mem(m); + mm.look_target.set(Tracker::Block(t.pos)); + mm.walk_target.set(WalkTarget { + target: Tracker::Block(t.pos), + speed: 1.0, + close: 0, + }); + } + } + fn on_reached(&mut self, m: &mut Mob, cx: &mut Bx, t: &Target) { + if !within(cx.w, m, 2.0, t, center(m)) { + self.on_start_travelling(m, cx); + return; + } + self.ticks += 1; + // onTargetInteraction. + mem(m).look_target.set(Tracker::Block(t.pos)); + stop_in_place(m); + if let Some(i) = self.interaction { + let (state, sound) = match i { + Interaction::PickupItem => (cg::GETTING_ITEM, "entity.copper_golem.no_item_get"), + Interaction::PickupNoItem => { + (cg::GETTING_NO_ITEM, "entity.copper_golem.no_item_no_get") + } + Interaction::PlaceItem => (cg::DROPPING_ITEM, "entity.copper_golem.item_drop"), + Interaction::PlaceNoItem => { + (cg::DROPPING_NO_ITEM, "entity.copper_golem.item_no_drop") + } + }; + if self.ticks == 1 { + // container.startOpen, before setOpenedChestPos. + for h in &t.halves { + open_or_close(cx, *h, true); + } + m.extra.opened_chest = Some(t.pos); + m.extra.variant3 = state; + } + if self.ticks == 9 && !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events.push(MobEvent::Sound(sound, at, 1.0, 1.0)); + } + if self.ticks == 60 { + // container.getEntitiesWithContainerOpen().contains(body): + // only a single chest lists its openers (CompoundContainer + // keeps Container's empty list, so a double chest is left + // to the openers recheck). + if t.halves.len() == 1 && has_open(cx.w, m, t.pos) { + open_or_close(cx, t.pos, false); + } + m.extra.opened_chest = None; + } + } + if self.ticks >= 60 { + let items = slots(cx.w, &t.halves); + if held(m).is_none() { + if items.iter().any(Option::is_some) { + self.pick_up(m, cx, &t.halves, &items); + } else { + self.stop_targeting(m); + } + } else if leaving_ok(m, &items) { + self.put_down(m, cx, &t.halves, items); + } else { + self.stop_targeting(m); + } + self.on_start_travelling(m, cx); + } + } + /// `pickUpItems`: up to 16 of the first non-empty slot. + fn pick_up( + &mut self, + m: &mut Mob, + cx: &mut Bx, + halves: &[[i32; 3]], + items: &[Option], + ) { + if let Some((n, s)) = items + .iter() + .enumerate() + .find_map(|(n, s)| s.as_ref().map(|s| (n, s.clone()))) + { + let take = s.count.min(16); + let mut left = s.clone(); + left.count -= take; + let mut got = s; + got.count = take; + if let Some((h, slot)) = slot_at(cx.w, halves, n) { + cx.events.push(MobEvent::ChestSlot { + chest: h, + slot, + stack: (left.count > 0).then_some(left), + }); + } + set_held(m, Some(got)); + } + self.clear_memories(m); + } + /// `putDownItem` (`addItemsToContainer`, which takes from the carried + /// stack all the room a slot had, not what it put there). + fn put_down( + &mut self, + m: &mut Mob, + cx: &mut Bx, + halves: &[[i32; 3]], + items: Vec>, + ) { + let mut carried = held(m).cloned(); + for (n, slot) in items.into_iter().enumerate() { + let Some(stack) = carried.clone() else { break }; + match slot { + None => { + if let Some((h, s)) = slot_at(cx.w, halves, n) { + cx.events.push(MobEvent::ChestSlot { + chest: h, + slot: s, + stack: Some(stack), + }); + } + carried = None; + break; + } + Some(mut there) => { + let max = max_stack(cx.w, &there); + if there.item == stack.item + && there.extra == stack.extra + && there.damage == stack.damage + && there.count < max + { + let room = max - there.count; + let add = room.min(stack.count); + there.count += add; + if let Some((h, s)) = slot_at(cx.w, halves, n) { + cx.events.push(MobEvent::ChestSlot { + chest: h, + slot: s, + stack: Some(there), + }); + } + let left = i64::from(stack.count) - i64::from(room); + if left <= 0 { + carried = None; + break; + } + let mut rest = stack; + rest.count = left as u32; + carried = Some(rest); + } + } + } + } + let emptied = carried.is_none(); + set_held(m, carried); + if emptied { + self.clear_memories(m); + } else { + self.stop_targeting(m); + } + } + fn on_start_travelling(&mut self, m: &mut Mob, _: &mut Bx) { + // CopperGolemAi.onTravelling: clearOpenedChestPos, IDLE. + m.extra.opened_chest = None; + m.extra.variant3 = cg::IDLE; + self.state = State::Travelling; + self.interaction = None; + self.ticks = 0; + } + fn stop_targeting(&mut self, m: &mut Mob) { + self.ticks = 0; + self.target = None; + m.nav_stop(); + mem(m).walk_target.clear(); + } + fn clear_memories(&mut self, m: &mut Mob) { + self.stop_targeting(m); + let mm = mem(m); + mm.visited_block_positions.clear(); + mm.unreachable_transport_block_positions.clear(); + } + fn enter_cooldown(&mut self, m: &mut Mob) { + self.stop_targeting(m); + let mm = mem(m); + mm.transport_items_cooldown_ticks.set(140); + mm.visited_block_positions.clear(); + mm.unreachable_transport_block_positions.clear(); + } + fn set_visited(&mut self, m: &mut Mob, p: [i32; 3]) { + let mut list = mem_list(m, false); + if !list.contains(&p) { + list.push(p); + } + if list.len() > 10 { + self.enter_cooldown(m); + } else { + mem(m).visited_block_positions.set_ttl(list, 6000); + } + } + fn mark_unreachable(&mut self, m: &mut Mob, p: [i32; 3]) { + let mut visited = mem_list(m, false); + visited.retain(|q| *q != p); + let mut unreachable = mem_list(m, true); + if !unreachable.contains(&p) { + unreachable.push(p); + } + if unreachable.len() > 50 { + self.enter_cooldown(m); + } else { + let mm = mem(m); + mm.visited_block_positions.set_ttl(visited, 6000); + mm.unreachable_transport_block_positions + .set_ttl(unreachable, 6000); + } + } +} +fn mem_list(m: &Mob, unreachable: bool) -> Vec<[i32; 3]> { + let Some(mm) = mem_ref(m) else { + return Vec::new(); + }; + let slot = if unreachable { + &mm.unreachable_transport_block_positions + } else { + &mm.visited_block_positions + }; + slot.get().cloned().unwrap_or_default() +} +/// `matchesLeavingItemsRequirement`: an empty container, or one holding the +/// carried item. +fn leaving_ok(m: &Mob, items: &[Option]) -> bool { + let carried = held(m); + items.iter().all(Option::is_none) + || items + .iter() + .flatten() + .any(|s| carried.is_some_and(|c| c.item == s.item)) +} +fn reached_interaction(m: &Mob, w: &MobWorld, halves: &[[i32; 3]]) -> Interaction { + let items = slots(w, halves); + if held(m).is_none() { + if items.iter().any(Option::is_some) { + Interaction::PickupItem + } else { + Interaction::PickupNoItem + } + } else if leaving_ok(m, &items) { + Interaction::PlaceItem + } else { + Interaction::PlaceNoItem + } +} +/// `canSeeAnyTargetSide`: a clip from `eye` to the middle of any face of the +/// chest's block hits that block. +fn sees_a_side(w: &MobWorld, p: [i32; 3], eye: [f64; 3]) -> bool { + let c = Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ); + // Direction order: down, up, north, south, west, east. + let steps = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ]; + let from = Vec3::new(eye[0], eye[1], eye[2]); + steps.iter().any(|s| { + let to = Vec3::new( + c.x + 0.5 * f64::from(s[0]), + c.y + 0.5 * f64::from(s[1]), + c.z + 0.5 * f64::from(s[2]), + ); + w.clip_block_at(from, to) == Some(p) + }) +} diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 55a507fa7..40931fcff 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -131,6 +131,38 @@ impl MobWorld<'_> { }); result.ok().flatten() } + /// Level.clip with COLLIDER shapes and no fluids: the block the segment + /// first hits, if it does. + pub fn clip_block_at(&self, from: Vec3, to: Vec3) -> Option<[i32; 3]> { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let result = traverse_blocks(from, to, 512, |p: BlockPos| { + let state = self.world.block(p.x, p.y, p.z); + if self.facts.is_air(state) { + return None; + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p).map(|_| [p.x, p.y, p.z]) + }); + result.ok().flatten() + } + /// The bounds of the block's collision shape, relative to the block. + pub fn collision_bounds(&self, p: [i32; 3]) -> Option { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let state = self.world.block(p[0], p[1], p[2]); + self.collision + .collision_shape(&mut scene, state, p) + .ok()? + .bounds() + } /// LivingEntity.hasLineOfSight: eye to eye within 128 blocks. pub fn line_of_sight(&self, from_eye: Vec3, to: Vec3) -> bool { let d = diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index f27b27108..15a413491 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -26,6 +26,9 @@ pub struct World { /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// Each chest's `ContainerOpenersCounter`: opener count and largest + /// interaction range. + pub chest_openers: HashMap<(i32, i32, i32), (i32, f64)>, /// `BaseContainerBlockEntity.name`: custom names of container block entities. pub block_names: HashMap<(i32, i32, i32), String>, /// States (by id) whose writes are recorded in `watched_writes` (sculk @@ -116,6 +119,7 @@ impl World { loaded_entities: Vec::new(), modified: HashSet::new(), block_entities: HashMap::new(), + chest_openers: HashMap::new(), block_names: HashMap::new(), watched: Vec::new(), watched_writes: Vec::new(), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 6185d65f0..4a575f30d 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -211,7 +211,7 @@ public final class VanillaMobAiOracle { } } case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } - case "fill", "block" -> s.blocks.add(f); + case "fill", "block", "chest" -> s.blocks.add(f); case "at" -> s.timed.add(new Object[] {Integer.parseInt(f[1]), java.util.Arrays.copyOfRange(f, 2, f.length)}); case "watch" -> { int[] box = new int[6]; @@ -450,9 +450,21 @@ public final class VanillaMobAiOracle { static void place(String[] b, ServerLevel level) throws Exception { var blocks = level.holderLookup(Registries.BLOCK); { - if (b[0].equals("block")) { + if (b[0].equals("block") || b[0].equals("chest")) { BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState(); - level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16); + BlockPos at = new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])); + level.setBlock(at, state, 2 | 16); + // chest X Y Z STATE SLOTS: the slots' contents (item*count, - for empty). + if (b[0].equals("chest") && b.length > 5) { + var chest = (net.minecraft.world.level.block.entity.ChestBlockEntity) level.getBlockEntity(at); + String[] slots = b[5].split(","); + for (int k = 0; k < slots.length; k++) { + if (slots[k].equals("-")) continue; + String[] ic = slots[k].split("\\*"); + chest.setItem(k, new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(ic[0])), Integer.parseInt(ic[1]))); + } + } } else { BlockState state = BlockStateParser.parseForBlock(blocks, b[7], false).blockState(); int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]); @@ -565,6 +577,14 @@ public final class VanillaMobAiOracle { case "leashed", "leashto" -> { // Leashed once every mob exists (below). } + case "hand" -> { + String[] ic = v.split("\\*"); + mob.setItemSlot(net.minecraft.world.entity.EquipmentSlot.MAINHAND, new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(ic[0])), Integer.parseInt(ic[1]))); + } + case "cooldown" -> { + // Set after the seeded constructor draw (below). + } default -> throw new IllegalArgumentException(flag); } } @@ -572,6 +592,15 @@ public final class VanillaMobAiOracle { for (Runnable r : afterAdd) r.run(); mob.getRandom().setSeed(spec.seed); Brain brain = mob.getBrain(); + if (mob instanceof net.minecraft.world.entity.animal.golem.CopperGolem) { + // The constructor's TRANSPORT_ITEMS_COOLDOWN_TICKS draw, made with the seeded + // random; "cooldown=N" then sets it (0: none, transporting at once). + int cooldown = mob.getRandom().nextInt(60, 100); + for (String flag : spec.flags) + if (flag.startsWith("cooldown=")) cooldown = Integer.parseInt(flag.substring(9)); + if (cooldown > 0) brain.setMemory(MemoryModuleType.TRANSPORT_ITEMS_COOLDOWN_TICKS, cooldown); + else brain.eraseMemory(MemoryModuleType.TRANSPORT_ITEMS_COOLDOWN_TICKS); + } @SuppressWarnings("unchecked") Map> sensors = (Map>) get(brain, "sensors"); for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); @@ -722,6 +751,7 @@ public final class VanillaMobAiOracle { } for (int i = 0; i < ENTS.size(); i++) print(t, i, ENTS.get(i)); for (BlockPos h : heartPositions) printHeart(t, level, h); + for (String[] b : s.blocks) if (b[0].equals("chest")) printChest(t, s, level, b); for (String sound : SOUNDS) out.println(t + " sound " + sound); for (var w : watched.entrySet()) { BlockState now = level.getBlockState(w.getKey()); @@ -755,6 +785,19 @@ public final class VanillaMobAiOracle { return sb.toString(); } + /** A chest's slots (trailing empties dropped) and opener count. */ + static void printChest(int t, Scenario s, ServerLevel level, String[] b) throws Exception { + BlockPos at = new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])); + if (!(level.getBlockEntity(at) instanceof net.minecraft.world.level.block.entity.ChestBlockEntity chest)) return; + List slots = new ArrayList<>(); + for (int k = 0; k < chest.getContainerSize(); k++) slots.add(stack(chest.getItem(k))); + while (!slots.isEmpty() && slots.getLast().equals("-")) slots.removeLast(); + Object counter = get(chest, "openersCounter"); + out.println(t + " chest " + (at.getX() - s.originX) + "," + at.getY() + "," + (at.getZ() - s.originZ) + " " + + (slots.isEmpty() ? "-" : String.join(",", slots)) + " " + + ((net.minecraft.world.level.block.entity.ContainerOpenersCounter) counter).getOpenerCount()); + } + /** A heart's block state and block entity, and the level random. */ static void printHeart(int t, ServerLevel level, BlockPos at) throws Exception { StringBuilder sb = new StringBuilder(); @@ -913,6 +956,11 @@ public final class VanillaMobAiOracle { sb.append("\tmem ").append(String.join(" ", mem)); } if (m instanceof Villager villager) sb.append("\tvx ").append(villager(villager)); + if (m instanceof net.minecraft.world.entity.animal.golem.CopperGolem golem) { + Object opened = get(golem, "openedChestPos"); + sb.append("\tcg ").append(golem.getState().ordinal()).append(' ').append(stack(golem.getMainHandItem())).append(' ') + .append(opened == null ? "-" : pos((BlockPos) opened)); + } out.println(sb); } diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 9abc3f960..9dd7535d4 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -174,6 +174,28 @@ def scenarios(): 'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent', 'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2', 'mob minecraft:trader_llama 3.5 -60 -1.5 0 106 persistent leashto=0 strength=4']) + # Copper golems sorting chests (TransportItemsBetweenContainers): from a copper chest to a chest, + # skipping a chest without the carried item, queueing at a chest another golem has open, a double + # chest, a blocked copper chest, a part-full chest, and idling with nothing to carry. + def chest(x, z, slots='-', kind='chest', facing='north', half='single', y=-60): + return f'chest {x} {y} {z} minecraft:{kind}[facing={facing},type={half},waterlogged=false] {slots}' + golem = 'mob minecraft:copper_golem {} -60 {} {} {} persistent cooldown=0' + add('golem_copper_to_chest', 600, [chest(4, 0, 'cobblestone*20,-,iron_ingot*5', 'copper_chest'), + chest(-4, 3), golem.format(0.5, 0.5, 0, 111)]) + add('golem_skips_other_items', 700, [chest(4, 0, 'cobblestone*40', 'copper_chest'), + chest(-3, 0, 'dirt*3'), chest(-6, 5, 'cobblestone*10'), + golem.format(0.5, 0.5, 90, 112)]) + add('golem_queue', 600, [chest(3, 0, 'oak_log*48,stick*7', 'copper_chest'), chest(-4, 0), + golem.format(0.5, 0.5, 0, 113), golem.format(0.5, 3.5, 180, 114)]) + add('golem_double_chest', 600, [chest(4, 0, 'apple*30', 'exposed_copper_chest'), + chest(-4, 2, '-', 'chest', 'north', 'left'), chest(-5, 2, 'apple*2', 'chest', 'north', 'right'), + golem.format(0.5, 0.5, 0, 115)]) + add('golem_blocked_chest', 400, [chest(3, 0, 'sand*5', 'copper_chest'), 'block 3 -59 0 minecraft:stone', + chest(-5, -2, 'gravel*9', 'oxidized_copper_chest'), chest(0, 6), + golem.format(0.5, 0.5, 0, 116)]) + add('golem_part_full', 500, [chest(-3, 1, 'cobblestone*60,cobblestone*64,-,cobblestone*63'), + 'mob minecraft:copper_golem 0.5 -60 0.5 0 117 persistent cooldown=0 hand=cobblestone*16']) + add('golem_idle', 400, ['player 4.5 -60 2.5', 'mob minecraft:copper_golem 0.5 -60 0.5 0 118 persistent']) return s @@ -193,7 +215,7 @@ def write_scenarios(path, chosen): elif f[0] == 'mob': f[2] = repr(float(f[2]) + ox) f[4] = repr(float(f[4]) + oz) - elif f[0] in ('block', 'heart'): + elif f[0] in ('block', 'heart', 'chest'): f[1] = str(int(f[1]) + ox) f[3] = str(int(f[3]) + oz) elif f[0] == 'fill': @@ -228,6 +250,9 @@ def parse(path): if parts[1] == 'heart': cur.setdefault('hearts', {}).setdefault(t, []).append(line.split(' ', 2)[2]) continue + if parts[1] == 'chest': + cur.setdefault('chests', {}).setdefault(t, []).append(parts[2]) + continue mob = int(parts[1]) row = {} if len(parts) > 2: @@ -321,8 +346,8 @@ def compare(vanilla, rust, fields=None): report.append(f'{name}: hearts differ at tick {t}: vanilla {v.get("hearts", {}).get(t)} | horizon {r.get("hearts", {}).get(t)}') clean = False break - # Sounds and watched block changes: first differing tick. - for kind in ('sounds', 'blocks'): + # Sounds, watched block changes and chest contents: first differing tick. + for kind in ('sounds', 'blocks', 'chests'): va, ra = v.get(kind, {}), r.get(kind, {}) for t in sorted(set(va) | set(ra)): if va.get(t, []) != ra.get(t, []): From 71e677ed6a978274a76d3d783522aafc9ec09f54 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:40:50 +0200 Subject: [PATCH 07/18] dedicated_server: settle the generated world in game ticks, without random ticks The world was saved 20 wall-clock seconds after force-loading the area, so on a busy machine chunks were still generating or their fluids flowing, and random ticks changed blocks while the client was being sent its chunks: which chunks differed varied from run to run. Wait until every force-loaded chunk is loaded and 600 game ticks have passed, with random_tick_speed 0. Co-Authored-By: Claude Opus 5.5 --- tools/test_dedicated_server_parity.py | 37 ++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 044d75bee..e7bac561d 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -163,6 +163,36 @@ class Server: self.log.close() +def settle(server, ticks=600, timeout=600): + """Waits until every force-loaded chunk is loaded, then for `ticks` game + ticks, so their fluids have finished flowing however slow the machine.""" + deadline = time.time() + timeout + offsets = range(-80, 81, 16) + for poll in range(1_000_000): + start = len(server.lines) + for dx in offsets: + for dz in offsets: + server.console(f'execute unless loaded ~{dx} ~ ~{dz} run say unloaded') + server.console(f'say poll {poll}') + server.wait_for(rf'\[Server\] poll {poll}$', timeout=max(1, deadline - time.time())) + if not any(l.endswith('[Server] unloaded') for l in server.lines[start:]): + break + time.sleep(2) + + def game_time(): + start = len(server.lines) + server.console('time query gametime') + while time.time() < deadline: + for line in server.lines[start:]: + if m := re.search(r'The time is (\d+)', line): + return int(m.group(1)) + time.sleep(0.2) + raise AssertionError(f'{server.log_path.name}: no game time in {timeout} s') + until = game_time() + ticks + while game_time() < until: + time.sleep(2) + + def legacy_ping(port): """The reply to a 1.6 client's 0xFE 0x01 0xFA MC|PingHost query (LegacyQueryHandler).""" host = 'localhost' @@ -330,9 +360,14 @@ def main(): # Vanilla keeps no spawn chunks: force-load the area the client is # sent and its neighbours (the console stands at the world spawn) so # both servers load full chunks instead of finishing proto-chunks. + # Random ticks change blocks while the client is being sent its + # chunks, more of them the busier the machine: none, so both servers + # send the world as it was saved. + server.console('gamerule random_tick_speed 0') + server.wait_for(r'random_tick_speed', timeout=30) server.console('forceload add ~-80 ~-80 ~80 ~80') server.wait_for(r'chunks in the Overworld are now force loaded|forceloaded|force loaded', timeout=60) - time.sleep(20) + settle(server) server.console('forceload remove all') server.console('save-all flush') server.wait_for(r'Saved the game', timeout=120) From 75336660bb0db8ad73710b93899c6174f861602d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:42:57 +0200 Subject: [PATCH 08/18] Compare the focused chat with vanilla The HUD harness's chat cases now also draw the chat as the open chat screen does: foreground, at the focused height, scrolled, with the scroll bar. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/hud_fixture/kinds.rs | 6 +++++- .../java/dev/horizonlab/parity/VanillaHudOracle.java | 10 +++++++++- tools/hud_parity_cases.py | 4 +++- tools/test_hud_parity.py | 3 ++- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index 550da026b..850db5218 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -322,5 +322,9 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { false, ); } - chat.layout(h, c["now"].as_u64().unwrap_or(0), false) + let focused = c["focused"].as_bool().unwrap_or(false); + if let Some(n) = c["scroll"].as_i64() { + chat.scroll_by(n as i32, focused); + } + chat.layout(h, c["now"].as_u64().unwrap_or(0), focused) } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java index dac37a2f7..b1e6cd619 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java @@ -593,7 +593,15 @@ public final class VanillaHudOracle { default -> chat.addPlayerMessage(text, null, null); } } - chat.extractRenderState(capture, font, i("now", 0), 0, 0, net.minecraft.client.gui.components.ChatComponent.DisplayMode.BACKGROUND, false); + // Focused: the chat screen is open (isChatFocused), the chat is drawn in the + // foreground and may be scrolled. + boolean focused = c.has("focused") && b("focused"); + if (focused) put(gui, net.minecraft.client.gui.Gui.class, "screen", alloc(net.minecraft.client.gui.screens.ChatScreen.class)); + if (c.has("scroll")) chat.scrollChat(i("scroll", 0)); + chat.extractRenderState(capture, font, i("now", 0), 0, 0, focused + ? net.minecraft.client.gui.components.ChatComponent.DisplayMode.FOREGROUND + : net.minecraft.client.gui.components.ChatComponent.DisplayMode.BACKGROUND, false); + put(gui, net.minecraft.client.gui.Gui.class, "screen", null); } default -> throw new IllegalArgumentException(c.get("kind").getAsString()); } diff --git a/tools/hud_parity_cases.py b/tools/hud_parity_cases.py index 3957dcb70..711b2a3f5 100644 --- a/tools/hud_parity_cases.py +++ b/tools/hud_parity_cases.py @@ -225,7 +225,9 @@ def chat(rng, n): 'chatScale': rng.choice([1.0, 1.0, 0.5, 0.0 + 0.75, 0.25]), 'chatWidth': rng.choice([1.0, 1.0, 0.5, 0.0, 0.3]), 'chatOpacity': rng.choice([1.0, 0.5, 0.0, 0.25]), 'textOpacity': rng.choice([0.5, 0.0, 1.0, 0.25]), 'chatLineSpacing': rng.choice([0.0, 0.0, 0.5, 1.0, 0.25]), 'chatHeightUnfocused': rng.choice([70 / 160, 1.0, 0.0, 0.5]), - 'chatHeightFocused': 1.0} + 'chatHeightFocused': rng.choice([1.0, 1.0, 0.5, 0.25]), + # The chat screen open: foreground, focused height, scrolled up or down. + 'focused': rng.random() < 0.5, 'scroll': rng.choice([0, 0, 1, 3, 7, 20, -2, 1000])} # Generators by kind: (rng, index) -> case. Cases are drawn round-robin. diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py index afaf7decd..544e5d544 100644 --- a/tools/test_hud_parity.py +++ b/tools/test_hud_parity.py @@ -23,7 +23,8 @@ Case kinds (`tools/hud_parity_cases.py`), drawn round-robin: overlays extractCameraOverlays (vignette, spyglass and scopeScale, pumpkin, powder snow, portal, nausea) and extractSleepOverlay chat ChatComponent: wrapping (StringSplitter, indents), fades, - tags, scale, width, height and spacing options + tags, scale, width, height and spacing options, focused + (the chat screen open: foreground, scrolled, scroll bar) test_hud_parity.py [--count N] [--detail N] [--kind K] """ From 4093112bb66d04f10d81dfbcac29d37ffca4f9eb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:43:32 +0200 Subject: [PATCH 09/18] Update the README for player skins, the focused chat and copper golem sorting Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b0d4ee7f6..8dd194fb5 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete and verified against vanilla by differential tests). The percentage is the average; `tests/test_parity.py` keeps it in sync with this table. Last audited 2026-10-12 against the harness results: 270 harnesses pass. Two still differ -from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and +from vanilla in places: `mob_ai` (78 of 79 scenarios; a tempted ghastling) and `sculk` (427 of 435; shrieker warnings and warden summoning). | Subsystem | Score | Main gaps | @@ -134,11 +134,11 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and | Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included | | World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla | | Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded | -| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing | +| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (78 of 79 scenarios, villager and copper golem brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing | | Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla | -| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), and the player list matches over 844,758 draw calls; the focused chat is not compared and player list heads use default skins | +| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), the player list matches over 872,000 draw calls with heads drawn from players' skins (authlib's textures, SkinManager's lookup, legacy skin conversion), and the chat matches focused and scrolled; the chat input box and command suggestions are not compared, and there is no resource pack screen | | Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla | -| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers (6,000 cases), crafters (4,000 crafts) and block entity removal (containers spill, 4,000 cases) match vanilla; 8 of 435 sculk scenarios differ (shrieker warnings and warden summoning) and the copper golem's chest sorting is not compared | +| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers (6,000 cases), crafters (4,000 crafts) and block entity removal (containers spill, 4,000 cases) match vanilla; copper golems sort chests as vanilla's brain does (7 scenarios, tick for tick); 8 of 435 sculk scenarios differ (shrieker warnings and warden summoning) | ### What's new since the previous version From 7322bba2b59895e3afc8c878b1a5ccec832dc945 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:51:40 +0200 Subject: [PATCH 10/18] dedicated_server: read the game time as the console prints it Co-Authored-By: Claude Opus 5.5 --- tools/test_dedicated_server_parity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index e7bac561d..0f27d599c 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -184,7 +184,7 @@ def settle(server, ticks=600, timeout=600): server.console('time query gametime') while time.time() < deadline: for line in server.lines[start:]: - if m := re.search(r'The time is (\d+)', line): + if m := re.search(r'The (?:game )?time is (\d+)', line): return int(m.group(1)) time.sleep(0.2) raise AssertionError(f'{server.log_path.name}: no game time in {timeout} s') From 4078118c711cc3695dfd584bc0bdcfbac18f8ee4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:54:23 +0200 Subject: [PATCH 11/18] Generate superflat worlds with their layers (FlatLevelSource) Horizon generated noise terrain in minecraft:flat worlds. Since chunk streaming finishes the corners of the spawn neighbourhood, save_roundtrip's flat test world got four noise chunks where vanilla had saved flat proto chunks. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/flatgen.rs | 73 ++++++++++++++++++++++++++++ crates/horizon-client/src/game.rs | 23 ++++++++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/save.rs | 12 ++++- 4 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-client/src/flatgen.rs diff --git a/crates/horizon-client/src/flatgen.rs b/crates/horizon-client/src/flatgen.rs new file mode 100644 index 000000000..72245a4d3 --- /dev/null +++ b/crates/horizon-client/src/flatgen.rs @@ -0,0 +1,73 @@ +//! FlatLevelSource: superflat worlds (`minecraft:flat` generator). +use crate::{chunk::Chunk, streaming::ChunkGenerator}; +use horizon_world::{nbt::Tag, registry::BlockRegistry}; + +/// The layers of a flat generator, bottom up from the world's minimum Y. +pub struct FlatTerrain { + layers: Vec, + biome: u16, +} +impl FlatTerrain { + /// The overworld generator of `world_gen_settings` (`data.dimensions`), if it + /// is flat. Its `features` and `lakes` decorate the world; a world without + /// them (the default) gets only its layers, as FlatLevelSource places them. + pub fn from_settings( + settings: &Tag, + registry: &BlockRegistry, + biomes: &crate::biome::Biomes, + ) -> Option { + let generator = settings + .get("dimensions")? + .get("minecraft:overworld")? + .get("generator")?; + if crate::save::text(generator.get("type"))?.trim_start_matches("minecraft:") != "flat" { + return None; + } + let s = generator.get("settings")?; + let biome = crate::save::text(s.get("biome")).unwrap_or_else(|| "minecraft:plains".into()); + let mut layers = Vec::new(); + if let Some(Tag::List(list)) = s.get("layers") { + for layer in list { + let block = crate::save::text(layer.get("block"))?; + let height = crate::save::number(layer.get("height")).unwrap_or(0).max(0); + let state = registry.default_state(&block)?.0 as u16; + layers.extend(std::iter::repeat_n(state, height as usize)); + } + } + Some(Self { + layers, + biome: biomes.id(&biome), + }) + } +} +impl ChunkGenerator for FlatTerrain { + type Worker = (); + fn worker(&self) {} + fn proto(&self, _: &mut (), cx: i32, cz: i32) -> crate::streaming::Proto { + let mut chunk = Chunk::empty(cx, cz); + for s in &mut chunk.sections { + std::sync::Arc::make_mut(s).biomes = horizon_core::paletted::PalettedContainer::new( + crate::chunk::BIOME_STRATEGY, + u32::from(self.biome), + ); + } + for (i, &block) in self.layers.iter().enumerate().take(384) { + if block == 0 { + continue; + } + for z in 0..16 { + for x in 0..16 { + chunk.set(x, -64 + i as i32, z, block); + } + } + } + for s in &mut chunk.sections { + std::sync::Arc::make_mut(s).compact(); + } + Box::new(chunk) + } + /// FlatLevelSource.spawnOriginalMobs is empty: no generation-time spawns. + fn finish(&self, proto: crate::streaming::Proto) -> Chunk { + *proto.downcast::().expect("flat terrain proto") + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 972ad6fb8..d0509bf2a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5236,7 +5236,28 @@ impl Game<'_> { dim.id(), ))); let res = &*self.res; - let mut streaming = if self.options.test_terrain && dim == Dim::Overworld { + let flat = (dim == Dim::Overworld) + .then(|| horizon_client::save::world_gen_settings(world_root)) + .flatten() + .and_then(|s| { + horizon_client::flatgen::FlatTerrain::from_settings( + &s, + res.assets.registry, + &res.biomes, + ) + }); + let mut streaming = if let Some(inner) = flat { + Streaming::new( + Arc::new(Persistent { + inner: Arc::new(inner), + save: save.clone(), + registry: res.assets.clone(), + biomes: res.biomes.clone(), + }), + res.context.clone(), + res.threads, + ) + } else if self.options.test_terrain && dim == Dim::Overworld { let inner = Arc::new(TestTerrain::new(res.assets.registry, &res.biomes)?); Streaming::new( Arc::new(Persistent { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 4e6d6bf05..c888a1b60 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -41,6 +41,7 @@ pub mod entities; pub mod entity_nbt; pub mod environment; pub mod fastutil_order; +pub mod flatgen; pub mod fog; pub mod font; pub mod gamerules; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 96965431f..1006534c5 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -46,7 +46,7 @@ pub const VERSION_NAME: &str = "26.3"; fn string(s: &str) -> Tag { Tag::String(s.into()) } -pub(crate) fn text(tag: Option<&Tag>) -> Option { +pub fn text(tag: Option<&Tag>) -> Option { match tag { Some(Tag::String(s)) => Some(s.to_string_lossy()), _ => None, @@ -1340,6 +1340,16 @@ fn read_saved_data(world: &Path, name: &str) -> Option { .get("data") .cloned() } +/// The world's generator settings: world_gen_settings.dat (26.3) or +/// level.dat's Data.WorldGenSettings. +pub fn world_gen_settings(world: &Path) -> Option { + read_saved_data(world, "world_gen_settings").or_else(|| { + read_dat(&world.join("level.dat"))? + .get("Data")? + .get("WorldGenSettings") + .cloned() + }) +} fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> { write_dat( &saved_data_path(world, name), From 85242053e2da8773a0809bdaa9cf26ba512ce4c3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:59:11 +0200 Subject: [PATCH 12/18] save_roundtrip: accept the promotion of vanilla's border proto chunks Co-Authored-By: Claude Opus 5.5 --- tools/test_save_roundtrip_parity.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index 11dfdae56..ec28c90f8 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -52,6 +52,12 @@ IGNORED = { r'^chunk\.LastUpdate$': 'game time of the save (Horizon saves at its own time)', r'^chunk\.InhabitedTime$': 'ticks the chunk was loaded; differs by the time Horizon ran', r'^chunk\.isLightOn$': 'light is recomputed by vanilla when absent', + # Vanilla's server (view distance 4) leaves a border of proto chunks; Horizon's + # render distance 6 may finish some, as vanilla does when it loads the world at + # that distance. Their blocks are still compared; only what a full chunk saves + # differently (no worldgen heightmaps, entities in entities/) is accepted. + r'^chunk\.promoted\.(Status|Heightmaps\.(OCEAN_FLOOR_WG|WORLD_SURFACE_WG)|entities)$': + 'a proto chunk vanilla left at its view distance, finished by Horizon', # Horizon keeps simulating between loading and saving (it needs a few seconds of # chunk generation first), so counters and positions of live things move on. r'^chunk\.block_entities\.\(2, -60, 5\)\.(cooking_time_spent|lit_time_remaining|Items\[\]\.count)$': @@ -445,6 +451,8 @@ def compare_chunks(vanilla, horizon, report): ha, hs = normalize_chunk(horizon[key]) out = [] diff(va, ha, 'chunk', out) + if va.get('Status') != 'minecraft:full' and ha.get('Status') == 'minecraft:full': + out = [(path.replace('chunk.', 'chunk.promoted.', 1), p, q) for path, p, q in out] for y in sorted(set(vs) | set(hs)): empty = {'blocks': ['minecraft:air'] * 4096, 'biomes': None, 'BlockLight': None, 'SkyLight': None} a, b = vs.get(y, empty), hs.get(y, empty) From b15db4749f1f3b8061834ff3a001fc8c4705b75d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:04:17 +0200 Subject: [PATCH 13/18] Net harness client: wait for each chat reply instead of 1.5 s On a busy machine the /list reply sometimes came after the client had left. Each step now waits for a new chat line, up to 15 s. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/net_harness.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/net_harness.rs b/crates/horizon-client/src/game/net_harness.rs index 755a4c562..d9bb6a74b 100644 --- a/crates/horizon-client/src/game/net_harness.rs +++ b/crates/horizon-client/src/game/net_harness.rs @@ -21,6 +21,7 @@ impl Game<'_> { let mut quiet_since = Instant::now(); let mut step = 0; let mut step_at = Instant::now(); + let mut chat_at = 0; let mut position = None; let mut chunks = 0; let mut error = None; @@ -44,6 +45,10 @@ impl Game<'_> { last_chunks = count; quiet_since = now; } + // Each step waits for what it sent to be answered (its chat line, + // the /list reply), however busy the machine, up to 15 s. + let shown = self.remote.as_ref().map_or(0, |r| r.chat.len()); + let answered = shown > chat_at || now - step_at > Duration::from_secs(15); match step { 0 if spawned_at.is_some() && count > 0 @@ -53,13 +58,15 @@ impl Game<'_> { self.send_chat("hello from the horizon client"); step = 1; step_at = now; + chat_at = shown; } - 1 if now - step_at > Duration::from_millis(1500) => { + 1 if answered => { self.send_chat("/list"); step = 2; step_at = now; + chat_at = shown; } - 2 if now - step_at > Duration::from_millis(1500) => { + 2 if answered => { step = 3; break; } From 7826a221c5c9d01d6e251a5cd3a78d09875c3a08 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:32:48 +0200 Subject: [PATCH 14/18] jmath: satisfy clippy (fdlibm's constants and NaN idiom, verbatim) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-core/src/jmath.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/horizon-core/src/jmath.rs b/crates/horizon-core/src/jmath.rs index 90bb9abfe..6d94b835b 100644 --- a/crates/horizon-core/src/jmath.rs +++ b/crates/horizon-core/src/jmath.rs @@ -124,7 +124,7 @@ fn with_hi(x: f64, high: i32) -> f64 { /// `java.lang.FdLibm` ports (`StrictMath`) of what the `libm` crate computes /// differently. -#[allow(clippy::excessive_precision)] // fdlibm's constants, verbatim. +#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::eq_op)] // fdlibm's constants and NaN, verbatim. pub mod fdlibm { use super::{hi, with_hi}; @@ -337,7 +337,7 @@ pub mod fdlibm { /// HotSpot's AArch64 `Math.sin` / `Math.cos` stubs /// (`MacroAssembler::generate_dsin_dcos`): fdlibm with fused multiply-adds. /// Exposed on every architecture so they can be tested anywhere. -#[allow(clippy::excessive_precision, clippy::unreadable_literal)] // HotSpot's tables, verbatim. +#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::unreadable_literal)] // HotSpot's tables, verbatim. pub mod aarch64 { use super::hi; @@ -474,7 +474,7 @@ pub mod aarch64 { } fn sin_cos(x: f64, is_cos: bool) -> f64 { - let ix = (hi(x) & 0x7fff_ffff) as i32; + let ix = hi(x) & 0x7fff_ffff; if ix < 0x3e400000 { return if is_cos { 1.0 } else { x }; } From 4ce4e983e70eacbeacda304d2fd3646e369a183e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:33:03 +0200 Subject: [PATCH 15/18] jmath: rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/horizon-core/src/jmath.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/horizon-core/src/jmath.rs b/crates/horizon-core/src/jmath.rs index 6d94b835b..c88a8c81d 100644 --- a/crates/horizon-core/src/jmath.rs +++ b/crates/horizon-core/src/jmath.rs @@ -124,7 +124,8 @@ fn with_hi(x: f64, high: i32) -> f64 { /// `java.lang.FdLibm` ports (`StrictMath`) of what the `libm` crate computes /// differently. -#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::eq_op)] // fdlibm's constants and NaN, verbatim. +// fdlibm's constants and NaN, verbatim. +#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::eq_op)] pub mod fdlibm { use super::{hi, with_hi}; @@ -337,7 +338,8 @@ pub mod fdlibm { /// HotSpot's AArch64 `Math.sin` / `Math.cos` stubs /// (`MacroAssembler::generate_dsin_dcos`): fdlibm with fused multiply-adds. /// Exposed on every architecture so they can be tested anywhere. -#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::unreadable_literal)] // HotSpot's tables, verbatim. +// HotSpot's tables, verbatim. +#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::unreadable_literal)] pub mod aarch64 { use super::hi; From b1a560264d40028184aac1d30d9a646292b1e8ff Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:33:20 +0200 Subject: [PATCH 16/18] jmath: rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/horizon-core/src/jmath.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-core/src/jmath.rs b/crates/horizon-core/src/jmath.rs index c88a8c81d..57775c674 100644 --- a/crates/horizon-core/src/jmath.rs +++ b/crates/horizon-core/src/jmath.rs @@ -339,7 +339,11 @@ pub mod fdlibm { /// (`MacroAssembler::generate_dsin_dcos`): fdlibm with fused multiply-adds. /// Exposed on every architecture so they can be tested anywhere. // HotSpot's tables, verbatim. -#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::unreadable_literal)] +#[allow( + clippy::excessive_precision, + clippy::approx_constant, + clippy::unreadable_literal +)] pub mod aarch64 { use super::hi; From 66114adfd9a85398e31188f305b2f03985641a7b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:40:01 +0200 Subject: [PATCH 17/18] save_roundtrip: promote only the fields a full chunk saves differently Co-Authored-By: Claude Opus 5.5 --- tools/test_save_roundtrip_parity.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index ec28c90f8..317956a40 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -452,7 +452,9 @@ def compare_chunks(vanilla, horizon, report): out = [] diff(va, ha, 'chunk', out) if va.get('Status') != 'minecraft:full' and ha.get('Status') == 'minecraft:full': - out = [(path.replace('chunk.', 'chunk.promoted.', 1), p, q) for path, p, q in out] + promoted = re.compile(r'^chunk\.(Status|Heightmaps\.\w+_WG|entities)$') + out = [(path.replace('chunk.', 'chunk.promoted.', 1) if promoted.match(path) else path, p, q) + for path, p, q in out] for y in sorted(set(vs) | set(hs)): empty = {'blocks': ['minecraft:air'] * 4096, 'biomes': None, 'BlockLight': None, 'SkyLight': None} a, b = vs.get(y, empty), hs.get(y, empty) From 8976bd37d4bcbe006c56e936a64b7d4a6daaddec Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:47:36 +0200 Subject: [PATCH 18/18] Select resource packs as vanilla's PackSelectionModel does, compared with vanilla horizon_client::packs::SelectionModel ports PackRepository's selection and PackSelectionModel (default positions, fixed and required packs, moving up and down, commit), and the pack screen uses it. The new pack_selection harness drives vanilla's model and Horizon's through 4,000 random action sequences; every state matches. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- .../examples/pack_selection_fixture.rs | 100 ++++++++++ crates/horizon-client/src/game/packs.rs | 35 ++-- crates/horizon-client/src/options_ui.rs | 61 +++--- crates/horizon-client/src/packs.rs | 181 ++++++++++++++++++ .../parity/VanillaPackSelectionOracle.java | 111 +++++++++++ tools/test_pack_selection_parity.py | 98 ++++++++++ 7 files changed, 539 insertions(+), 53 deletions(-) create mode 100644 crates/horizon-client/examples/pack_selection_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java create mode 100644 tools/test_pack_selection_parity.py diff --git a/README.md b/README.md index 0c70f54e6..4ef3f3cb1 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete and verified against vanilla by differential tests). The percentage is the average; `tests/test_parity.py` keeps it in sync with this table. Last audited 2026-10-12 against the harness results: 270 harnesses pass. Two still differ -from vanilla in places: `mob_ai` (78 of 79 scenarios; a tempted ghastling) and +from vanilla in places: `mob_ai` (83 of 84 scenarios; a tempted ghastling) and `sculk` (427 of 435; shrieker warnings and warden summoning). | Subsystem | Score | Main gaps | @@ -134,9 +134,9 @@ from vanilla in places: `mob_ai` (78 of 79 scenarios; a tempted ghastling) and | Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included | | World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla | | Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded | -| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (78 of 79 scenarios, villager and copper golem brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing | +| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (83 of 84 scenarios, villager and copper golem brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing | | Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla | -| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), the player list matches over 872,000 draw calls with heads drawn from players' skins (authlib's textures, SkinManager's lookup, legacy skin conversion), and the chat matches focused and scrolled; the chat input box and command suggestions are not compared, and there is no resource pack screen | +| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), the player list matches over 872,000 draw calls with heads drawn from players' skins (authlib's textures, SkinManager's lookup, legacy skin conversion), and the chat matches focused and scrolled; the resource pack screen's selection (moving packs between the lists, ordering, required and fixed packs) matches over 4,000 cases; the pack screen's drawing, its incompatibility confirmation, and the chat input box and command suggestions are not compared | | Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla | | Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers (6,000 cases), crafters (4,000 crafts) and block entity removal (containers spill, 4,000 cases) match vanilla; copper golems sort chests as vanilla's brain does (7 scenarios, tick for tick); 8 of 435 sculk scenarios differ (shrieker warnings and warden summoning) | diff --git a/crates/horizon-client/examples/pack_selection_fixture.rs b/crates/horizon-client/examples/pack_selection_fixture.rs new file mode 100644 index 000000000..65ed2471a --- /dev/null +++ b/crates/horizon-client/examples/pack_selection_fixture.rs @@ -0,0 +1,100 @@ +//! Headless transport for the pack selection parity gate: builds each +//! case's `horizon_client::packs::SelectionModel`, applies its actions and +//! writes both lists with each entry's select/unselect/move flags after +//! every action, and the committed selection. +#![forbid(unsafe_code)] +use horizon_client::packs::{Position, Selectable, SelectionModel}; +use serde_json::{Value, json}; +use std::{ + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn lists(m: &SelectionModel) -> Value { + let side = |selected: bool| -> Value { + let list = if selected { &m.selected } else { &m.unselected }; + (0..list.len()) + .map(|i| { + let mut flags = String::new(); + for (on, c) in [ + (m.can_select(selected, i), 's'), + (m.can_unselect(selected, i), 'u'), + (m.can_move_up(selected, i), '^'), + (m.can_move_down(selected, i), 'v'), + ] { + if on { + flags.push(c); + } + } + json!([list[i].id, flags]) + }) + .collect() + }; + json!({"unselected": side(false), "selected": side(true)}) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [inputs, output] = args.as_slice() else { + return Err("usage: pack_selection_fixture INPUTS OUTPUT".into()); + }; + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let c: Value = serde_json::from_str(line)?; + let packs = c["packs"] + .as_array() + .into_iter() + .flatten() + .map(|p| Selectable { + id: p["id"].as_str().unwrap_or("").to_owned(), + required: p["required"].as_bool().unwrap_or(false), + position: if p["position"] == "top" { + Position::Top + } else { + Position::Bottom + }, + fixed: p["fixed"].as_bool().unwrap_or(false), + compatible: p["compat"] == "compatible", + }) + .collect(); + let selected: Vec = c["selected"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect(); + let mut m = SelectionModel::new(packs, &selected); + let mut steps = vec![lists(&m)]; + for op in c["ops"].as_array().into_iter().flatten() { + let sel = op["list"] == "selected"; + let len = if sel { + m.selected.len() + } else { + m.unselected.len() + }; + if len > 0 { + let i = op["index"].as_i64().unwrap_or(0).rem_euclid(len as i64) as usize; + match op["op"].as_str() { + Some("activate") => { + m.activate(sel, i, op["confirm"].as_bool().unwrap_or(false)); + } + Some("up") => { + m.move_by(sel, i, true); + } + Some("down") => { + m.move_by(sel, i, false); + } + _ => return Err(format!("unknown op {op}").into()), + } + } + steps.push(lists(&m)); + } + writeln!(out, "{}", json!({"steps": steps, "committed": m.commit()}))?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index fe438915d..85ff5f508 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -57,28 +57,19 @@ impl Game<'_> { /// PackSelectionModel: available (unselected) and selected (top first). pub(super) fn refresh_pack_lists(&mut self) { let all = packs::discover(&self.vanilla_root(), &packs_dir()); - let selected_ids = &self.settings.resource_packs; - let mut selected: Vec = selected_ids - .iter() - .rev() - .filter_map(|id| { - if id == "vanilla" { - Some(vanilla_entry()) - } else { - all.iter().find(|p| &p.id == id).map(entry) - } - }) - .collect(); - if !selected.iter().any(|p| p.id == "vanilla") { - selected.push(vanilla_entry()); - } - let available = all - .iter() - .filter(|p| !selected_ids.contains(&p.id)) - .map(entry) - .collect(); - self.ui.options.available = available; - self.ui.options.selected = selected; + let mut choices = vec![packs::Selectable::vanilla()]; + choices.extend( + all.iter() + .map(|p| packs::Selectable::optional(&p.id, p.compatible)), + ); + let model = packs::SelectionModel::new(choices, &self.settings.resource_packs); + let mut entries: Vec = all.iter().map(entry).collect(); + entries.push(vanilla_entry()); + let o = &mut self.ui.options; + o.available = entries; + o.selected = Vec::new(); + o.pack_model = model; + o.sync_pack_lists(); } /// Rebuild the overlay and reload what can change while running. pub(super) fn reload_packs(&mut self) { diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index a934e287e..b65cb8904 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -617,6 +617,8 @@ pub struct OptionsUi { /// Packs: (available, selected top-first). pub available: Vec, pub selected: Vec, + /// The selection logic behind the two lists (`PackSelectionModel`). + pub pack_model: crate::packs::SelectionModel, packs_changed: bool, pub in_world: bool, /// Scroll the selected language into the middle on the next layout. @@ -636,6 +638,7 @@ impl Default for OptionsUi { language_search: search, available: Vec::new(), selected: Vec::new(), + pack_model: Default::default(), packs_changed: false, in_world: false, center_language: false, @@ -1586,31 +1589,21 @@ impl OptionsUi { index, .. } => { - if pack.required { - continue; - } + let _ = pack; + // TransferableSelectionList.PackEntry.mouseClicked: the + // right quarters of a selected pack's icon move it, the + // icon otherwise selects or unselects it. let on_icon = x < wd.x + 34.0; - if selected && on_icon && x >= wd.x + 18.0 { - // Right half of the icon: move up (top) or down (bottom). - let up = y < wd.y + 18.0; - let target = if up { - index.checked_sub(1) - } else { - Some(index + 1) - }; - if let Some(t) = target - .filter(|t| *t < self.selected.len() && !self.selected[*t].required) - { - self.selected.swap(index, t); - self.packs_changed = true; - } - } else if selected { - let p = self.selected.remove(index); - self.available.insert(0, p); - self.packs_changed = true; + let m = &mut self.pack_model; + let changed = if selected && on_icon && x >= wd.x + 18.0 { + m.move_by(true, index, y < wd.y + 18.0) } else { - let p = self.available.remove(index); - self.selected.insert(0, p); + // No confirmation screen yet: an incompatible pack + // is selected as if its warning were accepted. + m.activate(selected, index, true) + }; + if changed { + self.sync_pack_lists(); self.packs_changed = true; } } @@ -1620,6 +1613,21 @@ impl OptionsUi { } events } + /// Orders the two entry lists as the selection model has them. + pub fn sync_pack_lists(&mut self) { + let all: Vec = self + .available + .drain(..) + .chain(self.selected.drain(..)) + .collect(); + let pick = |ids: &[crate::packs::Selectable]| -> Vec { + ids.iter() + .filter_map(|s| all.iter().find(|e| e.id == s.id).cloned()) + .collect() + }; + self.available = pick(&self.pack_model.unselected); + self.selected = pick(&self.pack_model.selected); + } pub fn release(&mut self) { self.dragging = None; } @@ -1643,11 +1651,8 @@ impl OptionsUi { } } Page::Packs if self.packs_changed => { - let mut ids: Vec = - self.selected.iter().rev().map(|p| p.id.clone()).collect(); - if !ids.contains(&"vanilla".to_owned()) { - ids.insert(0, "vanilla".into()); - } + // PackSelectionModel.commit: bottom first, required packs kept. + let ids = self.pack_model.commit(); s.resource_packs = ids.clone(); events.push(Event::Packs(ids)); } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index b5205922b..1e0c35358 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -418,6 +418,187 @@ pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf { } } +/// `Pack.Position`: where a pack goes when it is added to a list. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Position { + Top, + Bottom, +} +/// A pack as the selection sees it (`PackSelectionConfig` and its +/// compatibility). +#[derive(Clone, Debug, PartialEq)] +pub struct Selectable { + pub id: String, + pub required: bool, + pub position: Position, + pub fixed: bool, + pub compatible: bool, +} +impl Selectable { + /// A pack from `resourcepacks/` or a built-in optional one: not + /// required, added on top, free to move (`FolderRepositorySource`). + pub fn optional(id: &str, compatible: bool) -> Self { + Self { + id: id.to_owned(), + required: false, + position: Position::Top, + fixed: false, + compatible, + } + } + /// The vanilla pack: required, at the bottom (`BuiltInPackSource`). + pub fn vanilla() -> Self { + Self { + id: "vanilla".into(), + required: true, + position: Position::Bottom, + fixed: false, + compatible: true, + } + } +} + +/// `Pack.Position.insert`: below or above the packs fixed at that end. +fn insert(list: &mut Vec, pack: Selectable, reverse: bool) { + let own = pack.position; + let side = match (own, reverse) { + (Position::Top, false) | (Position::Bottom, true) => Position::Top, + _ => Position::Bottom, + }; + let pinned = |p: &Selectable| p.fixed && p.position == own; + if side == Position::Bottom { + let i = list.iter().take_while(|p| pinned(p)).count(); + list.insert(i, pack); + } else { + let i = list.len() - list.iter().rev().take_while(|p| pinned(p)).count(); + list.insert(i, pack); + } +} + +/// `PackSelectionModel` over a `PackRepository`: the packs not selected +/// (in id order) and the selected ones, top first, as the pack screen's two +/// lists show them. +#[derive(Clone, Debug, Default)] +pub struct SelectionModel { + available: Vec, + pub unselected: Vec, + pub selected: Vec, +} +impl SelectionModel { + /// `available` in any order; `selected` as options.txt lists them, + /// bottom first. + pub fn new(mut available: Vec, selected: &[String]) -> Self { + // PackRepository.available is a TreeMap by id (String.compareTo). + available.sort_by(|a, b| a.id.encode_utf16().cmp(b.id.encode_utf16())); + available.dedup_by(|a, b| a.id == b.id); + let mut m = Self { + available, + ..Self::default() + }; + let mut chosen = m.rebuild(selected); + chosen.reverse(); + m.unselected = m + .available + .iter() + .filter(|p| !chosen.iter().any(|c| c.id == p.id)) + .cloned() + .collect(); + m.selected = chosen; + m + } + /// `PackRepository.rebuildSelected`: the named packs that exist, and + /// every required one. + fn rebuild(&self, ids: &[String]) -> Vec { + let mut out: Vec = ids + .iter() + .filter_map(|id| self.available.iter().find(|p| p.id == *id).cloned()) + .collect(); + for p in &self.available { + if p.required && !out.iter().any(|o| o.id == p.id) { + insert(&mut out, p.clone(), false); + } + } + out + } + fn list(&self, selected: bool) -> &Vec { + if selected { + &self.selected + } else { + &self.unselected + } + } + pub fn can_select(&self, selected: bool, _: usize) -> bool { + !selected + } + pub fn can_unselect(&self, selected: bool, i: usize) -> bool { + selected && !self.selected[i].required + } + pub fn can_move_up(&self, selected: bool, i: usize) -> bool { + i > 0 && !self.list(selected)[i - 1].fixed + } + pub fn can_move_down(&self, selected: bool, i: usize) -> bool { + let list = self.list(selected); + i + 1 < list.len() && !list[i + 1].fixed + } + /// `EntryBase.toggleSelection`: to the other list, at its default + /// position (from the other end). + fn toggle(&mut self, selected: bool, i: usize) { + let (from, to) = if selected { + (&mut self.selected, &mut self.unselected) + } else { + (&mut self.unselected, &mut self.selected) + }; + let p = from.remove(i); + insert(to, p, true); + } + /// `PackEntry`'s activation (a click on the icon, or the select key): + /// select, an incompatible pack only once its confirmation was + /// accepted, or else unselect. True when the lists changed. + pub fn activate(&mut self, selected: bool, i: usize, confirmed: bool) -> bool { + if self.can_select(selected, i) { + if self.unselected[i].compatible || confirmed { + self.toggle(false, i); + return true; + } + false + } else if self.can_unselect(selected, i) { + self.toggle(true, i); + true + } else { + false + } + } + /// Whether activating the entry asks first (`handlePackSelection`'s + /// ConfirmScreen for an incompatible pack). + pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool { + self.can_select(selected, i) && !self.unselected[i].compatible + } + /// `moveUp` / `moveDown` when allowed. + pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool { + let ok = if up { + self.can_move_up(selected, i) + } else { + self.can_move_down(selected, i) + }; + if ok { + let list = if selected { + &mut self.selected + } else { + &mut self.unselected + }; + let p = list.remove(i); + list.insert(if up { i - 1 } else { i + 1 }, p); + } + ok + } + /// `commit`: the repository's selection, bottom first, as options.txt + /// stores it. + pub fn commit(&self) -> Vec { + let ids: Vec = self.selected.iter().rev().map(|p| p.id.clone()).collect(); + self.rebuild(&ids).into_iter().map(|p| p.id).collect() + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java new file mode 100644 index 000000000..6d0cbe30f --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPackSelectionOracle.java @@ -0,0 +1,111 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.gui.screens.packs.PackSelectionModel; +import net.minecraft.network.chat.Component; +import net.minecraft.server.packs.PackLocationInfo; +import net.minecraft.server.packs.PackSelectionConfig; +import net.minecraft.server.packs.repository.Pack; +import net.minecraft.server.packs.repository.PackCompatibility; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.PackSource; +import net.minecraft.world.flag.FeatureFlagSet; + +/** + * Runs the resource pack screen's selection logic: a PackRepository of the + * case's packs (required, default position, fixed position, compatibility) + * with an initial selection, a PackSelectionModel over it, and the actions + * TransferableSelectionList.PackEntry performs on a click or key press: + * select (an incompatible pack only once its ConfirmScreen is accepted), + * unselect, move up, move down. After each action: both lists and every + * entry's canSelect, canUnselect, canMoveUp and canMoveDown; at the end the + * repository's selection after commit. + * + * Input lines: case JSON. Output lines: {steps:[...], committed:[...]} or {error}. + */ +public final class VanillaPackSelectionOracle { + static JsonObject lists(PackSelectionModel model) { + var o = new JsonObject(); + for (String side : new String[] {"unselected", "selected"}) { + var a = new JsonArray(); + var entries = side.equals("selected") ? model.getSelected().toList() : model.getUnselected().toList(); + for (var e : entries) { + var row = new JsonArray(); + row.add(e.getId()); + row.add((e.canSelect() ? "s" : "") + (e.canUnselect() ? "u" : "") + (e.canMoveUp() ? "^" : "") + (e.canMoveDown() ? "v" : "")); + a.add(row); + } + o.add(side, a); + } + return o; + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + JsonObject c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + try { + List packs = new ArrayList<>(); + for (var p : c.getAsJsonArray("packs")) { + var o = p.getAsJsonObject(); + String id = o.get("id").getAsString(); + var location = new PackLocationInfo(id, Component.literal(id), PackSource.DEFAULT, Optional.empty()); + var compatibility = switch (o.get("compat").getAsString()) { + case "old" -> PackCompatibility.TOO_OLD; + case "new" -> PackCompatibility.TOO_NEW; + default -> PackCompatibility.COMPATIBLE; + }; + var metadata = new Pack.Metadata(Component.literal(id), compatibility, FeatureFlagSet.of(), List.of()); + var config = new PackSelectionConfig(o.get("required").getAsBoolean(), + o.get("position").getAsString().equals("top") ? Pack.Position.TOP : Pack.Position.BOTTOM, o.get("fixed").getAsBoolean()); + packs.add(new Pack(location, null, metadata, config)); + } + var repository = new PackRepository(consumer -> packs.forEach(consumer)); + repository.reload(); + List initial = new ArrayList<>(); + for (var s : c.getAsJsonArray("selected")) initial.add(s.getAsString()); + repository.setSelected(initial); + var model = new PackSelectionModel(e -> { }, p -> null, repository, r -> { }); + var steps = new JsonArray(); + steps.add(lists(model)); + for (var step : c.getAsJsonArray("ops")) { + var o = step.getAsJsonObject(); + var entries = o.get("list").getAsString().equals("selected") ? model.getSelected().toList() : model.getUnselected().toList(); + if (!entries.isEmpty()) { + var e = entries.get(Math.floorMod(o.get("index").getAsInt(), entries.size())); + switch (o.get("op").getAsString()) { + // PackEntry.keyPressed(select) / a click on the icon: handlePackSelection or unselect. + case "activate" -> { + if (e.canSelect()) { + if (e.getCompatibility().isCompatible() || o.get("confirm").getAsBoolean()) e.select(); + } else if (e.canUnselect()) { + e.unselect(); + } + } + case "up" -> { if (e.canMoveUp()) e.moveUp(); } + case "down" -> { if (e.canMoveDown()) e.moveDown(); } + default -> throw new IllegalArgumentException(o.toString()); + } + } + steps.add(lists(model)); + } + result.add("steps", steps); + model.commit(); + var committed = new JsonArray(); + for (var p : repository.getSelectedPacks()) committed.add(p.getId()); + result.add("committed", committed); + } catch (Throwable error) { + result.addProperty("error", String.valueOf(error)); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_pack_selection_parity.py b/tools/test_pack_selection_parity.py new file mode 100644 index 000000000..8610d85f3 --- /dev/null +++ b/tools/test_pack_selection_parity.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Compare the resource pack screen's selection with the vanilla client's. + +Each case is a pack repository (packs required or not, added at the top or +the bottom, fixed in place or not, compatible, too old or too new), an +initial selection as options.txt stores it, and the actions the screen's +entries take on a click or key press: select (an incompatible pack only when +its confirmation is accepted), unselect, move up, move down. The Java oracle +(VanillaPackSelectionOracle) runs vanilla's PackRepository and +PackSelectionModel; examples/pack_selection_fixture runs +horizon_client::packs::SelectionModel, which the game's pack screen uses. +After every action both lists, in order, with each entry's canSelect, +canUnselect, canMoveUp and canMoveDown, and the selection committed at the +end must agree. + + test_pack_selection_parity.py [--count N] [--detail N] +""" +import argparse +import json +import os +import random +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab + import test_rust_parity as base + import test_model_baking_parity as baking + +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +IDS = ['vanilla', 'programmer_art', 'file/Faithful.zip', 'file/alpha', 'file/Zeta pack', 'file/zeta', 'file/é', + 'file/0', 'server', 'world', 'fabric', 'file/a.zip', 'file/A.zip', 'file/b'] + + +def cases(count): + rng = random.Random(0x5041434B) + out = [] + for _ in range(count): + ids = rng.sample(IDS, rng.randint(1, 9)) + packs = [{'id': i, 'required': rng.random() < 0.2, 'position': rng.choice(['top', 'top', 'bottom']), + 'fixed': rng.random() < 0.2, 'compat': rng.choice(['compatible'] * 4 + ['old', 'new'])} for i in ids] + selected = rng.sample(ids + ['file/missing'], rng.randint(0, len(ids))) + ops = [{'list': rng.choice(['selected', 'unselected']), 'index': rng.randint(-2, 8), + 'op': rng.choice(['activate', 'activate', 'up', 'down']), 'confirm': rng.random() < 0.5} + for _ in range(rng.randint(0, 16))] + out.append({'packs': packs, 'selected': selected, 'ops': ops}) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--count', type=int, default=4000) + parser.add_argument('--detail', type=int, default=3) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-pack-selection-parity'; build.mkdir(parents=True, exist_ok=True) + chosen = cases(args.count) + inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + classes = build / 'classes'; classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, + *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaPackSelectionOracle'))], 'compile-java') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackSelectionOracle', + inputs, build / 'vanilla.jsonl'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'pack_selection_fixture', '--', + inputs, build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust) == len(chosen) + errors = [v['error'] for v in vanilla if 'error' in v] + bad = [(c, v, r) for c, v, r in zip(chosen, vanilla, rust) if 'error' not in v and v != r] + for e in sorted(set(errors))[:5]: + print('ORACLE ERROR', e) + for c, v, r in bad[:args.detail]: + print('MISMATCH', json.dumps(c)) + step = next((i for i, (a, b) in enumerate(zip(v['steps'], r['steps'])) if a != b), None) + if step is None: + print(f' committed: vanilla {v["committed"]} | horizon {r["committed"]}') + else: + print(f' after action {step}: vanilla {v["steps"][step]}\n horizon {r["steps"][step]}') + steps = sum(len(v.get('steps', [])) for v in vanilla) + print(f'{len(chosen) - len(bad) - len(errors)}/{len(chosen)} pack selections match ({steps} states); {len(errors)} oracle errors') + if bad or errors: + sys.exit(1) + print('pack selection parity ok') + + +if __name__ == '__main__': + main()