From fd23a8d6820eadcb78310bd5388d8bb83b1fcabe Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:23:16 +0200 Subject: [PATCH] Match vanilla atan2 tables, rotation constants, despawn checks and target search Mth.atan2 builds its tables with StrictMath.asin (fdlibm, ported) and HotSpot's cos; the controls multiply by the folded RAD_TO_DEG float constant. Mob.checkDespawn runs before the tick and, in 26.3, persistent mobs only reset their idle time near a player. NearestAttackableTargetGoal always requires a line of sight and ignores mustReach when searching. MeleeAttackGoal starts its canUse clock at game time 0. The harness now records every random draw of the vanilla mobs with its caller, the random state per tick, and starts each scenario at game time 1000. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 7 +- crates/horizon-client/src/mobs/ai.rs | 53 ++++++------ crates/horizon-client/src/mobs/goals.rs | 46 ++-------- crates/horizon-core/src/geometry/trig.rs | 83 +++++++++++++++++-- crates/horizon-core/src/random.rs | 5 ++ .../horizonlab/parity/VanillaMobAiOracle.java | 41 +++++++++ tools/test_mob_ai_parity.py | 30 ++++++- 7 files changed, 190 insertions(+), 75 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 952723b9e..2406314d6 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -308,7 +308,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { d(lk.wanted[1]), d(lk.wanted[2]) ); - let _ = writeln!( + let _ = write!( out, "\tin {},{},{},{}", f(m.ai.xxa), @@ -316,6 +316,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { f(m.ai.speed), u8::from(m.ai.jumping) ); + let _ = writeln!(out, "\trng {:x}", m.random.state()); } fn main() -> horizon_client::Result<()> { @@ -404,6 +405,7 @@ fn main() -> horizon_client::Result<()> { world.chunks.insert(k, Arc::new(c)); } world.day_time = s.time; + world.game_time = 1000; let mut mobs: Vec = Vec::new(); for (i, spec) in s.mobs.iter().enumerate() { let kind = types @@ -457,6 +459,9 @@ fn main() -> horizon_client::Result<()> { } }); let mut scratch = LegacyRandom::new(0); + for (i, m) in mobs.iter().enumerate() { + print(&mut out, 0, i, m); + } for t in 1..=s.ticks { world.game_time += 1; let snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 027a55125..be23ad75b 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -268,6 +268,11 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { if m.removed { return false; } + // ServerLevel.tick checks despawning before ticking the entity. + if !check_despawn(m, w) { + m.removed = true; + return false; + } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; @@ -304,13 +309,6 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { m.update_walk_animation(); m.anim.end_tick(m.ai.swinging); tick_swing(m); - if !m.alive() { - return true; - } - if !check_despawn(m, w) { - m.removed = true; - return false; - } m.position.y > -128.0 } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -683,42 +681,39 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { _ => {} } } -/// Mob.checkDespawn (players are the only despawn reference). +/// Mob.checkDespawn, before the tick (players are the only despawn +/// reference). Returns false when the mob is discarded. fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { - let creature = m.kind.category == "creature"; - // Warden.removeWhenFarAway is false; a jockey's chicken despawns like a monster. - if m.persistent - || m.species() == Species::Warden - || creature && m.kind.flags.animal && !m.extra.jockey - { - m.ai.no_action_time = 0; - return true; - } let Some(p) = &w.player else { return true }; let d = m.distance_sqr(p.position); - // Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`). - if super::raider::keeps_alive(m, d) - || super::zombie_villager::keeps_alive(m) - || super::riders::keeps_alive(m) - // requiresCustomPersistence: a tame nautilus, a sulfur cube holding a - // block or let out of a bucket. + // requiresCustomPersistence: raiders in a raid, a tame nautilus, a sulfur + // cube holding a block or let out of a bucket. + let persistent = m.persistent || super::nautilus::is_nautilus(m.species()) && m.extra.tame || m.species() == Species::SulfurCube - && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0) - { - return true; - } + && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); + // removeWhenFarAway: animals, wardens, patrols and raiders, zombie + // villagers being cured and ridden mobs stay. + let creature = m.kind.category == "creature"; + let removable = !(m.species() == Species::Warden + || creature && m.kind.flags.animal && !m.extra.jockey + || super::raider::keeps_alive(m, d) + || super::zombie_villager::keeps_alive(m) + || super::riders::keeps_alive(m)); + // MobCategory.getDespawnDistance / getNoDespawnDistance let despawn = if m.kind.category == "water_ambient" { 64.0 } else { 128.0 }; - if d > despawn * despawn { + if !persistent && d > despawn * despawn && removable { return false; } - if m.ai.no_action_time > 600 + if !persistent + && m.ai.no_action_time > 600 && m.random.next_int_bound(800).unwrap_or(1) == 0 && d > 32.0 * 32.0 + && removable { return false; } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index def62484b..059e58462 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -745,7 +745,7 @@ impl MeleeAttack { path_target: [0.0; 3], recalc: 0, until_attack: 0, - last_check: i64::MIN / 2, + last_check: 0, raise_arm: 0, interval: 20, } @@ -928,8 +928,6 @@ pub struct NearestTarget { pub struct TargetState { unseen: i32, pub unseen_memory: i32, - reach_cache: i32, - reach_time: i32, /// `TargetGoal.getFollowDistance` as a fraction of the follow range. pub follow_scale: f64, } @@ -938,8 +936,6 @@ impl Default for TargetState { Self { unseen: 0, unseen_memory: 0, - reach_cache: 0, - reach_time: 0, follow_scale: 1.0, } } @@ -1008,23 +1004,6 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m } true } -/// TargetGoal.canAttack's reach check. -fn can_reach(st: &mut TargetState, m: &mut Mob, cx: &mut Cx, at: Vec3) -> bool { - st.reach_time -= 1; - if st.reach_time <= 0 { - st.reach_cache = 0; - } - if st.reach_cache == 0 { - st.reach_time = reduced(10 + m.random.next_int_bound(5).unwrap_or(0)); - let path = m.create_path_to_entity(cx.w, [at.x, at.y, at.z], 0); - let ok = path.and_then(|p| p.end()).is_some_and(|e| { - let (xx, zz) = (e.x - at.x.floor() as i32, e.z - at.z.floor() as i32); - f64::from(xx * xx + zz * zz) <= 2.25 - }); - st.reach_cache = if ok { 1 } else { 2 }; - } - st.reach_cache == 1 -} impl Goal for NearestTarget { goal_clone!(); fn flags(&self) -> u8 { @@ -1041,21 +1020,17 @@ impl Goal for NearestTarget { } let range = m.attrs.follow_range * self.target_goal.follow_scale; self.found = None; + // NearestAttackableTargetGoal.findTarget: TargetingConditions.forCombat() + // always checks the line of sight; mustSee and mustReach only matter + // to TargetGoal.canContinueToUse and canAttack. match &self.prey { Prey::Player => { - if m.can_target_player(cx.w, range, self.must_see) { - let at = - cx.w.player - .as_ref() - .map(|p| p.position) - .unwrap_or(Vec3::ZERO); - if !self.must_reach || can_reach(&mut self.target_goal, m, cx, at) { - self.found = Some(Who::Player); - } + if m.can_target_player(cx.w, range, true) { + self.found = Some(Who::Player); } } prey => { - let pos = m.position; + let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z); let id = m.id; let candidates: Vec<(u32, Vec3)> = cx.w.nearby(pos, range, move |s| { @@ -1072,10 +1047,7 @@ impl Goal for NearestTarget { if m.distance_sqr(cpos) > range * range { continue; } - if self.must_see && !m.sees(cx.w, Who::Mob(cid)) { - continue; - } - if self.must_reach && !can_reach(&mut self.target_goal, m, cx, cpos) { + if !m.sees(cx.w, Who::Mob(cid)) { continue; } self.found = Some(Who::Mob(cid)); @@ -1090,8 +1062,6 @@ impl Goal for NearestTarget { } fn start(&mut self, m: &mut Mob, _: &mut Cx) { m.ai.target = self.found; - self.target_goal.reach_cache = 0; - self.target_goal.reach_time = 0; self.target_goal.unseen = 0; } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index 8a8aba77e..36c0b069d 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -29,8 +29,15 @@ pub fn atan2(mut y: f64, mut x: f64) -> f64 { let (asin, cos) = TABLES.get_or_init(|| { (0..257) .map(|i| { - let a = (f64::from(i) / 256.0).asin(); - (a, a.cos()) + let a = fdlibm_asin(f64::from(i) / 256.0); + // HotSpot's x86-64 Math.cos intrinsic rounds entry 61 one ulp + // above the correctly rounded value the platform cos gives. + let c = if i == 61 { + f64::from_bits(0x3fef_140a_0a08_6af1) + } else { + a.cos() + }; + (a, c) }) .unzip() }); @@ -73,10 +80,11 @@ pub fn atan2(mut y: f64, mut x: f64) -> f64 { } theta } -/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)`: the angle in degrees -/// as the AI controls compute it. +/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)` as the AI controls +/// compute it: the compiled code multiplies by the folded float constant +/// `Mth.RAD_TO_DEG` widened to double. pub fn atan2_degrees(y: f64, x: f64) -> f32 { - (atan2(y, x) * 180.0 / f64::from(std::f32::consts::PI)) as f32 + (atan2(y, x) * f64::from(RAD_TO_DEG)) as f32 } /// `Mth.sin` / `Mth.cos` on a float, as the models call them. @@ -93,9 +101,74 @@ impl Mth for f32 { } } +/// fdlibm `__ieee754_asin`, as `StrictMath.asin` (and so `Math.asin`) computes it. +pub fn fdlibm_asin(x: f64) -> f64 { + const PIO2_HI: f64 = 1.570_796_326_794_896_558_00e+00; + const PIO2_LO: f64 = 6.123_233_995_736_766_035_87e-17; + const PIO4_HI: f64 = 7.853_981_633_974_482_789_99e-01; + const PS0: f64 = 1.666_666_666_666_666_574_15e-01; + const PS1: f64 = -3.255_658_186_224_009_154_05e-01; + const PS2: f64 = 2.012_125_321_348_629_258_81e-01; + const PS3: f64 = -4.005_553_450_067_941_140_27e-02; + const PS4: f64 = 7.915_349_942_898_145_321_76e-04; + const PS5: f64 = 3.479_331_075_960_211_675_70e-05; + const QS1: f64 = -2.403_394_911_734_414_218_78e+00; + const QS2: f64 = 2.020_945_760_233_505_694_71e+00; + const QS3: f64 = -6.882_839_716_054_532_930_30e-01; + const QS4: f64 = 7.703_815_055_590_193_527_91e-02; + let bits = x.to_bits(); + let hx = (bits >> 32) as i32; + let ix = hx & 0x7fff_ffff; + if ix >= 0x3ff0_0000 { + if ((ix - 0x3ff0_0000) as u32 | bits as u32) == 0 { + return x * PIO2_HI + x * PIO2_LO; + } + return (x - x) / (x - x); + } else if ix < 0x3fe0_0000 { + if ix < 0x3e40_0000 && 1.0e300 + x > 1.0 { + return x; + } + let t = x * x; + let p = t * (PS0 + t * (PS1 + t * (PS2 + t * (PS3 + t * (PS4 + t * PS5))))); + let q = 1.0 + t * (QS1 + t * (QS2 + t * (QS3 + t * QS4))); + let w = p / q; + return x + x * w; + } + let w = 1.0 - x.abs(); + let t = w * 0.5; + let p = t * (PS0 + t * (PS1 + t * (PS2 + t * (PS3 + t * (PS4 + t * PS5))))); + let q = 1.0 + t * (QS1 + t * (QS2 + t * (QS3 + t * QS4))); + let s = t.sqrt(); + let t = if ix >= 0x3fef_3333 { + let w = p / q; + PIO2_HI - (2.0 * (s + s * w) - PIO2_LO) + } else { + let w = f64::from_bits(s.to_bits() & 0xffff_ffff_0000_0000); + let c = (t - w * w) / (s + w); + let r = p / q; + let p = 2.0 * s * r - (PIO2_LO - 2.0 * c); + let q = PIO4_HI - 2.0 * w; + PIO4_HI - (p - q) + }; + if hx > 0 { t } else { -t } +} + #[cfg(test)] mod tests { use super::*; + /// Values the 26.3 client computes on x86-64 HotSpot. + #[test] + fn atan2_matches_the_client_tables() { + for (y, x, r) in [ + (0x402f_3b4b_8041_4df1_u64, 0xc018_53ca_369b_9e91_u64, 0x3fff_1334_9f9d_e798_u64), + (0xc025_d316_35f2_9de8, 0xc018_fb4a_7ec4_3ba8, 0xc000_b996_6547_a498), + (0xc026_5d9c_2b5a_472d, 0xc030_954d_c2dc_3d10, 0xc004_62e7_82d4_c97e), + ] { + assert_eq!(atan2(f64::from_bits(y), f64::from_bits(x)).to_bits(), r); + } + assert_eq!(fdlibm_asin(60.0 / 256.0).to_bits(), 0x3fce_481c_0fce_7134); + assert_eq!(fdlibm_asin(61.0 / 256.0).to_bits(), 0x3fce_cbd7_5b6c_d8f0); + } #[test] fn long_narrowing_and_quadrants() { assert_eq!(sin(0.0).to_bits(), 0.0f32.to_bits()); diff --git a/crates/horizon-core/src/random.rs b/crates/horizon-core/src/random.rs index 46397b5c4..9b2b570e4 100644 --- a/crates/horizon-core/src/random.rs +++ b/crates/horizon-core/src/random.rs @@ -78,6 +78,11 @@ impl LegacyRandom { } } + /// The 48-bit generator state (differential tests compare it). + pub fn state(&self) -> u64 { + self.state + } + fn bits(&mut self, count: u32) -> i32 { self.state = self.state.wrapping_mul(Self::MULTIPLIER).wrapping_add(11) & Self::MASK; (self.state >> (48 - count)) as i32 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 4fd1af517..ca1b2f299 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -107,6 +107,32 @@ public final class VanillaMobAiOracle { static PrintWriter out; static final List SOUNDS = new ArrayList<>(); + /** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */ + static final class TracingRandom extends net.minecraft.world.level.levelgen.LegacyRandomSource { + static int tick; + static boolean on; + final List log; + final int who; + TracingRandom(long seed, List log, int who) { super(seed); this.log = log; this.who = who; } + @Override + public int next(int bits) { + int v = super.next(bits); + if (on) { + StringBuilder sb = new StringBuilder(tick + " trace " + who + " " + bits + "=" + Integer.toHexString(v) + ":"); + int n = 0; + for (StackTraceElement e : new Throwable().getStackTrace()) { + String c = e.getClassName(); + if (c.contains("RandomSource") || c.contains("TracingRandom") || c.contains("Mth")) continue; + sb.append(' ').append(c.substring(c.lastIndexOf('.') + 1)).append('.').append(e.getMethodName()).append(':').append(e.getLineNumber()); + if (++n == 7) break; + } + log.add(sb.toString()); + } + return v; + } + } + static final List TRACE = new ArrayList<>(); + static final class MobSpec { String type; double x, y, z; @@ -188,6 +214,12 @@ public final class VanillaMobAiOracle { MinecraftServer.spin(thread -> Server.create(thread, access, packs)); } + static String traceSpec() { String v = System.getenv("AI_TRACE"); return v == null ? "" : v; } + // Every mob random is traced unless AI_TRACE=0. + static boolean tracing(Scenario s) { return !traceSpec().equals("0"); } + static int traceFrom() { return 0; } + static int traceTo() { return Integer.MAX_VALUE; } + static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); } @@ -376,6 +408,8 @@ public final class VanillaMobAiOracle { out.println("== " + s.name); var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD); this.clockManager().setTotalTicks(clock, s.time); + // Every scenario starts at game time 1000. + this.getWorldData().overworldData().setGameTime(1000L); // isRaining/isThundering read the rain and thunder levels only. level.setRainLevel(s.rain ? 1.0F : 0.0F); level.setThunderLevel(s.thunder ? 1.0F : 0.0F); @@ -398,6 +432,7 @@ public final class VanillaMobAiOracle { for (MobSpec spec : s.mobs) { EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type)); Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND); + if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, mobs.size())); mob.setId(id++); mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F); mob.setYHeadRot(spec.yaw); @@ -424,6 +459,7 @@ public final class VanillaMobAiOracle { Method tickTime = method(ServerLevel.class, "tickTime"); Object manager = get(level, "entityManager"); Method managerTick = method(manager.getClass(), "tick"); + for (int i = 0; i < mobs.size(); i++) print(0, i, mobs.get(i)); for (int t = 1; t <= s.ticks; t++) { level.environmentAttributes().invalidateTickCache(); level.updateSkyBrightness(); @@ -435,6 +471,8 @@ public final class VanillaMobAiOracle { player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); player.setDeltaMovement(Vec3.ZERO); } + TracingRandom.tick = t; + TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo(); SOUNDS.clear(); for (Mob mob : mobs) { if (mob.isRemoved()) continue; @@ -445,6 +483,8 @@ public final class VanillaMobAiOracle { managerTick.invoke(manager); for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i)); for (String sound : SOUNDS) out.println(t + " sound " + sound); + for (String line : TRACE) out.println(line); + TRACE.clear(); } for (Mob mob : mobs) mob.discard(); managerTick.invoke(manager); @@ -518,6 +558,7 @@ public final class VanillaMobAiOracle { .append(d((double) get(lc, "wantedY"))).append(',').append(d((double) get(lc, "wantedZ"))); sb.append("\tin ").append(f(m.xxa)).append(',').append(f(m.zza)).append(',').append(f(m.getSpeed())).append(',') .append(field(LivingEntity.class, "jumping").getBoolean(m) ? 1 : 0); + sb.append("\trng ").append(Long.toHexString(((java.util.concurrent.atomic.AtomicLong) field(net.minecraft.world.level.levelgen.LegacyRandomSource.class, "seed").get(m.getRandom())).get())); Brain brain = m.getBrain(); if (!brain.getActiveActivities().isEmpty() && !((Map) get(brain, "sensors")).isEmpty()) { List acts = new ArrayList<>(); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 33e11edb4..b6b75ec3a 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -116,6 +116,9 @@ def parse(path): if parts[1] == 'sound': cur['sounds'].setdefault(t, []).append(parts[2]) continue + if parts[1] == 'trace': + cur.setdefault('trace', {}).setdefault(t, []).append(parts[2]) + continue mob = int(parts[1]) row = {} if len(parts) > 2: @@ -142,6 +145,22 @@ def decode(value): return ' '.join(out) +MULT, MASK = 0x5DEECE66D, (1 << 48) - 1 + + +def draws(before, after, limit=20000): + """How many LegacyRandomSource steps lead from one state to the next.""" + try: + s, goal = int(before, 16), int(after, 16) + except (TypeError, ValueError): + return '?' + for n in range(limit): + if s == goal: + return n + s = (s * MULT + 11) & MASK + return f'>{limit}' + + def compare(vanilla, rust, fields=None): """Returns (report lines, totals).""" report, totals = [], {'mob_ticks': 0, 'matched': 0, 'scenarios': 0, 'clean': 0} @@ -169,11 +188,18 @@ def compare(vanilla, rust, fields=None): diffs = [] for k in (a or {}): if b is None or a.get(k) != b.get(k): - diffs.append(f'{k}: vanilla {decode(a.get(k, "?"))} | horizon {decode((b or {}).get(k, "?"))}') + show = (lambda x: x) if k == 'rng' else decode + diffs.append(f'{k}: vanilla {show(a.get(k, "?"))} | horizon {show((b or {}).get(k, "?"))}') for k in (b or {}): if a is None or k not in a: diffs.append(f'{k}: vanilla ? | horizon {decode(b[k])}') - report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)}') + prev_v = v['ticks'].get(t - 1, {}).get(mob, {}).get('rng') + prev_r = r['ticks'].get(t - 1, {}).get(mob, {}).get('rng') + report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)} ' + f'(random draws this tick: vanilla {draws(prev_v, (a or {}).get("rng"))}, ' + f'horizon {draws(prev_r, (b or {}).get("rng"))})') + for line in [x for x in v.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]: + report.append(' vanilla ' + line) report.extend(' ' + d for d in diffs[:12]) if first is not None: clean = False