From edd598cc68a68d66a850f91f82e465b422a4d0a3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:46:50 +0200 Subject: [PATCH 01/14] WIP: unfinished warden-sculk parity work, stopped by Ludovic Uncommitted changes the agent had in progress when it was stopped on 2026-10-12; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 14 +- crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/ai.rs | 9 +- .../horizon-client/src/mobs/villager_brain.rs | 16 +- crates/horizon-client/src/mobs/warden.rs | 1135 +++----------- .../horizon-client/src/mobs/warden_brain.rs | 1343 +++++++++++++++++ .../horizonlab/parity/VanillaMobAiOracle.java | 11 + tools/test_mob_ai_parity.py | 10 + 8 files changed, 1600 insertions(+), 939 deletions(-) create mode 100644 crates/horizon-client/src/mobs/warden_brain.rs diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 4c5178fae..4534a9ee1 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -355,7 +355,9 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { u8::from(m.ai.jumping) ); let _ = write!(out, "\trng {:x}", m.random.state()); - if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) { + if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) + .or_else(|| horizon_client::mobs::warden_brain::describe(m)) + { let _ = write!(out, "\tact {acts}\tmem {mem}"); } out.push('\n'); @@ -467,6 +469,12 @@ fn main() -> horizon_client::Result<()> { match flag.as_str() { "persistent" => m.persistent = true, "noai" => m.no_ai = true, + // Warden.finalizeSpawn's own part. + "digcooldown" | "emerge" => horizon_client::mobs::warden::finalize( + &mut m, + flag == "emerge", + &mut Vec::new(), + ), other => panic!("unknown mob flag {other}"), } } @@ -481,6 +489,10 @@ fn main() -> horizon_client::Result<()> { spec.seed, ); } + if m.species() == Species::Warden { + // As for villagers: the sensors delayed again, the RunOne seeded. + horizon_client::mobs::warden::init_brain(&mut m, spec.seed); + } mobs.push(m); } let player = s.player.map(|p| { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5200e465b..7e08b07d8 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -58,6 +58,7 @@ pub mod vex; pub mod villager; pub mod villager_brain; pub mod warden; +pub mod warden_brain; pub mod witch; pub mod wither; mod world; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a5a4faaec..c87404dab 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -682,6 +682,10 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let _ = m.random.next_int_bound(4); } for (who, at) in targets { + // Warden.doPush: touching it angers it, then the push itself. + if m.species() == Species::Warden { + super::warden::do_push(m, w, who, events); + } // Entity.push(Entity) with `this` the other entity. let (mut xa, mut za) = (m.position.x - at.x, m.position.z - at.z); let mut dd = xa.abs().max(za.abs()); @@ -758,6 +762,10 @@ fn server_ai_step( super::villager_brain::tick(m, w, level_random, events); let _ = m.random.next_int_bound(100); } + if m.species() == Species::Warden { + // Warden.customServerAiStep: the brain and its bookkeeping. + super::warden::server_ai_step(m, w, level_random, events); + } { let mut cx = Cx { w, events }; custom_server_ai_step(m, &mut cx); @@ -782,7 +790,6 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Enderman => super::enderman::custom_server_ai_step(m, cx), Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), - Species::Warden => super::warden::server_ai_step(m, cx), Species::Wither if m.alive() => super::wither::custom_server_ai_step(m, cx.w, cx.events), // SpellcasterIllager.customServerAiStep. Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index beb877bb1..f778ece27 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -36,7 +36,8 @@ impl Default for Slot { } } impl Slot { - fn tick(&mut self) { + /// `MemorySlot.tick` (`Brain.forgetOutdatedMemories`). + pub(super) fn tick(&mut self) { if self.v.is_some() && self.ttl != NEVER { if self.ttl <= 0 { self.clear(); @@ -66,9 +67,16 @@ impl Slot { pub fn get(&self) -> Option<&T> { self.v.as_ref() } + pub(super) fn get_mut(&mut self) -> Option<&mut T> { + self.v.as_mut() + } pub fn present(&self) -> bool { self.v.is_some() } + /// The time to live (`i64::MAX`: never expires). + pub fn ttl(&self) -> i64 { + self.ttl + } } impl Slot { pub fn value(&self) -> Option { @@ -77,7 +85,7 @@ impl Slot { } impl Slot> { /// `Brain.setMemory` of a collection: an empty one erases the memory. - fn set_list(&mut self, v: Vec) { + pub(super) fn set_list(&mut self, v: Vec) { if v.is_empty() { self.clear(); } else { @@ -162,8 +170,8 @@ impl WalkTarget { /// cache of `Sensor.isEntityTargetable`. #[derive(Clone, Debug, Default)] pub struct Visible { - list: Vec, - cache: Vec<(Who, bool)>, + pub(super) list: Vec, + pub(super) cache: Vec<(Who, bool)>, } /// The memories a villager's brain registers. diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 11394a011..44ef96dd0 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -1,34 +1,23 @@ -//! The warden (`Warden`, `WardenAi`, `AngerManagement`): a brain with the -//! emerge, dig, roar, fight, investigate, sniff and idle activities, anger -//! kept per entity, vibration listening, the sonic boom, the heartbeat and -//! tendril animations, and digging back into the ground when nothing has -//! disturbed it for a minute. +//! The warden (`Warden`, `AngerManagement`): anger kept per entity, +//! vibration listening, the sonic boom and melee attack, the heartbeat and +//! tendril animations, the model and its emissive layers. Its brain +//! (`WardenAi`) is in `warden_brain`. use super::{ Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, - goals::{Cx, Float}, keyframes::Animation, - path::{Path, PathType}, + path::PathType, + warden_brain::{self, Brain}, }; use crate::sculk::{self, Context, Info}; use horizon_core::{ geometry::{Vec3, trig::Mth}, - random::RandomSource, + random::{LegacyRandom, RandomSource}, }; use std::{collections::HashMap, f32::consts::PI}; -pub const EMERGE_DURATION: i64 = 134; -pub const ROAR_DURATION: i64 = 84; -const ROAR_SOUND_DELAY: i64 = 25; -const SNIFFING_DURATION: i64 = 84; -const DIGGING_DURATION: i64 = 100; -pub const DIGGING_COOLDOWN: i64 = 1200; -const MELEE_ATTACK_COOLDOWN: i64 = 18; -const SONIC_DURATION: i64 = 60; -const SONIC_SOUND_DELAY: i64 = 34; -const SPEED_IDLING: f64 = 0.5; -const SPEED_INVESTIGATING: f64 = 0.7; -const SPEED_FIGHTING: f64 = 1.2; +pub const EMERGE_DURATION: i64 = warden_brain::EMERGE_DURATION as i64; +pub const DIGGING_COOLDOWN: i64 = warden_brain::DIGGING_COOLDOWN; const DEFAULT_ANGER: i32 = 35; const PROJECTILE_ANGER: i32 = 10; const ON_HURT_ANGER_BOOST: i32 = 20; @@ -87,7 +76,7 @@ pub fn digging_or_emerging(m: &Mob) -> bool { matches!(pose(m), Pose::Digging | Pose::Emerging) } /// `Entity.setPose`, with `onSyncedDataUpdated` starting the keyframes. -fn set_pose(m: &mut Mob, new: Pose) { +pub(super) fn set_pose(m: &mut Mob, new: Pose) { if pose(m) == new { return; } @@ -236,142 +225,20 @@ impl AngerManagement { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Activity { - Emerge, - Dig, - Roar, - Fight, - Investigate, - Sniff, - Idle, -} -#[derive(Clone, Copy, Debug, PartialEq)] -enum Track { - Block([i32; 3]), - /// An entity, tracked at its eyes when the flag is set. - Entity(Who, bool), -} -#[derive(Clone, Copy, Debug, PartialEq)] -struct Walk { - target: Track, - speed: f32, - close_enough: i32, -} -/// `MoveToTargetSink`'s running state. +/// The warden's state: anger, its vibration listener and its brain. #[derive(Clone, Debug, Default)] -struct MoveSink { - end: i64, - last_target: [i32; 3], - speed: f32, - path: Option, -} -/// `RunOne` over the idle stroll and `DoNothing`. -#[derive(Clone, Copy, Debug, Default)] -struct Pause { - end: i64, -} - -/// The warden's brain and sensors. -#[derive(Clone, Debug)] pub struct Warden { pub anger: AngerManagement, pub vibration: sculk::Data, - activity: Activity, - in_brain: bool, - // Memories: the game time they stop being present (None: absent). - dig_cooldown: Option, - is_emerging: Option, - sniffing: bool, - sniff_cooldown: Option, - roar_target: Option, - attack_target: Option, - disturbance: Option<([i32; 3], i64)>, - look: Option<(Track, i64)>, - walk: Option, - cant_reach_since: Option, - vibration_cooldown: Option, - touch_cooldown: Option, - recent_projectile: Option, - roar_sound_delay: Option, - roar_sound_cooldown: Option, - sonic_cooldown: Option, - sonic_sound_delay: Option, - sonic_sound_cooldown: Option, - attack_cooling_down: Option, - nearest_living: Vec, - nearest_attackable: Option, - sensor_timer: i32, - // Running behaviours (the game time they time out). - emerging: Option, - digging: Option, - roaring: Option, - sniffing_run: Option, - sonic: Option, - look_sink: Option, - move_sink: Option, - move_cooldown: i32, - pause: Option, + pub brain: Brain, /// `getClientAngerLevel`, synchronised once a second. pub client_anger: i32, - /// Attackers noted by `hurtServer` and not yet handled by the brain. + /// Attackers noted by `hurtServer` and not yet reacted to. hurt_by: Vec<(Option, bool)>, } -const NEVER: i64 = i64::MAX; -impl Default for Warden { - fn default() -> Self { - Self { - anger: AngerManagement::default(), - vibration: sculk::Data::default(), - activity: Activity::Idle, - in_brain: false, - dig_cooldown: None, - is_emerging: None, - sniffing: false, - sniff_cooldown: None, - roar_target: None, - attack_target: None, - disturbance: None, - look: None, - walk: None, - cant_reach_since: None, - vibration_cooldown: None, - touch_cooldown: None, - recent_projectile: None, - roar_sound_delay: None, - roar_sound_cooldown: None, - sonic_cooldown: None, - sonic_sound_delay: None, - sonic_sound_cooldown: None, - attack_cooling_down: None, - nearest_living: Vec::new(), - nearest_attackable: None, - sensor_timer: 0, - emerging: None, - digging: None, - roaring: None, - sniffing_run: None, - sonic: None, - look_sink: None, - move_sink: None, - move_cooldown: 0, - pause: None, - client_anger: 0, - hurt_by: Vec::new(), - } - } -} -fn present(memory: Option, now: i64) -> bool { - memory.is_some_and(|until| now < until) -} impl Warden { - /// `Brain.setMemoryWithExpiry`: present for `ttl` brain ticks; set - /// outside the brain's tick it loses the one it ticks at once. - fn expiry(&self, now: i64, ttl: i64) -> Option { - Some(now + ttl - i64::from(!self.in_brain)) - } pub fn target(&self) -> Option { - self.attack_target + self.brain.mem.attack_target.value() } } @@ -384,38 +251,40 @@ pub fn register(m: &mut Mob) { m.set_malus(PathType::Lava, 8.0); m.set_malus(PathType::Fire, 0.0); m.set_malus(PathType::FireInNeighbor, 0.0); - // Swim(0.8) is part of the brain's core activity. - m.ai.goals.add(0, Float); - // The sensors scan on a random phase. - let phase = m.random.next_int_bound(20).unwrap_or(0); - if let Some(w) = m.extra.warden.as_mut() { - w.sensor_timer = phase; + // Brain.Provider.makeBrain: the sensors start on a random phase. + delay_sensors(m); +} +/// `Sensor.randomlyDelayStart` for the warden's two sensors, from its random. +pub fn delay_sensors(m: &mut Mob) { + if let Some(mut st) = m.extra.warden.take() { + st.brain.delay_sensors(&mut m.random); + m.extra.warden = Some(st); } } -/// `Sensor.randomlyDelayStart` for the warden's sensors, in brain order -/// (`NEAREST_PLAYERS`, then `WARDEN_ENTITY_SENSOR`, which sets the phase of -/// the combined scan here). -pub fn delay_sensors(m: &mut Mob) { - if m.species() != Species::Warden { - return; - } - let _players = m.random.next_int_bound(20).unwrap_or(0); - let entities = m.random.next_int_bound(20).unwrap_or(0); - if let Some(w) = m.extra.warden.as_mut() { - w.sensor_timer = entities; +/// A brain whose `RunOne` shuffles with `seed` (vanilla seeds it from the +/// clock; harnesses seed both sides alike), its sensors delayed again. +pub fn init_brain(m: &mut Mob, seed: i64) { + if let Some(st) = m.extra.warden.as_mut() { + let mem = std::mem::take(&mut st.brain.mem); + st.brain = Brain::new(seed); + st.brain.mem = mem; } + delay_sensors(m); } /// `Warden.finalizeSpawn`: a minute until it digs back down; a summoned /// warden climbs out of the ground first. pub fn finalize(m: &mut Mob, triggered: bool, events: &mut Vec) { - let now = i64::from(m.age); - let Some(st) = m.extra.warden.as_mut() else { + if m.extra.warden.is_none() { return; - }; - st.dig_cooldown = Some(now + DIGGING_COOLDOWN); + } + warden_brain::mem(m) + .dig_cooldown + .set_ttl((), DIGGING_COOLDOWN); if triggered { - st.is_emerging = Some(now + EMERGE_DURATION); set_pose(m, Pose::Emerging); + warden_brain::mem(m) + .is_emerging + .set_ttl((), EMERGE_DURATION); sound(m, "entity.warden.agitated", 5.0, 1.0, events); } } @@ -431,15 +300,19 @@ fn voice_pitch(m: &mut Mob) -> f32 { } fn closer_than(m: &Mob, p: Vec3, horizontal: f64, vertical: f64) -> bool { let (dx, dy, dz) = (p.x - m.position.x, p.y - m.position.y, p.z - m.position.z); - dx * dx + dz * dz < horizontal * horizontal && dy.abs() < vertical + dx * dx + dz * dz < horizontal * horizontal && dy * dy < vertical * vertical } // ---- entity facts ---- -/// `Warden.canTargetEntity`. +/// `Warden.canTargetEntity`: living, neither creative nor spectator, not a +/// warden, alive. pub fn can_target(w: &MobWorld, who: Who) -> bool { match who { - Who::Player => w.player.as_ref().is_some_and(|p| p.alive && !p.creative), + Who::Player => w + .player + .as_ref() + .is_some_and(|p| p.alive && !p.creative && !p.spectator), Who::Mob(id) => w .seen(id) .is_some_and(|s| s.alive && s.species != Species::Warden), @@ -448,54 +321,12 @@ pub fn can_target(w: &MobWorld, who: Who) -> bool { fn position_of(w: &MobWorld, who: Who) -> Option { w.target_info(who).map(|t| t.position) } -fn track_position(w: &MobWorld, track: Track) -> Option<[f64; 3]> { - match track { - Track::Block(p) => Some([ - f64::from(p[0]) + 0.5, - f64::from(p[1]) + 0.5, - f64::from(p[2]) + 0.5, - ]), - Track::Entity(who, eyes) => w.target_info(who).map(|t| { - [ - t.position.x, - if eyes { t.eye_y } else { t.position.y }, - t.position.z, - ] - }), - } -} -fn track_block(w: &MobWorld, track: Track) -> Option<[i32; 3]> { - match track { - Track::Block(p) => Some(p), - Track::Entity(who, _) => w.target_info(who).map(|t| { - [ - t.position.x.floor() as i32, - t.position.y.floor() as i32, - t.position.z.floor() as i32, - ] - }), - } -} -fn block_pos(m: &Mob) -> [i32; 3] { - [ - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, - ] -} -fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { - (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() -} -fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> f64 { - (0..3).map(|i| f64::from(a[i] - b[i]).powi(2)).sum() -} // ---- anger ---- /// `Warden.increaseAngerAt`. -fn increase_anger( +pub(super) fn increase_anger( m: &mut Mob, - st: &mut Warden, w: &MobWorld, who: Option, amount: i32, @@ -503,62 +334,39 @@ fn increase_anger( events: &mut Vec, ) { let Some(who) = who else { return }; - if !can_target(w, who) { + if m.no_ai || !can_target(w, who) { return; } - set_dig_cooldown(st, i64::from(m.age)); - let maybe_switch = st.attack_target != Some(Who::Player); + warden_brain::set_dig_cooldown(m); + let Some(st) = m.extra.warden.as_mut() else { + return; + }; + let maybe_switch = st.target() != Some(Who::Player); let new = st.anger.increase(who, amount); if who == Who::Player && maybe_switch && AngerLevel::by_anger(new).is_angry() { - st.attack_target = None; + st.brain.mem.attack_target.clear(); } if play_sound && pose(m) != Pose::Roaring { - let level = angry_level(st); + let level = anger_level(m); let pitch = voice_pitch(m); sound(m, level.listening_sound(), 10.0, pitch, events); } } -fn angry_level(st: &Warden) -> AngerLevel { - AngerLevel::by_anger(st.anger.active_anger(st.attack_target)) -} /// `Warden.getEntityAngryAt`. -fn entity_angry_at(st: &Warden, w: &MobWorld) -> Option { - if angry_level(st).is_angry() { +pub(super) fn entity_angry_at(m: &Mob, w: &MobWorld) -> Option { + let st = m.extra.warden.as_ref()?; + if anger_level(m).is_angry() { st.anger.active_entity(|e| can_target(w, e)) } else { None } } -/// `Warden.getAngerLevel` of a warden (for its ambient sound). +/// `Warden.getAngerLevel`. pub fn anger_level(m: &Mob) -> AngerLevel { m.extra.warden.as_ref().map_or(AngerLevel::Calm, |s| { - AngerLevel::by_anger(s.anger.active_anger(s.attack_target)) + AngerLevel::by_anger(s.anger.active_anger(s.target())) }) } -/// `WardenAi.setDigCooldown`. -fn set_dig_cooldown(st: &mut Warden, now: i64) { - if present(st.dig_cooldown, now) { - st.dig_cooldown = st.expiry(now, DIGGING_COOLDOWN); - } -} -/// `WardenAi.setDisturbanceLocation`. -fn set_disturbance(st: &mut Warden, w: &MobWorld, now: i64, position: [i32; 3]) { - if entity_angry_at(st, w).is_none() && st.attack_target.is_none() { - set_dig_cooldown(st, now); - st.sniff_cooldown = st.expiry(now, 100); - let until = st.expiry(now, 100).unwrap_or(now); - st.look = Some((Track::Block(position), until)); - st.disturbance = Some((position, until)); - st.walk = None; - } -} -/// `Warden.setAttackTarget`. -fn set_attack_target(st: &mut Warden, target: Who, now: i64) { - st.roar_target = None; - st.attack_target = Some(target); - st.cant_reach_since = None; - st.sonic_cooldown = st.expiry(now, 200); -} // ---- damage ---- @@ -566,9 +374,9 @@ fn set_attack_target(st: &mut Warden, target: Who, now: i64) { pub fn accepts_damage(m: &Mob, source: &Damage) -> bool { !(digging_or_emerging(m) && source.kind != DamageKind::Generic) } -/// `Warden.hurtServer`'s reaction, handled by the brain's next tick. +/// `Warden.hurtServer`'s reaction, handled at the warden's next tick. pub fn hurt(m: &mut Mob, source: &Damage) { - if digging_or_emerging(m) { + if m.no_ai || digging_or_emerging(m) { return; } let direct = !matches!( @@ -579,32 +387,79 @@ pub fn hurt(m: &mut Mob, source: &Damage) { st.hurt_by.push((source.attacker, direct)); } } +/// The rest of `Warden.hurtServer`. +fn handle_hurt(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let hurt = m + .extra + .warden + .as_mut() + .map(|st| std::mem::take(&mut st.hurt_by)) + .unwrap_or_default(); + for (attacker, direct) in hurt { + increase_anger( + m, + w, + attacker, + AngerLevel::Angry.minimum() + ON_HURT_ANGER_BOOST, + false, + events, + ); + if !warden_brain::mem(m).attack_target.present() + && let Some(who) = attacker + && let Some(p) = position_of(w, who) + && (direct || m.distance_sqr(p) < 25.0) + { + warden_brain::set_attack_target(m, who); + } + } +} +/// `Warden.doPush`: touching something angers it (once a second). +pub fn do_push(m: &mut Mob, w: &MobWorld, who: Who, events: &mut Vec) { + if m.no_ai || m.extra.warden.is_none() || warden_brain::mem(m).touch_cooldown.present() { + return; + } + warden_brain::mem(m).touch_cooldown.set_ttl((), 20); + increase_anger(m, w, Some(who), DEFAULT_ANGER, true, events); + if let Some(t) = w.target_info(who) { + let block = [ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]; + warden_brain::set_disturbance(m, w, block); + } +} +/// `Warden.doHurtTarget`: the attack keyframes (entity event 4), the impact +/// sound, a sonic boom cooldown, then `Mob.doHurtTarget`. +pub(super) fn do_hurt_target(m: &mut Mob, target: Who, w: &MobWorld, events: &mut Vec) { + m.anim.states[ROAR].stop(); + m.anim.states[ATTACK].start(m.age as f32); + let pitch = voice_pitch(m); + sound(m, "entity.warden.attack_impact", 10.0, pitch, events); + warden_brain::mem(m).sonic_boom_cooldown.set_ttl((), 40); + let mut cx = warden_brain::cx(w, events); + super::ai::do_hurt_target(m, target, &mut cx); +} // ---- vibrations ---- /// `Warden.VibrationUser.canReceiveVibration`. -pub fn can_receive_vibration(m: &Mob, now: i64, ctx: &Context) -> bool { +pub fn can_receive_vibration(m: &Mob, _now: i64, ctx: &Context) -> bool { let Some(st) = m.extra.warden.as_ref() else { return false; }; - m.alive() - && !present(st.vibration_cooldown, now) + !m.no_ai + && m.alive() + && !st.brain.mem.vibration_cooldown.present() && !digging_or_emerging(m) && !(ctx.living && !ctx.targetable) } /// `Warden.VibrationUser.onReceiveVibration`. -fn receive_vibration( - m: &mut Mob, - st: &mut Warden, - w: &MobWorld, - info: Info, - events: &mut Vec, -) { +fn receive_vibration(m: &mut Mob, w: &MobWorld, info: Info, events: &mut Vec) { if !m.alive() { return; } - let now = i64::from(m.age); - st.vibration_cooldown = st.expiry(now, 40); + warden_brain::mem(m).vibration_cooldown.set_ttl((), 40); // Entity event 61: the tendrils twitch. m.anim.v[TENDRIL] = 10.0; let pitch = voice_pitch(m); @@ -617,9 +472,9 @@ fn receive_vibration( let mut suspicious = origin; if let Some(owner) = info.owner { if let Some(p) = position_of(w, owner) - && closer_than_distance(m, p, 30.0) + && m.distance_sqr(p) < 900.0 { - if present(st.recent_projectile, now) { + if warden_brain::mem(m).recent_projectile.present() { if can_target(w, owner) && let Some(t) = w.target_info(owner) { @@ -629,585 +484,97 @@ fn receive_vibration( t.position.z.floor() as i32, ]; } - increase_anger(m, st, w, Some(owner), DEFAULT_ANGER, true, events); + increase_anger(m, w, Some(owner), DEFAULT_ANGER, true, events); } else { - increase_anger(m, st, w, Some(owner), PROJECTILE_ANGER, true, events); + increase_anger(m, w, Some(owner), PROJECTILE_ANGER, true, events); } } - st.recent_projectile = st.expiry(now, 100); + warden_brain::mem(m).recent_projectile.set_ttl((), 100); } else { - increase_anger(m, st, w, info.source, DEFAULT_ANGER, true, events); + increase_anger(m, w, info.source, DEFAULT_ANGER, true, events); } - if !angry_level(st).is_angry() { - let active = st.anger.active_entity(|e| can_target(w, e)); + if !anger_level(m).is_angry() { + let active = m + .extra + .warden + .as_ref() + .and_then(|st| st.anger.active_entity(|e| can_target(w, e))); if info.owner.is_some() || active.is_none() || active == info.source { - set_disturbance(st, w, now, suspicious); + warden_brain::set_disturbance(m, w, suspicious); } } } -fn closer_than_distance(m: &Mob, p: Vec3, distance: f64) -> bool { - m.distance_sqr(p) < distance * distance -} -// ---- the brain ---- +// ---- the server tick ---- -/// `Warden.customServerAiStep`: the vibration ticker, the brain, darkness, -/// anger and the activity. -pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) { - let Some(mut st) = m.extra.warden.take() else { +/// `Warden.tick` (the vibration ticker, persistence keeping the dig +/// cooldown) and `Warden.customServerAiStep` (the brain, the darkness +/// pulse, anger and the activity). +pub fn server_ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { + if m.extra.warden.is_none() { return; - }; - let now = i64::from(m.age); - // Warden.tick: vibrations arrive before the brain thinks. - st.in_brain = false; - if st.dig_cooldown.is_some() && m.custom_name.is_some() { - set_dig_cooldown(&mut st, now); } - let tick = st - .vibration - .tick(cx.w.game_time, true, false, |d| d.floor() as i32); + let tick = m + .extra + .warden + .as_mut() + .map(|st| st.vibration.tick(w.game_time, true, false, |d| d.floor() as i32)) + .unwrap_or_default(); if let Some((info, travel)) = tick.started { let eye = [m.position.x, m.position.y + m.kind.eye_height, m.position.z]; - cx.events.push(MobEvent::Vibration { + events.push(MobEvent::Vibration { from: info.pos, to: eye, ticks: travel, }); } if let Some(info) = tick.received { - receive_vibration(m, &mut st, cx.w, info, cx.events); + receive_vibration(m, w, info, events); } - touch_entities(m, &mut st, cx); - handle_hurt(m, &mut st, cx); - st.in_brain = true; - brain_tick(m, &mut st, cx); - st.in_brain = false; - // Warden.customServerAiStep after the brain. + if m.persistent || m.custom_name.is_some() { + warden_brain::set_dig_cooldown(m); + } + handle_hurt(m, w, events); + warden_brain::tick(m, w, level_random, events); if (i64::from(m.age) + i64::from(m.id)) % 120 == 0 { - cx.events.push(MobEvent::Darkness { - at: [m.position.x, m.position.y, m.position.z], + events.push(MobEvent::Darkness { + at: at(m), radius: DARKNESS_RADIUS, }); } - if m.age.is_multiple_of(20) { - let w = cx.w; + if m.age.is_multiple_of(20) + && let Some(st) = m.extra.warden.as_mut() + { st.anger.tick(|who| can_target(w, who)); - st.client_anger = st.anger.active_anger(st.attack_target); + st.client_anger = st.anger.active_anger(st.target()); } - update_activity(m, &mut st, now); - m.extra.warden = Some(st); -} -/// `Warden.doPush`: touching something angers it (every second). -fn touch_entities(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - if digging_or_emerging(m) || !m.alive() { - return; - } - let now = i64::from(m.age); - if present(st.touch_cooldown, now) { - return; - } - let bounds = m.bounds(); - let mut touched = None; - if let Some(p) = cx.w.player.as_ref() - && p.alive - && !p.spectator - && bounds.intersects(p.bounds) - { - touched = Some(Who::Player); - } - if touched.is_none() { - touched = - cx.w.others - .iter() - .find(|s| s.id != m.id && s.alive && bounds.intersects(s.bounds)) - .map(|s| Who::Mob(s.id)); - } - if let Some(who) = touched { - st.touch_cooldown = st.expiry(now, 20); - increase_anger(m, st, cx.w, Some(who), DEFAULT_ANGER, true, cx.events); - if let Some(t) = cx.w.target_info(who) { - let block = [ - t.position.x.floor() as i32, - t.position.y.floor() as i32, - t.position.z.floor() as i32, - ]; - set_disturbance(st, cx.w, now, block); - } + if let Some(st) = m.extra.warden.as_mut() { + st.brain.update_activity(); } } -/// The rest of `Warden.hurtServer`. -fn handle_hurt(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - for (attacker, direct) in std::mem::take(&mut st.hurt_by) { - increase_anger( - m, - st, - cx.w, - attacker, - AngerLevel::Angry.minimum() + ON_HURT_ANGER_BOOST, - false, - cx.events, - ); - if st.attack_target.is_none() - && let Some(who) = attacker - && let Some(p) = position_of(cx.w, who) - && (direct || closer_than_distance(m, p, 5.0)) - { - set_attack_target(st, who, i64::from(m.age)); - } - } -} -/// `Brain.setActiveActivityToFirstValid`, erasing the memories of the -/// activity being left. -fn update_activity(m: &mut Mob, st: &mut Warden, now: i64) { - let _ = m; - let next = if present(st.is_emerging, now) { - Activity::Emerge - } else if st.roar_target.is_none() && !present(st.dig_cooldown, now) { - Activity::Dig - } else if st.roar_target.is_some() { - Activity::Roar - } else if st.attack_target.is_some() { - Activity::Fight - } else if st.disturbance.is_some_and(|(_, until)| now < until) { - Activity::Investigate - } else if st.sniffing { - Activity::Sniff - } else { - Activity::Idle - }; - if next != st.activity { - match st.activity { - Activity::Emerge => st.is_emerging = None, - Activity::Roar => st.roar_target = None, - Activity::Fight => st.attack_target = None, - Activity::Investigate => st.disturbance = None, - Activity::Sniff => st.sniffing = false, - Activity::Dig | Activity::Idle => {} - } - st.activity = next; - } -} -fn active(st: &Warden, activity: Activity) -> bool { - st.activity == activity -} -fn brain_tick(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // Memories that timed out are forgotten. - if st.disturbance.is_some_and(|(_, until)| now >= until) { - st.disturbance = None; - } - if st.look.is_some_and(|(_, until)| now >= until) { - st.look = None; - } - sense(m, st, cx.w); - start_behaviours(m, st, cx); - tick_behaviours(m, st, cx); -} -/// `WardenEntitySensor` (and `NearestLivingEntitySensor`) every 20 ticks. -fn sense(m: &mut Mob, st: &mut Warden, w: &MobWorld) { - st.sensor_timer -= 1; - if st.sensor_timer > 0 { - return; - } - st.sensor_timer = 20; - let range = m.attrs.follow_range; - let area = m - .bounds() - .inflate(horizon_core::geometry::Vec3::new(range, range, range)); - let mut found: Vec<(Who, f64)> = Vec::new(); - if let Some(p) = w.player.as_ref() - && p.alive - && area.intersects(p.bounds) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - for s in w.others { - if s.id != m.id && s.alive && area.intersects(s.bounds) { - found.push((Who::Mob(s.id), m.distance_sqr(s.position))); - } - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - st.nearest_living = found.into_iter().map(|(who, _)| who).collect(); - let closest = |players: bool| { - st.nearest_living - .iter() - .copied() - .find(|who| can_target(w, *who) && (*who == Who::Player) == players) - }; - let attackable = closest(true).or_else(|| closest(false)); - st.nearest_attackable = attackable; -} -/// `NearestVisibleLivingEntities.contains`. -fn visible(m: &mut Mob, st: &Warden, w: &MobWorld, who: Who) -> bool { - st.nearest_living.contains(&who) && m.sees(w, who) -} - -fn start_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // Core: SetWardenLookTarget. - if st.attack_target.is_none() { - let target = st - .roar_target - .and_then(|who| track_block(cx.w, Track::Entity(who, true))) - .or(st.disturbance.map(|(p, _)| p)); - if let Some(p) = target { - st.look = Some((Track::Block(p), NEVER)); - } - } - // Dig: Digging. - if active(st, Activity::Dig) - && st.digging.is_none() - && st.attack_target.is_none() - && st.walk.is_none() - && (m.on_ground || m.is_in_liquid()) - { - st.digging = Some(now + DIGGING_DURATION); - if m.on_ground { - set_pose(m, Pose::Digging); - sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); - } else { - sound(m, "entity.warden.agitated", 5.0, 1.0, cx.events); - stop_digging(m, st); - } - } - // Core: LookAtTargetSink. - if st.look_sink.is_none() && st.look.is_some() { - let duration = 45 + i64::from(m.random.next_int_bound(46).unwrap_or(0)); - st.look_sink = Some(now + duration); - } - // Core: MoveToTargetSink. - if st.move_sink.is_none() && st.walk.is_some() { - start_move_sink(m, st, cx); - } - // Emerge: Emerging. - if active(st, Activity::Emerge) - && st.emerging.is_none() - && present(st.is_emerging, now) - && st.walk.is_none() - { - st.emerging = Some(now + EMERGE_DURATION); - set_pose(m, Pose::Emerging); - sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); - } - // SetRoarTarget (investigate, sniff and idle). - if matches!( - st.activity, - Activity::Investigate | Activity::Sniff | Activity::Idle - ) && st.roar_target.is_none() - && st.attack_target.is_none() - && let Some(target) = entity_angry_at(st, cx.w).filter(|t| can_target(cx.w, *t)) - { - st.roar_target = Some(target); - st.cant_reach_since = None; - } - // Investigate: GoToTargetLocation. - if active(st, Activity::Investigate) - && st.attack_target.is_none() - && st.walk.is_none() - && let Some((location, until)) = st.disturbance - && now < until - && dist_sqr(location, block_pos(m)) >= 4.0 - { - let ox = m.random.next_int_bound(3).unwrap_or(1) - 1; - let oz = m.random.next_int_bound(3).unwrap_or(1) - 1; - let target = [location[0] + ox, location[1], location[2] + oz]; - st.look = Some((Track::Block(target), NEVER)); - st.walk = Some(Walk { - target: Track::Block(target), - speed: SPEED_INVESTIGATING as f32, - close_enough: 2, - }); - } - // Sniff: Sniffing. - if active(st, Activity::Sniff) - && st.sniffing_run.is_none() - && st.sniffing - && st.attack_target.is_none() - && st.walk.is_none() - { - st.sniffing_run = Some(now + SNIFFING_DURATION); - sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); - } - // Roar. - if active(st, Activity::Roar) - && st.roaring.is_none() - && let Some(target) = st.roar_target - && st.attack_target.is_none() - { - st.roaring = Some(now + ROAR_DURATION); - st.roar_sound_delay = st.expiry(now, ROAR_SOUND_DELAY); - st.walk = None; - st.look = Some((Track::Entity(target, true), NEVER)); - set_pose(m, Pose::Roaring); - increase_anger(m, st, cx.w, Some(target), 20, false, cx.events); - } - // Fight: the dig cooldown setter. - if active(st, Activity::Fight) { - set_dig_cooldown(st, now); - } - // Idle: TryToSniff. - if active(st, Activity::Idle) - && !present(st.sniff_cooldown, now) - && st.nearest_attackable.is_some() - && st.disturbance.is_none() - { - st.sniffing = true; - let cooldown = 100 + i64::from(m.random.next_int_bound(101).unwrap_or(0)); - st.sniff_cooldown = st.expiry(now, cooldown); - st.walk = None; - set_pose(m, Pose::Sniffing); - } - // Fight: StopAttackingIfTargetInvalid. - if active(st, Activity::Fight) - && let Some(target) = st.attack_target - { - let tired = st.cant_reach_since.is_some_and(|since| now - since > 200); - let valid = can_target(cx.w, target) - && !tired - && cx.w.target_info(target).is_some_and(|t| t.alive) - && angry_level(st).is_angry(); - if !valid { - if !can_target(cx.w, target) { - st.anger.clear(target); - } - set_dig_cooldown(st, now); - st.attack_target = None; - } - } - // Idle: RunOne over the stroll and DoNothing. - if active(st, Activity::Idle) && st.pause.is_none() && !st.sniffing { - run_one(m, st, cx); - } - // Fight: SetEntityLookTarget. - if active(st, Activity::Fight) - && st.look.is_none() - && let Some(target) = st.attack_target - && visible(m, st, cx.w, target) - && position_of(cx.w, target) - .is_some_and(|p| m.distance_sqr(p) <= m.attrs.follow_range * m.attrs.follow_range) - { - st.look = Some((Track::Entity(target, true), NEVER)); - } - // Fight: SetWalkTargetFromAttackTargetIfTargetOutOfReach. - if active(st, Activity::Fight) - && let Some(target) = st.attack_target - { - let in_reach = visible(m, st, cx.w, target) - && cx - .w - .target_info(target) - .is_some_and(|t| m.within_melee_range(&t)); - if in_reach { - st.walk = None; - } else { - st.look = Some((Track::Entity(target, true), NEVER)); - st.walk = Some(Walk { - target: Track::Entity(target, false), - speed: SPEED_FIGHTING as f32, - close_enough: 0, - }); - } - } - // Fight: SonicBoom. - if active(st, Activity::Fight) - && st.sonic.is_none() - && !present(st.sonic_cooldown, now) - && let Some(target) = st.attack_target - && position_of(cx.w, target).is_some_and(|p| closer_than(m, p, 15.0, 20.0)) - { - st.sonic = Some(now + SONIC_DURATION); - st.attack_cooling_down = st.expiry(now, SONIC_DURATION); - st.sonic_sound_delay = st.expiry(now, SONIC_SOUND_DELAY); - m.anim.states[SONIC_BOOM].start(m.age as f32); - sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); - } - // Fight: MeleeAttack. - if active(st, Activity::Fight) - && !present(st.attack_cooling_down, now) - && let Some(target) = st.attack_target - && visible(m, st, cx.w, target) - && let Some(info) = cx.w.target_info(target) - && m.within_melee_range(&info) - { - st.look = Some((Track::Entity(target, true), NEVER)); - m.swing(); - attack(m, target, cx); - st.attack_cooling_down = st.expiry(now, MELEE_ATTACK_COOLDOWN); - // SonicBoom.setCooldown(this, 40) from doHurtTarget. - st.sonic_cooldown = st.expiry(now, 40); - m.anim.states[ROAR].stop(); - m.anim.states[ATTACK].start(m.age as f32); - } -} -/// `Warden.doHurtTarget`: the hit, its impact sound and the knockback. -fn attack(m: &mut Mob, target: Who, cx: &mut Cx) { - let pitch = voice_pitch(m); - sound(m, "entity.warden.attack_impact", 10.0, pitch, cx.events); - super::ai::do_hurt_target(m, target, cx); - // ATTACK_KNOCKBACK 1.5: half of it, along the warden's facing. - let yaw = m.yaw.to_radians(); - cx.events.push(MobEvent::Push { - target, - velocity: [ - -f64::from(yaw.sin()) * 0.75, - 0.0, - f64::from(yaw.cos()) * 0.75, - ], - }); - m.velocity.x *= 0.6; - m.velocity.z *= 0.6; -} -/// `RunOne`: a stroll (weight 2) or a pause (weight 1), picked by shuffling. -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 pause_first = pause_key < stroll_key; - let order = if pause_first { - [false, true] - } else { - [true, false] - }; - for stroll in order { - if stroll { - // RandomStroll.stroll(0.5): only when there is no walk target. - if st.walk.is_none() { - st.walk = m.land_random_pos(cx.w, 10, 7).map(|p| Walk { - target: Track::Block([ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ]), - speed: SPEED_IDLING as f32, - close_enough: 0, - }); - return; - } - } else { - let duration = 30 + i64::from(m.random.next_int_bound(31).unwrap_or(0)); - st.pause = Some(Pause { - end: now + duration, - }); - return; - } - } -} -fn stop_digging(m: &mut Mob, st: &mut Warden) { - st.digging = None; - // Digging.stop: the warden is removed. - m.removed = true; -} - -fn tick_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // LookAtTargetSink. - if let Some(end) = st.look_sink { - let keep = now <= end - && st.look.is_some_and(|(track, _)| match track { - Track::Block(_) => true, - Track::Entity(who, _) => visible(m, st, cx.w, who), - }); - if keep { - if let Some((track, _)) = st.look - && let Some(p) = track_position(cx.w, track) - { - m.look_at(p); - } - } else { - st.look_sink = None; - st.look = None; - } - } - // MoveToTargetSink. - tick_move_sink(m, st, cx); - // Emerging. - if let Some(end) = st.emerging - && now > end - { - st.emerging = None; - if pose(m) == Pose::Emerging { - set_pose(m, Pose::Standing); - } - } - // Digging: removed when the time is up. - if let Some(end) = st.digging - && now > end - { - stop_digging(m, st); - } - // Sniffing. - if let Some(end) = st.sniffing_run - && now > end - { - st.sniffing_run = None; - if pose(m) == Pose::Sniffing { - set_pose(m, Pose::Standing); - } - st.sniffing = false; - if let Some(entity) = st.nearest_attackable.filter(|e| can_target(cx.w, *e)) - && let Some(p) = position_of(cx.w, entity) - { - if sniff_close(m, p) { - increase_anger(m, st, cx.w, Some(entity), DEFAULT_ANGER, true, cx.events); - } - if st.disturbance.is_none() { - let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; - set_disturbance(st, cx.w, now, block); - } - } - } - // Roar. - if let Some(end) = st.roaring { - if now > end { - st.roaring = None; - if pose(m) == Pose::Roaring { - set_pose(m, Pose::Standing); - } - if let Some(target) = st.roar_target.take() { - set_attack_target(st, target, now); - } - } else if !present(st.roar_sound_delay, now) && !present(st.roar_sound_cooldown, now) { - st.roar_sound_cooldown = st.expiry(now, ROAR_DURATION - ROAR_SOUND_DELAY); - sound(m, "entity.warden.roar", 3.0, 1.0, cx.events); - } - } - // Sonic boom. - if let Some(end) = st.sonic { - if now > end { - st.sonic = None; - st.sonic_cooldown = st.expiry(now, 40); - } else { - tick_sonic_boom(m, st, cx); - } - } - // The idle pause. - if let Some(pause) = st.pause - && now > pause.end - { - st.pause = None; - } -} -/// `Warden.closerThan(entity, 6, 20)` for the sniff. -fn sniff_close(m: &Mob, p: Vec3) -> bool { - closer_than(m, p, 6.0, 20.0) -} -fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - let Some(target) = st.attack_target else { +/// `SonicBoom.tick`: face the target; once the sound delay is over, the +/// beam, the sound, the damage and the knockback. +pub(super) fn tick_sonic_boom(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let Some(target) = warden_brain::mem(m).attack_target.value() else { return; }; - if let Some(t) = cx.w.target_info(target) { + if let Some(t) = w.target_info(target) { m.look_at([t.position.x, t.position.y, t.position.z]); } - if present(st.sonic_sound_delay, now) || present(st.sonic_sound_cooldown, now) { + let mm = warden_brain::mem(m); + if mm.sonic_boom_sound_delay.present() || mm.sonic_boom_sound_cooldown.present() { return; } - st.sonic_sound_cooldown = st.expiry(now, SONIC_DURATION - SONIC_SOUND_DELAY); - if !can_target(cx.w, target) { + mm.sonic_boom_sound_cooldown.set_ttl((), 60 - 34); + if !can_target(w, target) { return; } - let Some(t) = cx.w.target_info(target) else { + let Some(t) = w.target_info(target) else { return; }; if !closer_than(m, t.position, 15.0, 20.0) { @@ -1218,14 +585,15 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { let eye = [t.position.x, t.eye_y, t.position.z]; let delta = [eye[0] - source[0], eye[1] - source[1], eye[2] - source[2]]; let length = (delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]).sqrt(); - if length < 1.0e-9 { - return; - } - let normal = [delta[0] / length, delta[1] / length, delta[2] / length]; + let normal = if length < 1.0e-5 { + [0.0; 3] + } else { + [delta[0] / length, delta[1] / length, delta[2] / length] + }; let steps = length.floor() as i32 + 7; for i in 1..steps { let d = f64::from(i); - cx.events.push(MobEvent::Particles { + events.push(MobEvent::Particles { kind: "sonic_boom", at: [ source[0] + normal[0] * d, @@ -1235,17 +603,17 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { count: 0, }); } - sound(m, "entity.warden.sonic_boom", 3.0, 1.0, cx.events); + sound(m, "entity.warden.sonic_boom", 3.0, 1.0, events); let from = at(m); // Players and the mobs hit here have no knockback resistance. let resistance = 0.0; match target { - Who::Player => cx.events.push(MobEvent::DamagePlayer { + Who::Player => events.push(MobEvent::DamagePlayer { amount: 10.0, from, kind: "minecraft:sonic_boom", }), - Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + Who::Mob(id) => events.push(MobEvent::AttackMob { target: id, amount: 10.0, source: Damage { @@ -1257,7 +625,7 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { } let horizontal = 2.5 * (1.0 - resistance); let vertical = 0.5 * (1.0 - resistance); - cx.events.push(MobEvent::Push { + events.push(MobEvent::Push { target, velocity: [ normal[0] * horizontal, @@ -1266,109 +634,9 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { ], }); } - -// ---- walking: MoveToTargetSink ---- - -fn reached_target(m: &Mob, w: &MobWorld, walk: &Walk) -> bool { - track_block(w, walk.target).is_some_and(|p| manhattan(p, block_pos(m)) <= walk.close_enough) -} -/// `MoveToTargetSink.tryComputePath`. -fn try_compute_path(m: &mut Mob, st: &mut Warden, w: &MobWorld, walk: &Walk) -> Option { - let target = track_block(w, walk.target)?; - let now = i64::from(m.age); - let mut path = m.create_path_to(w, target, 0); - if reached_target(m, w, walk) { - st.cant_reach_since = None; - return None; - } - let can_reach = path.as_ref().is_some_and(|p| p.reached); - if can_reach { - st.cant_reach_since = None; - } else if st.cant_reach_since.is_none() { - st.cant_reach_since = Some(now); - } - if path.is_some() { - return path; - } - let bottom_center = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(p) = m.land_random_pos_towards(w, 10, 7, bottom_center) { - path = m.create_path_to_entity(w, p, 0); - } - path -} -fn start_move_sink(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - let Some(walk) = st.walk else { return }; - if st.move_sink.is_some() { - return; - } - if st.move_cooldown > 0 { - st.move_cooldown -= 1; - return; - } - let reached = reached_target(m, cx.w, &walk); - if !reached && let Some(path) = try_compute_path(m, st, cx.w, &walk) { - let duration = 150 + i64::from(m.random.next_int_bound(101).unwrap_or(0)); - let last = track_block(cx.w, walk.target).unwrap_or_default(); - m.nav_move_to_path(Some(path.clone()), f64::from(walk.speed)); - st.move_sink = Some(MoveSink { - end: now + duration, - last_target: last, - speed: walk.speed, - path: Some(path), - }); - return; - } - st.walk = None; - if reached { - st.cant_reach_since = None; - } -} -fn tick_move_sink(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - let Some(mut sink) = st.move_sink.take() else { - return; - }; - let walk = st.walk; - let still = now <= sink.end - && walk.is_some_and(|walk| { - let spectator = matches!(walk.target, Track::Entity(Who::Player, _)) - && cx.w.player.as_ref().is_some_and(|p| p.spectator); - !m.ai.nav.is_done() && !reached_target(m, cx.w, &walk) && !spectator - }); - if !still { - // MoveToTargetSink.stop. - if let Some(walk) = walk - && !reached_target(m, cx.w, &walk) - && m.ai.nav.stuck - { - st.move_cooldown = m.random.next_int_bound(40).unwrap_or(0); - } - m.nav_stop(); - st.walk = None; - return; - } - if let Some(walk) = walk - && let Some(target) = track_block(cx.w, walk.target) - && dist_sqr(target, sink.last_target) > 4.0 - && let Some(path) = try_compute_path(m, st, cx.w, &walk) - { - sink.last_target = target; - sink.speed = walk.speed; - m.nav_move_to_path(Some(path.clone()), f64::from(walk.speed)); - sink.path = Some(path); - } - st.move_sink = Some(sink); -} - -// ---- per-tick client behaviour ---- - -/// `Warden.tick` on the client: the heartbeat, the tendrils and the digging -/// crumbs; the keyframe states follow the pose. +/// `Warden.tick` on the client: the heartbeat (pitched by the client's copy +/// of the warden: a level event sound here), the tendril and heart +/// animations, digging crumbs, and keyframes that ended. pub fn ai_step(m: &mut Mob, events: &mut Vec) { let Some(st) = m.extra.warden.as_ref() else { return; @@ -1377,8 +645,12 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { let delay = heart_beat_delay(client_anger); if i64::from(m.age) % i64::from(delay) == 0 { m.anim.v[HEART] = 10.0; - let pitch = voice_pitch(m); - sound(m, "entity.warden.heartbeat", 5.0, pitch, events); + events.push(MobEvent::LevelEventSound { + sound: "entity.warden.heartbeat", + at: at(m), + volume: 5.0, + spread: 0.2, + }); } // The animation values count down after the sync of the last tick. for slot in [TENDRIL, HEART] { @@ -1429,10 +701,11 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { } /// Test aid: the minute of calm ran out. pub fn expire_dig_cooldown(m: &mut Mob) { - if let Some(st) = m.extra.warden.as_mut() { - st.dig_cooldown = None; - st.attack_target = None; - st.roar_target = None; + if m.extra.warden.is_some() { + let mm = warden_brain::mem(m); + mm.dig_cooldown.clear(); + mm.attack_target.clear(); + mm.roar_target.clear(); } } /// The warden's state for the control socket. @@ -1444,17 +717,13 @@ pub fn describe(m: &Mob) -> Option { .iter() .map(|w| format!("{w:?}={}", st.anger.anger_of(*w))) .collect(); + let (activities, memories) = warden_brain::describe(m).unwrap_or_default(); Some(serde_json::json!({ "pose": format!("{:?}", pose(m)), - "activity": format!("{:?}", st.activity), + "activities": activities, + "memories": memories, "anger_level": format!("{:?}", anger_level(m)), "anger": anger, - "attack_target": st.attack_target.map(|t| format!("{t:?}")), - "roar_target": st.roar_target.map(|t| format!("{t:?}")), - "disturbance": st.disturbance.map(|(p, _)| p), - "walk": st.walk.is_some(), - "dig_cooldown": st.dig_cooldown.map(|t| t - i64::from(m.age)), - "sniff_cooldown": st.sniff_cooldown.map(|t| t - i64::from(m.age)), "vibration": st.vibration.current.map(|i| i.event), })) } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs new file mode 100644 index 000000000..a513bd6b7 --- /dev/null +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -0,0 +1,1343 @@ +//! The warden's `Brain` (`Warden.BRAIN_PROVIDER` and `WardenAi`), ported +//! behaviour for behaviour on the villager brain's machinery (`Slot` +//! memories with their time to live, `Tracker`s, `WalkTarget`s and the +//! nearest-visible list): the two sensors and their scan phases, the core, +//! emerge, dig, idle, roar, fight, investigate and sniff activities, and their +//! behaviours started and ticked in vanilla's order (priority, then the +//! activity's slot in `Brain.availableBehaviorsByPriority`'s hash map, then +//! the order the activity lists them in). +//! +//! The level random (`ServerLevel.getRandom`) draws every `Behavior`'s +//! duration and the idle `DoNothing`, the sniff cooldown and the spot near a +//! disturbance; the warden's own random drives strolls, sounds and swimming. +//! `RunOne` shuffles with a random of its own, seeded with the brain's +//! shuffle seed. +use super::{ + Mob, MobEvent, MobWorld, Who, + goals::Cx, + path::Path, + villager_brain::{Slot, Tracker, Visible, WalkTarget}, + warden::{self, Pose}, +}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; + +/// `WardenAi` timings. +pub const EMERGE_DURATION: i32 = 134; +pub const ROAR_DURATION: i32 = 84; +const SNIFFING_DURATION: i32 = 84; +const DIGGING_DURATION: i32 = 100; +pub const DIGGING_COOLDOWN: i64 = 1200; +const MELEE_ATTACK_COOLDOWN: i64 = 18; +const SONIC_DURATION: i32 = 60; +const SONIC_SOUND_DELAY: i64 = 34; +const ROAR_SOUND_DELAY: i64 = 25; +const DISTURBANCE_EXPIRY: i64 = 100; +/// `Warden.createAttributes`: the follow range the fight's look target uses. +const FOLLOW_RANGE: f64 = 24.0; + +/// `Activity`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Act { + Core, + Emerge, + Dig, + Idle, + Roar, + Fight, + Investigate, + Sniff, +} +impl Act { + pub fn name(self) -> &'static str { + match self { + Act::Core => "core", + Act::Emerge => "emerge", + Act::Dig => "dig", + Act::Idle => "idle", + Act::Roar => "roar", + Act::Fight => "fight", + Act::Investigate => "investigate", + Act::Sniff => "sniff", + } + } + /// The bucket of `HashMap` (16 buckets, the hash of the + /// name); roar and investigate share one but never a priority. + fn slot(self) -> u8 { + match self { + Act::Core => 1, + Act::Dig => 3, + Act::Idle => 5, + Act::Sniff => 6, + Act::Emerge => 10, + Act::Roar | Act::Investigate => 11, + Act::Fight => 14, + } + } + /// Its place in `getActivities` (insertion order inside a bucket). + fn order(self) -> u8 { + self as u8 + } +} + +/// The memories the warden's brain registers. +#[derive(Clone, Debug, Default)] +pub struct Memories { + pub nearest_players: Slot>, + pub nearest_visible_player: Slot, + pub nearest_visible_targetable_player: Slot, + pub nearest_visible_targetable_players: Slot>, + pub mobs: Slot>, + pub visible_mobs: Slot, + pub nearest_attackable: Slot, + pub look_target: Slot, + pub walk_target: Slot, + pub path: Slot, + pub cant_reach_walk_target_since: Slot, + pub attack_target: Slot, + pub attack_cooling_down: Slot, + pub roar_target: Slot, + pub disturbance_location: Slot<[i32; 3]>, + pub recent_projectile: Slot<()>, + pub is_sniffing: Slot<()>, + pub is_emerging: Slot<()>, + pub roar_sound_delay: Slot<()>, + pub dig_cooldown: Slot<()>, + pub roar_sound_cooldown: Slot<()>, + pub sniff_cooldown: Slot<()>, + pub touch_cooldown: Slot<()>, + pub vibration_cooldown: Slot<()>, + pub sonic_boom_cooldown: Slot<()>, + pub sonic_boom_sound_cooldown: Slot<()>, + pub sonic_boom_sound_delay: Slot<()>, +} +impl Memories { + fn tick(&mut self) { + self.nearest_players.tick(); + self.nearest_visible_player.tick(); + self.nearest_visible_targetable_player.tick(); + self.nearest_visible_targetable_players.tick(); + self.mobs.tick(); + self.visible_mobs.tick(); + self.nearest_attackable.tick(); + self.look_target.tick(); + self.walk_target.tick(); + self.path.tick(); + self.cant_reach_walk_target_since.tick(); + self.attack_target.tick(); + self.attack_cooling_down.tick(); + self.roar_target.tick(); + self.disturbance_location.tick(); + self.recent_projectile.tick(); + self.is_sniffing.tick(); + self.is_emerging.tick(); + self.roar_sound_delay.tick(); + self.dig_cooldown.tick(); + self.roar_sound_cooldown.tick(); + self.sniff_cooldown.tick(); + self.touch_cooldown.tick(); + self.vibration_cooldown.tick(); + self.sonic_boom_cooldown.tick(); + self.sonic_boom_sound_cooldown.tick(); + self.sonic_boom_sound_delay.tick(); + } +} + +/// `Behavior`'s bookkeeping: running, and until when. +#[derive(Clone, Debug)] +struct Timed { + running: bool, + end: i64, + min: i32, + max: i32, +} +impl Timed { + fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw (made even when it cannot vary). + fn begin(&mut self, cx: &mut Bx) { + self.running = true; + let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); + self.end = cx.now + i64::from(d); + } +} + +/// `RunOne`'s `ShufflingList` over a stroll (weight 2) and `DoNothing` (1). +#[derive(Clone, Debug)] +struct Gate { + running: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, +} + +/// One behaviour of the warden's activities. +#[derive(Clone, Debug)] +enum B { + Swim(Timed), + SetWardenLookTarget(bool), + LookAtTargetSink(Timed), + MoveToTargetSink { + t: Timed, + cooldown: i32, + path: Option, + last_target: Option<[i32; 3]>, + speed: f32, + }, + Emerging(Timed), + ForceUnmount(Timed), + Digging(Timed), + SetRoarTarget(bool), + TryToSniff(bool), + RunOne(Box), + Stroll(bool), + DoNothing(Timed), + GoToDisturbance(bool), + Sniffing(Timed), + Roar(Timed), + DigCooldownSetter(bool), + StopAttackingIfTargetInvalid(bool), + SetEntityLookTarget(bool), + SetWalkTargetFromAttackTarget(bool), + SonicBoom(Timed), + MeleeAttack(bool), +} + +#[derive(Clone, Debug)] +struct Entry { + act: Act, + b: B, +} + +/// The warden's brain. +#[derive(Clone, Debug)] +pub struct Brain { + pub mem: Memories, + /// `NEAREST_PLAYERS` and `WARDEN_ENTITY_SENSOR`: ticks to the next scan. + sensors: [i64; 2], + /// The active non-core activity (`CORE` is always active). + pub activity: Act, + list: Vec, + pub shuffle_seed: i64, +} +impl Default for Brain { + fn default() -> Self { + Self::new(0) + } +} +impl Brain { + pub fn new(shuffle_seed: i64) -> Self { + Self { + mem: Memories::default(), + sensors: [0; 2], + activity: Act::Idle, + list: activities(shuffle_seed), + shuffle_seed, + } + } + pub fn is_active(&self, a: Act) -> bool { + a == Act::Core || a == self.activity + } + fn requirements_met(&self, a: Act) -> bool { + let m = &self.mem; + match a { + Act::Emerge => m.is_emerging.present(), + Act::Dig => !m.roar_target.present() && !m.dig_cooldown.present(), + Act::Roar => m.roar_target.present(), + Act::Fight => m.attack_target.present(), + Act::Investigate => m.disturbance_location.present(), + Act::Sniff => m.is_sniffing.present(), + Act::Core | Act::Idle => true, + } + } + /// `setActiveActivity`: leaving an activity erases the memory it needed. + fn set_active(&mut self, a: Act) { + if self.is_active(a) { + return; + } + let m = &mut self.mem; + match self.activity { + Act::Emerge => m.is_emerging.clear(), + Act::Roar => m.roar_target.clear(), + Act::Fight => m.attack_target.clear(), + Act::Investigate => m.disturbance_location.clear(), + Act::Sniff => m.is_sniffing.clear(), + Act::Core | Act::Dig | Act::Idle => {} + } + self.activity = a; + } + /// `WardenAi.updateActivity`: `setActiveActivityToFirstValid`. + pub fn update_activity(&mut self) { + for a in [ + Act::Emerge, + Act::Dig, + Act::Roar, + Act::Fight, + Act::Investigate, + Act::Sniff, + Act::Idle, + ] { + if self.requirements_met(a) { + self.set_active(a); + break; + } + } + } + /// `Sensor.randomlyDelayStart` for both sensors, from the warden's random. + pub fn delay_sensors(&mut self, random: &mut LegacyRandom) { + for s in &mut self.sensors { + *s = i64::from(random.next_int_bound(20).unwrap_or(0)); + } + } +} + +/// `WardenAi.getActivities`, in the order `Brain.startEachNonRunningBehavior` +/// meets the behaviours. +fn activities(seed: i64) -> Vec { + let gate = Gate { + running: false, + random: LegacyRandom::new(seed), + kids: vec![ + (B::Stroll(false), 2, 0.0), + (B::DoNothing(Timed::new(30, 60)), 1, 0.0), + ], + }; + let mut list = vec![ + (0, Act::Core, B::Swim(Timed::new(60, 60))), + (1, Act::Core, B::SetWardenLookTarget(false)), + (2, Act::Core, B::LookAtTargetSink(Timed::new(45, 90))), + ( + 3, + Act::Core, + B::MoveToTargetSink { + t: Timed::new(150, 250), + cooldown: 0, + path: None, + last_target: None, + speed: 0.0, + }, + ), + (5, Act::Emerge, B::Emerging(Timed::new(EMERGE_DURATION, EMERGE_DURATION))), + (0, Act::Dig, B::ForceUnmount(Timed::new(60, 60))), + (1, Act::Dig, B::Digging(Timed::new(DIGGING_DURATION, DIGGING_DURATION))), + (10, Act::Idle, B::SetRoarTarget(false)), + (11, Act::Idle, B::TryToSniff(false)), + (12, Act::Idle, B::RunOne(Box::new(gate))), + (10, Act::Roar, B::Roar(Timed::new(ROAR_DURATION, ROAR_DURATION))), + (10, Act::Fight, B::DigCooldownSetter(false)), + (11, Act::Fight, B::StopAttackingIfTargetInvalid(false)), + (12, Act::Fight, B::SetEntityLookTarget(false)), + (13, Act::Fight, B::SetWalkTargetFromAttackTarget(false)), + (14, Act::Fight, B::SonicBoom(Timed::new(SONIC_DURATION, SONIC_DURATION))), + (15, Act::Fight, B::MeleeAttack(false)), + (5, Act::Investigate, B::SetRoarTarget(false)), + (6, Act::Investigate, B::GoToDisturbance(false)), + (5, Act::Sniff, B::SetRoarTarget(false)), + (6, Act::Sniff, B::Sniffing(Timed::new(SNIFFING_DURATION, SNIFFING_DURATION))), + ]; + // A stable sort keeps each activity's own order. + list.sort_by_key(|(prio, act, _)| (*prio, act.slot(), act.order())); + list.into_iter() + .map(|(_, act, b)| Entry { act, b }) + .collect() +} + +/// What behaviours read and emit during a brain tick. +pub struct Bx<'a, 'w> { + pub w: &'a MobWorld<'w>, + pub lr: &'a mut LegacyRandom, + pub events: &'a mut Vec, + pub now: i64, +} + +fn brain(m: &Mob) -> Option<&Brain> { + m.extra.warden.as_ref().map(|w| &w.brain) +} +pub(super) fn mem(m: &mut Mob) -> &mut Memories { + &mut m.extra.warden.as_mut().expect("a warden").brain.mem +} +pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { + brain(m).map(|b| &b.mem) +} + +/// `Brain.tick` (from `Warden.customServerAiStep`). +pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec) { + if m.extra.warden.is_none() { + return; + } + // forgetOutdatedMemories + mem(m).tick(); + tick_sensors(m, w); + let Some(st) = m.extra.warden.as_mut() else { + return; + }; + let mut list = std::mem::take(&mut st.brain.list); + let mut cx = Bx { + w, + lr, + events, + now: w.game_time, + }; + for e in &mut list { + let active = m + .extra + .warden + .as_ref() + .is_some_and(|st| st.brain.is_active(e.act)); + if active && !e.b.running() { + e.b.try_start(m, &mut cx); + } + } + for e in &mut list { + if e.b.running() { + e.b.tick_or_stop(m, &mut cx); + } + } + if let Some(st) = m.extra.warden.as_mut() { + st.brain.list = list; + } +} + +// ---- Sensors ------------------------------------------------------------ + +fn tick_sensors(m: &mut Mob, w: &MobWorld) { + for i in 0..2 { + let fire = { + let b = &mut m.extra.warden.as_mut().expect("a warden").brain; + b.sensors[i] -= 1; + if b.sensors[i] <= 0 { + b.sensors[i] = 20; + true + } else { + false + } + }; + if fire { + if i == 0 { + sense_players(m, w); + } else { + sense_entities(m, w); + } + } + } +} +/// `TargetingConditions.forNonCombat().range(followRange)` (sensors use the +/// follow range of the mob that scanned last). +fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let range = m.attrs.follow_range; + match who { + Who::Player => m.can_see_player(w, range), + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && m.distance_sqr(s.position) <= range.max(2.0).powi(2) && m.sees(w, who) + } + } +} +/// `PlayerSensor`. +fn sense_players(m: &mut Mob, w: &MobWorld) { + let range = m.attrs.follow_range; + let near = w + .player + .as_ref() + .is_some_and(|p| !p.spectator && m.distance_sqr(p.position) < range * range); + let players: Vec = if near { vec![Who::Player] } else { vec![] }; + let visible: Vec = players + .iter() + .copied() + .filter(|&p| targetable(m, w, p)) + .collect(); + let attackable: Vec = visible + .iter() + .copied() + .filter(|_| m.can_target_player(w, range, true)) + .collect(); + let mm = mem(m); + mm.nearest_players.set_list(players); + mm.nearest_visible_player.set_opt(visible.first().copied()); + mm.nearest_visible_targetable_players + .set_list(attackable.clone()); + mm.nearest_visible_targetable_player + .set_opt(attackable.first().copied()); +} +/// `WardenEntitySensor`: `NearestLivingEntitySensor`, then the nearest +/// targetable player, else the nearest other targetable entity. +fn sense_entities(m: &mut Mob, w: &MobWorld) { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let attackable = list + .iter() + .copied() + .find(|&e| e == Who::Player && warden::can_target(w, e)) + .or_else(|| { + list.iter() + .copied() + .find(|&e| e != Who::Player && warden::can_target(w, e)) + }); + let mm = mem(m); + mm.mobs.set_list(list.clone()); + mm.visible_mobs.set(Visible { + list, + cache: Vec::new(), + }); + mm.nearest_attackable.set_opt(attackable); +} +/// The visible-entities memory's line-of-sight test, cached per memory. +fn visible_test(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + match mem_ref(m).and_then(|mm| mm.visible_mobs.get()) { + Some(v) => { + if let Some(&(_, r)) = v.cache.iter().find(|(k, _)| *k == who) { + return r; + } + } + None => return false, + } + // Sensor.isEntityTargetable: the attack target ignores invisibility. + let r = targetable(m, w, who); + if let Some(v) = mem(m).visible_mobs.get_mut() { + v.cache.push((who, r)); + } + r +} +/// `NearestVisibleLivingEntities.contains(entity)`. +fn visible_contains(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let listed = mem_ref(m) + .and_then(|mm| mm.visible_mobs.get()) + .is_some_and(|v| v.list.contains(&who)); + listed && visible_test(m, w, who) +} +/// `NearestVisibleLivingEntities.findClosest`. +fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) -> Option { + let list = mem_ref(m)?.visible_mobs.get()?.list.clone(); + list.into_iter() + .find(|&who| filter(m, who) && visible_test(m, w, who)) +} + +// ---- Shared warden actions ------------------------------------------------ + +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} +fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { + (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() +} +fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { + (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum() +} +/// `WardenAi.setDigCooldown`. +pub(super) fn set_dig_cooldown(m: &mut Mob) { + let mm = mem(m); + if mm.dig_cooldown.present() { + mm.dig_cooldown.set_ttl((), DIGGING_COOLDOWN); + } +} +/// `WardenAi.setDisturbanceLocation`. +pub(super) fn set_disturbance(m: &mut Mob, w: &MobWorld, position: [i32; 3]) { + if warden::entity_angry_at(m, w).is_some() || mem(m).attack_target.present() { + return; + } + set_dig_cooldown(m); + let mm = mem(m); + mm.sniff_cooldown.set_ttl((), DISTURBANCE_EXPIRY); + mm.look_target + .set_ttl(Tracker::Block(position), DISTURBANCE_EXPIRY); + mm.disturbance_location.set_ttl(position, DISTURBANCE_EXPIRY); + mm.walk_target.clear(); +} +/// `Warden.setAttackTarget`. +pub(super) fn set_attack_target(m: &mut Mob, target: Who) { + let mm = mem(m); + mm.roar_target.clear(); + mm.attack_target.set(target); + mm.cant_reach_walk_target_since.clear(); + mm.sonic_boom_cooldown.set_ttl((), 200); +} +/// `Entity.closerThan(target, horizontal, vertical)`. +fn closer_than(m: &Mob, p: Vec3, horizontal: f64, vertical: f64) -> bool { + let (dx, dy, dz) = (p.x - m.position.x, p.y - m.position.y, p.z - m.position.z); + dx * dx + dz * dz < horizontal * horizontal && dy * dy < vertical * vertical +} +/// `PositionTracker.isVisibleBy`. +fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { + match t { + Tracker::Entity(who, _) => { + w.target_info(who).is_some_and(|i| i.alive) && visible_contains(m, w, who) + } + _ => true, + } +} +/// `MoveToTargetSink.reachedTarget`. +fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { + walk.target + .block(w) + .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) +} +/// `MoveToTargetSink.tryComputePath`. +fn compute_path( + m: &mut Mob, + cx: &mut Bx, + walk: &WalkTarget, + path: &mut Option, + speed: &mut f32, +) -> bool { + let Some(target) = walk.target.block(cx.w) else { + return false; + }; + *path = m.create_path_to(cx.w, target, 0); + *speed = walk.speed; + if reached(m, cx.w, walk) { + mem(m).cant_reach_walk_target_since.clear(); + } else { + let can_reach = path.as_ref().is_some_and(|p| p.reached); + let mm = mem(m); + if can_reach { + mm.cant_reach_walk_target_since.clear(); + } else if !mm.cant_reach_walk_target_since.present() { + mm.cant_reach_walk_target_since.set(cx.now); + } + if path.is_some() { + return true; + } + let to = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ]; + if let Some(step) = + m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + { + let p = [ + step[0].floor() as i32, + step[1].floor() as i32, + step[2].floor() as i32, + ]; + *path = m.create_path_to(cx.w, p, 0); + return path.is_some(); + } + } + false +} +fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.nodes == b.nodes && a.target == b.target, + _ => false, + } +} +fn sound(m: &Mob, name: &'static str, volume: f32, pitch: f32, events: &mut Vec) { + events.push(MobEvent::Sound( + name, + [m.position.x, m.position.y, m.position.z], + volume, + pitch, + )); +} + +// ---- Behaviours ----------------------------------------------------------- + +impl B { + fn running(&self) -> bool { + match self { + B::Swim(t) + | B::LookAtTargetSink(t) + | B::Emerging(t) + | B::ForceUnmount(t) + | B::Digging(t) + | B::DoNothing(t) + | B::Sniffing(t) + | B::Roar(t) + | B::SonicBoom(t) => t.running, + B::MoveToTargetSink { t, .. } => t.running, + B::RunOne(g) => g.running, + B::SetWardenLookTarget(r) + | B::SetRoarTarget(r) + | B::TryToSniff(r) + | B::Stroll(r) + | B::GoToDisturbance(r) + | B::DigCooldownSetter(r) + | B::StopAttackingIfTargetInvalid(r) + | B::SetEntityLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r, + } + } + + /// `BehaviorControl.tryStart`. + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + match self { + B::Swim(t) => { + if !swim_condition(m) { + return false; + } + t.begin(cx); + true + } + B::SetWardenLookTarget(r) => one(r, || { + let mm = mem(m); + if mm.attack_target.present() { + return false; + } + let target = mm + .roar_target + .value() + .and_then(|who| cx.w.target_info(who)) + .map(|t| block_of(t.position)) + .or_else(|| mm.disturbance_location.value()); + let Some(p) = target else { return false }; + mem(m).look_target.set(Tracker::Block(p)); + true + }), + B::LookAtTargetSink(t) => { + if !mem(m).look_target.present() { + return false; + } + t.begin(cx); + true + } + B::MoveToTargetSink { + t, + cooldown, + path, + last_target, + speed, + } => { + let mm = mem(m); + if mm.path.present() || !mm.walk_target.present() { + return false; + } + // checkExtraStartConditions + if *cooldown > 0 { + *cooldown -= 1; + return false; + } + let Some(walk) = mm.walk_target.value() else { + return false; + }; + let reached = reached(m, cx.w, &walk); + if !reached && compute_path(m, cx, &walk, path, speed) { + *last_target = walk.target.block(cx.w); + t.begin(cx); + // start + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + return true; + } + let mm = mem(m); + mm.walk_target.clear(); + if reached { + mm.cant_reach_walk_target_since.clear(); + } + false + } + B::Emerging(t) => { + let mm = mem(m); + if !mm.is_emerging.present() || mm.walk_target.present() { + return false; + } + t.begin(cx); + warden::set_pose(m, Pose::Emerging); + sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); + true + } + // ForceUnmount: a warden never rides (Warden.canRide). + B::ForceUnmount(_) => false, + B::Digging(t) => { + let mm = mem(m); + if mm.attack_target.present() || mm.walk_target.present() { + return false; + } + let liquid = m.fluids.in_water || m.fluids.in_lava; + if !(m.on_ground || liquid) { + return false; + } + t.begin(cx); + if m.on_ground { + warden::set_pose(m, Pose::Digging); + sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); + } else { + sound(m, "entity.warden.agitated", 5.0, 1.0, cx.events); + // `stop` without `doStop`: discarded, still running. + m.removed = true; + } + true + } + B::SetRoarTarget(r) => one(r, || { + let mm = mem(m); + if mm.roar_target.present() || mm.attack_target.present() { + return false; + } + let Some(target) = warden::entity_angry_at(m, cx.w) else { + return false; + }; + if !warden::can_target(cx.w, target) { + return false; + } + let mm = mem(m); + mm.roar_target.set(target); + mm.cant_reach_walk_target_since.clear(); + true + }), + B::TryToSniff(r) => one(r, || { + let mm = mem(m); + if mm.sniff_cooldown.present() + || !mm.nearest_attackable.present() + || mm.disturbance_location.present() + { + return false; + } + mm.is_sniffing.set(()); + // UniformInt.of(100, 200).sample(level.getRandom()) + let cooldown = 100 + cx.lr.next_int_bound(101).unwrap_or(0); + let mm = mem(m); + mm.sniff_cooldown.set_ttl((), i64::from(cooldown)); + mm.walk_target.clear(); + warden::set_pose(m, Pose::Sniffing); + true + }), + B::RunOne(g) => { + if mem(m).is_sniffing.present() { + return false; + } + g.running = true; + // ShufflingList.shuffle: a fresh weight for each entry in the + // current order, then a stable sort. + for k in &mut g.kids { + let r = g.random.next_float(); + k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + } + g.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); + for k in &mut g.kids { + if !k.0.running() && k.0.try_start(m, cx) { + break; + } + } + true + } + B::Stroll(r) => one(r, || { + if mem(m).walk_target.present() { + return false; + } + // RandomStroll.stroll(0.5): LandRandomPos.getPos(body, 10, 7). + let target = m.land_random_pos(cx.w, 10, 7); + mem(m).walk_target.set_opt(target.map(|p| WalkTarget { + target: Tracker::Block([ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]), + speed: 0.5, + close: 0, + })); + true + }), + B::DoNothing(t) => { + t.begin(cx); + true + } + B::GoToDisturbance(r) => one(r, || { + let mm = mem(m); + if mm.attack_target.present() || mm.walk_target.present() { + return false; + } + let Some(p) = mm.disturbance_location.value() else { + return false; + }; + // Vec3i.closerThan(body.blockPosition(), 2) + if dist_sqr(p, block_of(m.position)) >= 4 { + // GoToTargetLocation.getNearbyPos: the level random. + let dx = cx.lr.next_int_bound(3).unwrap_or(0) - 1; + let dz = cx.lr.next_int_bound(3).unwrap_or(0) - 1; + let near = [p[0] + dx, p[1], p[2] + dz]; + let mm = mem(m); + mm.look_target.set(Tracker::Block(near)); + mm.walk_target.set(WalkTarget { + target: Tracker::Block(near), + speed: 0.7, + close: 2, + }); + } + true + }), + B::Sniffing(t) => { + let mm = mem(m); + if !mm.is_sniffing.present() + || mm.attack_target.present() + || mm.walk_target.present() + { + return false; + } + t.begin(cx); + sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); + true + } + B::Roar(t) => { + let mm = mem(m); + if mm.attack_target.present() { + return false; + } + let Some(target) = mm.roar_target.value() else { + return false; + }; + t.begin(cx); + let mm = mem(m); + mm.roar_sound_delay.set_ttl((), ROAR_SOUND_DELAY); + mm.walk_target.clear(); + // BehaviorUtils.lookAtEntity + mm.look_target.set(Tracker::Entity(target, true)); + warden::set_pose(m, Pose::Roaring); + warden::increase_anger(m, cx.w, Some(target), 20, false, cx.events); + true + } + B::DigCooldownSetter(r) => one(r, || { + set_dig_cooldown(m); + true + }), + B::StopAttackingIfTargetInvalid(r) => one(r, || { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let alive = cx.w.target_info(target).is_some_and(|t| t.alive); + let can = warden::can_target(cx.w, target); + let angry = warden::anger_level(m).is_angry(); + if can && alive && angry { + return true; + } + // WardenAi.onTargetInvalid + if !can && let Some(st) = m.extra.warden.as_mut() { + st.anger.clear(target); + } + set_dig_cooldown(m); + mem(m).attack_target.clear(); + true + }), + B::SetEntityLookTarget(r) => one(r, || { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let target = mm.attack_target.value(); + let max = (FOLLOW_RANGE as f32 * FOLLOW_RANGE as f32) as f64; + let w = cx.w; + let found = find_closest(m, w, |m, who| { + Some(who) == target + && w.target_info(who) + .is_some_and(|t| m.distance_sqr(t.position) <= max) + }); + let Some(found) = found else { return false }; + mem(m).look_target.set(Tracker::Entity(found, true)); + true + }), + B::SetWalkTargetFromAttackTarget(r) => one(r, || { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let w = cx.w; + let in_reach = mem(m).visible_mobs.present() + && visible_contains(m, w, target) + && w.target_info(target) + .is_some_and(|t| m.within_melee_range(&t)); + let mm = mem(m); + if in_reach { + mm.walk_target.clear(); + } else { + mm.look_target.set(Tracker::Entity(target, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(target, false), + speed: 1.2, + close: 0, + }); + } + true + }), + B::SonicBoom(t) => { + let mm = mem(m); + if mm.sonic_boom_cooldown.present() { + return false; + } + let Some(target) = mm.attack_target.value() else { + return false; + }; + let close = cx + .w + .target_info(target) + .is_some_and(|i| closer_than(m, i.position, 15.0, 20.0)); + if !close { + return false; + } + t.begin(cx); + let mm = mem(m); + mm.attack_cooling_down + .set_ttl(true, i64::from(SONIC_DURATION)); + mm.sonic_boom_sound_delay.set_ttl((), SONIC_SOUND_DELAY); + // Entity event 62: the sonic boom keyframes start. + m.anim.states[warden::SONIC_BOOM].start(m.age as f32); + sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); + true + } + B::MeleeAttack(r) => one(r, || { + let mm = mem(m); + if mm.attack_cooling_down.present() || !mm.visible_mobs.present() { + return false; + } + let Some(target) = mm.attack_target.value() else { + return false; + }; + let w = cx.w; + let Some(info) = w.target_info(target) else { + return false; + }; + if !(m.within_melee_range(&info) && visible_contains(m, w, target)) { + return false; + } + mem(m).look_target.set(Tracker::Entity(target, true)); + m.swing(); + warden::do_hurt_target(m, target, w, cx.events); + mem(m) + .attack_cooling_down + .set_ttl(true, MELEE_ATTACK_COOLDOWN); + true + }), + } + } + + /// `BehaviorControl.tickOrStop`. + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + let now = cx.now; + match self { + B::Swim(t) => { + if now > t.end || !swim_condition(m) { + self.do_stop(m, cx); + } else if m.random.next_float() < 0.8 { + m.ai.jumping = true; + } + } + B::LookAtTargetSink(t) => { + let target = mem(m).look_target.value(); + let visible = match target { + Some(tr) => tracker_visible(m, cx.w, tr), + None => false, + }; + if now > t.end || !visible { + self.do_stop(m, cx); + } else if let Some(at) = target.and_then(|tr| tr.position(cx.w)) { + m.look_at(at); + } + } + B::MoveToTargetSink { + t, + path, + last_target, + speed, + .. + } => { + let still = path.is_some() + && last_target.is_some() + && mem(m).walk_target.value().is_some_and(|walk| { + !m.ai.nav.is_done() + && !reached(m, cx.w, &walk) + && !matches!(walk.target, Tracker::Entity(Who::Player, _) + if cx.w.player.as_ref().is_some_and(|p| p.spectator)) + }); + if now > t.end || !still { + self.do_stop(m, cx); + return; + } + let new_path = m.ai.nav.path.clone(); + if !same_path(path.as_ref(), new_path.as_ref()) { + *path = new_path.clone(); + mem(m).path.set_opt(new_path.clone()); + } + if new_path.is_some() + && let Some(last) = *last_target + && let Some(walk) = mem(m).walk_target.value() + && let Some(now_target) = walk.target.block(cx.w) + && dist_sqr(now_target, last) > 4 + && compute_path(m, cx, &walk, path, speed) + { + *last_target = Some(now_target); + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + } + } + // canStillUse is true: they run their duration. + B::Emerging(t) | B::Sniffing(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::ForceUnmount(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::Digging(t) => { + if now > t.end || m.removed { + self.do_stop(m, cx); + } + } + B::DoNothing(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::RunOne(g) => { + for k in &mut g.kids { + if k.0.running() { + k.0.tick_or_stop(m, cx); + } + } + if !g.kids.iter().any(|k| k.0.running()) { + self.do_stop(m, cx); + } + } + B::Roar(t) => { + if now > t.end { + self.do_stop(m, cx); + return; + } + let mm = mem(m); + if !mm.roar_sound_delay.present() && !mm.roar_sound_cooldown.present() { + mm.roar_sound_cooldown + .set_ttl((), i64::from(ROAR_DURATION) - ROAR_SOUND_DELAY); + sound(m, "entity.warden.roar", 3.0, 1.0, cx.events); + } + } + B::SonicBoom(t) => { + if now > t.end { + self.do_stop(m, cx); + return; + } + warden::tick_sonic_boom(m, cx.w, cx.events); + } + // OneShot.tickOrStop: they stop the tick they ran. + _ => self.do_stop(m, cx), + } + } + + /// `BehaviorControl.doStop`. + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + match self { + B::Swim(t) | B::ForceUnmount(t) | B::DoNothing(t) => t.running = false, + B::LookAtTargetSink(t) => { + t.running = false; + mem(m).look_target.clear(); + } + B::MoveToTargetSink { + t, cooldown, path, .. + } => { + t.running = false; + if let Some(walk) = mem(m).walk_target.value() + && !reached(m, cx.w, &walk) + && m.ai.nav.stuck + { + *cooldown = cx.lr.next_int_bound(40).unwrap_or(0); + } + m.nav_stop(); + let mm = mem(m); + mm.walk_target.clear(); + mm.path.clear(); + *path = None; + } + B::Emerging(t) => { + t.running = false; + if warden::pose(m) == Pose::Emerging { + warden::set_pose(m, Pose::Standing); + } + } + B::Digging(t) => { + t.running = false; + m.removed = true; + } + B::RunOne(g) => { + g.running = false; + for k in &mut g.kids { + if k.0.running() { + k.0.do_stop(m, cx); + } + } + } + B::Sniffing(t) => { + t.running = false; + if warden::pose(m) == Pose::Sniffing { + warden::set_pose(m, Pose::Standing); + } + mem(m).is_sniffing.clear(); + let w = cx.w; + if let Some(entity) = mem(m).nearest_attackable.value() + && warden::can_target(w, entity) + && let Some(info) = w.target_info(entity) + { + if closer_than(m, info.position, 6.0, 20.0) { + warden::increase_anger(m, w, Some(entity), 35, true, cx.events); + } + if !mem(m).disturbance_location.present() { + set_disturbance(m, w, block_of(info.position)); + } + } + } + B::Roar(t) => { + t.running = false; + if warden::pose(m) == Pose::Roaring { + warden::set_pose(m, Pose::Standing); + } + if let Some(target) = mem(m).roar_target.value() { + set_attack_target(m, target); + } + mem(m).roar_target.clear(); + } + B::SonicBoom(t) => { + t.running = false; + mem(m).sonic_boom_cooldown.set_ttl((), 40); + } + B::SetWardenLookTarget(r) + | B::SetRoarTarget(r) + | B::TryToSniff(r) + | B::Stroll(r) + | B::GoToDisturbance(r) + | B::DigCooldownSetter(r) + | B::StopAttackingIfTargetInvalid(r) + | B::SetEntityLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r = false, + } + } +} + +/// `OneShot.tryStart`: running when the trigger fires. +fn one(running: &mut bool, f: impl FnOnce() -> bool) -> bool { + if f() { + *running = true; + true + } else { + false + } +} +/// `Swim`: deeper than the jump threshold, or in lava. +fn swim_condition(m: &Mob) -> bool { + m.fluids.water > m.fluid_jump_threshold() || m.fluids.in_lava +} +/// The `Cx` the mob library's attacks take. +pub(super) fn cx<'a, 'w>(w: &'a MobWorld<'w>, events: &'a mut Vec) -> Cx<'a, 'w> { + Cx { w, events } +} + +// ---- Printing --------------------------------------------------------------- + +fn who(w: Who) -> String { + match w { + Who::Player => "player".into(), + Who::Mob(id) => format!("e{id}"), + } +} +fn pos(p: [i32; 3]) -> String { + format!("{},{},{}", p[0], p[1], p[2]) +} +fn tracker(t: Tracker) -> String { + match t { + Tracker::Entity(e, _) => who(e), + Tracker::Block(p) => pos(p), + Tracker::Point(v) => pos([ + v[0].floor() as i32, + v[1].floor() as i32, + v[2].floor() as i32, + ]), + } +} +/// The active activities and the memories with values, as the mob AI oracle +/// prints them (`act core|idle`, `mem name=value...` sorted). +pub fn describe(m: &Mob) -> Option<(String, String)> { + let b = brain(m)?; + let mut acts = ["core", b.activity.name()]; + acts.sort_unstable(); + let mm = &b.mem; + let mut out: Vec = Vec::new(); + let mut put = |name: &str, value: String, ttl: i64| { + if ttl == i64::MAX { + out.push(format!("{name}={value}")); + } else { + out.push(format!("{name}={value}@{ttl}")); + } + }; + macro_rules! slot { + ($name:expr, $s:expr, $f:expr) => { + if let Some(v) = $s.get() { + put($name, $f(v), $s.ttl()); + } + }; + } + let unit = |_: &()| "u".to_string(); + let list = |l: &Vec| format!("n{}", l.len()); + slot!("nearest_players", mm.nearest_players, list); + slot!("nearest_visible_player", mm.nearest_visible_player, |e: &Who| who(*e)); + slot!( + "nearest_visible_targetable_player", + mm.nearest_visible_targetable_player, + |e: &Who| who(*e) + ); + slot!( + "nearest_visible_targetable_players", + mm.nearest_visible_targetable_players, + list + ); + slot!("mobs", mm.mobs, list); + slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { + "NearestVisibleLivingEntities".to_string() + }); + slot!("nearest_attackable", mm.nearest_attackable, |e: &Who| who(*e)); + slot!("look_target", mm.look_target, |t: &Tracker| tracker(*t)); + slot!("walk_target", mm.walk_target, |t: &WalkTarget| format!( + "{}/{:x}/{}", + tracker(t.target), + t.speed.to_bits(), + t.close + )); + slot!("path", mm.path, |p: &Path| format!("path{}", pos(p.target))); + slot!( + "cant_reach_walk_target_since", + mm.cant_reach_walk_target_since, + |t: &i64| t.to_string() + ); + slot!("attack_target", mm.attack_target, |e: &Who| who(*e)); + slot!("attack_cooling_down", mm.attack_cooling_down, |t: &bool| t + .to_string()); + slot!("roar_target", mm.roar_target, |e: &Who| who(*e)); + slot!( + "disturbance_location", + mm.disturbance_location, + |p: &[i32; 3]| pos(*p) + ); + slot!("recent_projectile", mm.recent_projectile, unit); + slot!("is_sniffing", mm.is_sniffing, unit); + slot!("is_emerging", mm.is_emerging, unit); + slot!("roar_sound_delay", mm.roar_sound_delay, unit); + slot!("dig_cooldown", mm.dig_cooldown, unit); + slot!("roar_sound_cooldown", mm.roar_sound_cooldown, unit); + slot!("sniff_cooldown", mm.sniff_cooldown, unit); + slot!("touch_cooldown", mm.touch_cooldown, unit); + slot!("vibration_cooldown", mm.vibration_cooldown, unit); + slot!("sonic_boom_cooldown", mm.sonic_boom_cooldown, unit); + slot!("sonic_boom_sound_cooldown", mm.sonic_boom_sound_cooldown, unit); + slot!("sonic_boom_sound_delay", mm.sonic_boom_sound_delay, unit); + out.sort(); + Some((acts.join("|"), out.join(" "))) +} 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 7185ec400..d44b4135e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -467,6 +467,17 @@ public final class VanillaMobAiOracle { for (String flag : spec.flags) { if (flag.equals("persistent")) mob.setPersistenceRequired(); else if (flag.equals("noai")) mob.setNoAi(true); + // Warden.finalizeSpawn's own part (Mob.finalizeSpawn draws the level random, + // which is not seeded yet): a minute before digging, or climbing out first. + else if (flag.equals("digcooldown") || flag.equals("emerge")) { + mob.getBrain().setMemoryWithExpiry(net.minecraft.world.entity.ai.memory.MemoryModuleType.DIG_COOLDOWN, + net.minecraft.util.Unit.INSTANCE, 1200L); + if (flag.equals("emerge")) { + mob.setPose(net.minecraft.world.entity.Pose.EMERGING); + mob.getBrain().setMemoryWithExpiry(net.minecraft.world.entity.ai.memory.MemoryModuleType.IS_EMERGING, + net.minecraft.util.Unit.INSTANCE, net.minecraft.world.entity.monster.warden.WardenAi.EMERGE_DURATION); + } + } else throw new IllegalArgumentException(flag); } level.addFreshEntity(mob); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 5730d8b3d..fc987aedd 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -77,6 +77,16 @@ def scenarios(): 'player 12.5 -60 0.5', 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) + # The warden: idle, sniffing out a player, roaring and fighting (WardenAi). + # Without finalizeSpawn's dig cooldown a warden digs straight back down. + add('warden_digs', 140, ['mob minecraft:warden 0.5 -60 0.5 0 60']) + add('warden_alone', 400, ['mob minecraft:warden 0.5 -60 0.5 0 61 digcooldown']) + add('warden_player', 600, ['player 5.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 62 digcooldown']) + add('warden_player_far', 600, ['player 14.5 -60 3.5', 'mob minecraft:warden 0.5 -60 0.5 90 63 digcooldown']) + add('warden_creative', 300, ['player 4.5 -60 0.5 creative', 'mob minecraft:warden 0.5 -60 0.5 0 64 digcooldown']) + add('warden_persistent', 400, ['player 7.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 65 persistent digcooldown']) + add('warden_emerging', 300, ['player 6.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 66 emerge']) + add('warden_cow', 600, ['mob minecraft:warden 0.5 -60 0.5 0 67 digcooldown', 'mob minecraft:cow 4.5 -60 0.5 0 68 persistent']) return s From 9c465af186cfd3dc816d0eb707b920518f23df5a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:46:50 +0200 Subject: [PATCH 02/14] WIP: unfinished spawn-gear parity work, stopped by Ludovic Uncommitted changes the agent had in progress when it was stopped on 2026-10-12; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- .../examples/finalize_spawn_fixture.rs | 484 ++++ crates/horizon-client/src/game/perspective.rs | 1 + crates/horizon-client/src/mobs.rs | 60 +- crates/horizon-client/src/mobs/aquatic.rs | 52 +- crates/horizon-client/src/mobs/finalize.rs | 1972 +++++++++++++++++ .../parity/VanillaFinalizeSpawnOracle.java | 525 +++++ tools/test_finalize_spawn_parity.py | 177 ++ 7 files changed, 3243 insertions(+), 28 deletions(-) create mode 100644 crates/horizon-client/examples/finalize_spawn_fixture.rs create mode 100644 crates/horizon-client/src/mobs/finalize.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java create mode 100644 tools/test_finalize_spawn_parity.py diff --git a/crates/horizon-client/examples/finalize_spawn_fixture.rs b/crates/horizon-client/examples/finalize_spawn_fixture.rs new file mode 100644 index 000000000..0e9aa9a5a --- /dev/null +++ b/crates/horizon-client/examples/finalize_spawn_fixture.rs @@ -0,0 +1,484 @@ +//! `Mob.finalizeSpawn` for differential tests against vanilla +//! (tools/test_finalize_spawn_parity.py): reads the cases of +//! `VanillaFinalizeSpawnOracle`, runs `mobs::finalize` with the same level +//! random and entity randoms, and prints every entity of the case in the +//! oracle's format. +//! +//! usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN +use horizon_client::{ + assets::Assets, + blocks::BlockFacts, + enchant::Enchantments, + items::Items, + mobs::{ + Mob, MobTypes, Species, + data::MobData, + finalize::{self, Attr, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries}, + gear, + render::{DYE_NAMES, PROFESSIONS, VILLAGER_TYPES}, + spawning::LocalDifficulty, + }, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource}, +}; +use std::{collections::HashMap, fmt::Write as _, fs, path::Path, sync::Arc}; + +struct Level<'a> { + types: &'a MobTypes, + data: &'a MobData, + biome: String, + structure: Option<(String, [i32; 6])>, + phase: usize, + monsters: bool, + peaceful: bool, + time: i64, + halloween: bool, + roof: Option, + eseed: i64, + /// Every entity of the case in creation order (case chickens first). + created: usize, + /// The level's entities that can carry a zombie: (id, bounds, ridden). + chickens: Vec<(u32, Aabb, bool)>, + rides: Vec<(u32, u32)>, +} +impl FinalizeLevel for Level<'_> { + fn biome(&self, _pos: [i32; 3]) -> String { + self.biome.clone() + } + fn biome_tag(&self, tag: &str, _pos: [i32; 3]) -> bool { + self.data.biome_has(tag, &self.biome) + } + fn structures_with_piece_at(&self, pos: [i32; 3]) -> Vec { + match &self.structure { + Some((id, b)) + if pos[0] >= b[0] + && pos[0] <= b[3] + && pos[1] >= b[1] + && pos[1] <= b[4] + && pos[2] >= b[2] + && pos[2] <= b[5] => + { + vec![id.clone()] + } + _ => Vec::new(), + } + } + fn moon_phase(&self, _pos: [i32; 3]) -> usize { + self.phase + } + fn spawning_monsters(&self) -> bool { + self.monsters + } + fn no_collision(&self, bounds: Aabb) -> bool { + // A floor under the spawn point and an optional roof layer. + self.roof.is_none_or(|y| { + let (lo, hi) = (bounds.min(horizon_core::geometry::Axis::Y), bounds.max(horizon_core::geometry::Axis::Y)); + !(lo < f64::from(y) + 1.0 && hi > f64::from(y)) + }) + } + fn free_chicken(&self, bounds: Aabb) -> Option { + self.chickens + .iter() + .find(|(_, b, ridden)| !ridden && b.intersects(bounds)) + .map(|c| c.0) + } + fn ride_chicken(&mut self, chicken: u32, rider: u32) { + if let Some(c) = self.chickens.iter_mut().find(|c| c.0 == chicken) { + c.2 = true; + } + self.rides.push((chicken, rider)); + } + fn game_time(&self) -> i64 { + self.time + } + fn halloween(&self) -> bool { + self.halloween + } + fn create(&mut self, kind: &str, _reason: Reason) -> Option { + if self.peaceful && !finalize::allowed_in_peaceful(kind) { + return None; + } + let t = Arc::new(self.types.types.get(kind)?.clone()); + let index = self.created; + self.created += 1; + let mut m = Mob::new(index as u32 + 1, t, Vec3::ZERO, 0.0); + m.random = LegacyRandom::new(self.eseed.wrapping_add(index as i64)); + Some(m) + } +} + +fn hex64(v: f64) -> String { + format!("{:x}", v.to_bits()) +} +fn hex32(v: f32) -> String { + format!("{:x}", v.to_bits()) +} +const HORSE: [&str; 7] = ["white", "creamy", "chestnut", "brown", "black", "gray", "dark_brown"]; +const MARKINGS: [&str; 5] = ["none", "white", "white_field", "white_dots", "black_dots"]; +const RABBITS: [&str; 6] = ["brown", "white", "black", "white_splotched", "gold", "salt"]; +const PARROTS: [&str; 5] = ["red_blue", "blue", "green", "yellow_blue", "gray"]; +const AXOLOTLS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"]; +const SALMON: [&str; 3] = ["small", "medium", "large"]; +const GENES: [&str; 7] = ["normal", "lazy", "worried", "playful", "brown", "weak", "aggressive"]; +const MEMORIES: [&str; 7] = [ + "long_jump_cooldown", + "ram_cooldown", + "attack_target_cooldown", + "hunted_recently", + "dig_cooldown", + "is_emerging", + "home", +]; + +fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) { + use Species as S; + let s = m.species(); + let named = |reg: &finalize::VariantRegistry, i: u8| { + format!("minecraft:{}", reg.names.get(i as usize).map_or("?", |n| n.as_str())) + }; + let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant)); + match s { + S::Pig => { + v.push(var); + v.push(named(®s.pig_sound, m.extra.sound_variant)); + } + S::Cow => { + v.push(var); + v.push(named(®s.cow_sound, m.extra.sound_variant)); + } + S::Mooshroom => v.push(if m.extra.variant == 0 { "red" } else { "brown" }.into()), + S::Chicken => { + v.push(var); + v.push(named(®s.chicken_sound, m.extra.sound_variant)); + v.push(format!("jockey={}", m.extra.jockey)); + } + S::Cat => { + v.push(var); + v.push(named(®s.cat_sound, m.extra.sound_variant)); + } + S::Wolf => { + v.push(var); + v.push(named(®s.wolf_sound, m.extra.sound_variant)); + } + S::Frog | S::ZombieNautilus => v.push(var), + S::Sheep => v.push(DYE_NAMES[m.extra.color as usize & 15].into()), + S::Horse => v.push(format!( + "{}/{}", + HORSE[m.extra.variant as usize % 7], + MARKINGS[m.extra.variant2 as usize % 5] + )), + S::Llama | S::TraderLlama => v.push(format!( + "{}/{}", + horizon_client::mobs::llama::VARIANTS[m.extra.variant as usize % 4], + m.extra.variant2 + )), + S::SkeletonHorse => v.push(format!("trap={}", m.extra.trap)), + S::Fox => v.push(if m.extra.variant == 1 { "snow" } else { "red" }.into()), + S::Rabbit => v.push(RABBITS[m.extra.variant as usize % 6].into()), + S::Parrot => v.push(PARROTS[m.extra.variant as usize % 5].into()), + S::Axolotl => v.push(AXOLOTLS[m.extra.variant as usize % 5].into()), + S::TropicalFish => { + let p = u32::from(m.extra.variant); + let pattern = if p < 6 { p << 8 } else { 1 | (p - 6) << 8 }; + let packed = (pattern & 0xFFFF) + | (u32::from(m.extra.variant2) & 0xFF) << 16 + | (u32::from(m.extra.variant3) & 0xFF) << 24; + v.push((packed as i32).to_string()); + } + S::Salmon => v.push(SALMON[m.extra.variant as usize % 3].into()), + S::Panda => v.push(format!( + "{}/{}", + GENES[m.extra.variant as usize % 7], + GENES[m.extra.variant2 as usize % 7] + )), + S::Goat => v.push(format!( + "scream={} horns={},{}", + m.extra.screaming, !m.extra.lost_horns[0], !m.extra.lost_horns[1] + )), + S::Slime | S::MagmaCube | S::SulfurCube => v.push(format!("size={}", m.extra.size.max(1))), + S::Villager => v.push(format!( + "minecraft:{}/minecraft:{}/{}", + VILLAGER_TYPES[m.extra.variant as usize % 7], + PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()], + m.extra.variant3.max(1) + )), + S::ZombieVillager => v.push(format!( + "minecraft:{}/{}", + VILLAGER_TYPES[m.extra.variant as usize % 7], + m.extra.variant3.max(1) + )), + S::Phantom => v.push(format!("size={}", m.extra.size)), + S::Turtle => v.push(format!( + "home={}", + m.extra.home.map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2])) + )), + S::Dolphin => v.push(format!("air={}", m.air)), + _ => {} + } + if matches!( + s, + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin + ) { + v.push(format!("doors={}", m.extra.can_break_doors)); + } + if horizon_client::mobs::raider::is_raider(s) { + let st = horizon_client::mobs::raider::state(m); + v.push(format!( + "leader={} patrolling={}", + st.is_some_and(|s| s.patrol_leader), + st.is_some_and(|s| s.patrolling) + )); + v.push(format!("raid={}", st.is_some_and(|s| s.can_join_raid))); + } + if s == S::Strider { + v.push(format!("saddled={}", m.extra.saddled)); + } +} + +fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { + let mut t = vec![m.kind.id.clone()]; + let vehicle = m + .extra + .mount + .and_then(|v| all.iter().position(|o| o.id == v)) + .map_or("-".to_owned(), |i| i.to_string()); + t.push(format!("veh={vehicle}")); + if finalize::ageable(m.species()) { + t.push(format!("age={}", m.extra.age)); + } else { + t.push(format!("baby={}", m.is_baby())); + } + t.push(format!("hp={}", hex32(m.health))); + t.push(format!("lh={}", m.extra.left_handed)); + t.push(format!("loot={}", m.extra.pick_up_loot)); + t.push(format!("persist={}", m.persistent)); + let mut eq = Vec::new(); + for (slot, name) in finalize::SLOT_NAMES.iter().enumerate() { + let Some(id) = finalize::item(m, slot) else { + continue; + }; + let mut text = id.to_string(); + let g = match slot { + 0 => Some(gear::MAIN), + 1 => Some(gear::OFF), + 2 => Some(gear::FEET), + 3 => Some(gear::LEGS), + 4 => Some(gear::CHEST), + 5 => Some(gear::HEAD), + _ => None, + }; + if let (Some(g), Some(levels)) = (g, gear::gear(m)) { + let mut list: Vec = levels.slots[g] + .iter() + .map(|(e, l)| format!("{e}={l}")) + .collect(); + list.sort(); + if !list.is_empty() { + let _ = write!(text, "[{}]", list.join(",")); + } + } + if slot == 5 && horizon_client::mobs::raider::is_captain(m) { + text.push_str("*4"); + } + eq.push(format!("{name}:{text}")); + } + t.push(format!("eq={}", if eq.is_empty() { "-".into() } else { eq.join(";") })); + let drops: Vec = finalize::SLOT_NAMES + .iter() + .enumerate() + .filter_map(|(i, name)| { + let d = finalize::stored_drop_chance(m, i); + (d != 0.085).then(|| format!("{name}:{}", hex32(d))) + }) + .collect(); + t.push(format!( + "drop={}", + if drops.is_empty() { "-".into() } else { drops.join(";") } + )); + let attrs: Vec = [ + Attr::MaxHealth, + Attr::MovementSpeed, + Attr::FollowRange, + Attr::AttackDamage, + Attr::KnockbackResistance, + Attr::SpawnReinforcements, + Attr::JumpStrength, + ] + .into_iter() + .filter(|a| finalize::default_value(m, *a).is_some()) + .map(|a| format!("{}:{}", a.name(), hex64(finalize::value(m, a)))) + .collect(); + t.push(format!("a={}", attrs.join(","))); + let mut fx: Vec = m + .extra + .effects + .iter() + .map(|(e, d, a)| format!("{e}:{a}:{d}")) + .collect(); + fx.sort(); + t.push(format!("fx={}", if fx.is_empty() { "-".into() } else { fx.join(",") })); + let mem: Vec = MEMORIES + .iter() + .filter_map(|name| { + let (_, value, ttl) = m.extra.memories.iter().find(|x| x.0 == *name)?; + let text = match *name { + "hunted_recently" => "true".to_owned(), + "dig_cooldown" | "is_emerging" => "INSTANCE".to_owned(), + "home" => m + .extra + .home + .map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2])), + _ => value.to_string(), + }; + Some(format!("{name}:{text}:{ttl}")) + }) + .collect(); + if !mem.is_empty() { + t.push(format!("mem={}", mem.join(","))); + } + let mut v = Vec::new(); + variant(m, regs, &mut v); + if !v.is_empty() { + t.push(format!("v={}", v.join(" ").replace(' ', "_"))); + } + t.join(" ") +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let halloween = args.get(4).is_some_and(|h| h == "true"); + let assets = Assets::load(root)?; + let facts = BlockFacts::load(root, assets.registry)?; + let mob_data = MobData::load(root, &facts); + let items = Items::tags_only(root)?; + let enchantments = Enchantments::load(root); + let types = MobTypes::load(root)?; + let registries = SpawnRegistries::load(root); + let camel = &types.types["minecraft:camel_husk"]; + let data = SpawnData { + registries: ®istries, + enchantments: &enchantments, + items: &items, + camel_husk_size: (camel.width as f32, camel.height as f32), + }; + let mut out = format!("halloween {halloween}\n"); + for line in input.lines().filter(|l| !l.trim().is_empty()) { + let mut c: HashMap<&str, &str> = HashMap::new(); + let mut name = ""; + for token in line.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let p: Vec = get("pos", "0,0,0") + .split(',') + .map(|x| x.parse().unwrap_or(0.0)) + .collect(); + let pos = Vec3::new(p[0], p[1], p[2]); + let block = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32]; + let base = match get("difficulty", "normal").as_str() { + "peaceful" => 0, + "easy" => 1, + "hard" => 3, + _ => 2, + }; + let phase: usize = get("phase", "0").parse().unwrap_or(0); + let time: i64 = get("time", "0").parse().unwrap_or(0); + let inhabited: i64 = get("inhabited", "0").parse().unwrap_or(0); + let difficulty = LocalDifficulty::new( + base, + time, + inhabited, + horizon_client::mobs::spawning::MOON_BRIGHTNESS[phase & 7], + ); + let mut level = Level { + types: &types, + data: &mob_data, + biome: get("biome", "minecraft:plains"), + structure: c.get("structure").map(|s| { + ( + (*s).to_owned(), + [ + block[0] - 8, + block[1] - 8, + block[2] - 8, + block[0] + 8, + block[1] + 8, + block[2] + 8, + ], + ) + }), + phase, + monsters: get("monsters", "1") != "0", + peaceful: base == 0, + time, + halloween, + roof: c + .get("roof") + .and_then(|r| r.parse::().ok()) + .map(|r| block[1] + r), + eseed: get("eseed", "0").parse().unwrap_or(0), + created: 0, + chickens: Vec::new(), + rides: Vec::new(), + }; + let mut all: Vec = Vec::new(); + let chickens: usize = get("chickens", "0").parse().unwrap_or(0); + for i in 0..chickens { + if let Some(mut chicken) = level.create("minecraft:chicken", Reason::Load) { + chicken.position = Vec3::new(pos.x + i as f64, pos.y, pos.z); + level.chickens.push((chicken.id, chicken.bounds(), false)); + all.push(chicken); + } + } + let kind = get("type", "minecraft:pig"); + let reason = Reason::parse(&get("reason", "NATURAL")).unwrap_or(Reason::Natural); + let pack: usize = get("pack", "1").parse().unwrap_or(1); + let mut random = LegacyRandom::new(get("seed", "0").parse().unwrap_or(0)); + let mut group = None; + for _ in 0..pack { + let Some(mut mob) = level.create(&kind, reason) else { + break; + }; + mob.position = pos; + mob.previous = pos; + let mut cx = Ctx { + level: &mut level, + random: &mut random, + difficulty, + data: &data, + created: Vec::new(), + }; + group = finalize::finalize(&mut cx, &mut mob, reason, group); + let created = std::mem::take(&mut cx.created); + all.push(mob); + all.extend(created); + } + for (chicken, rider) in std::mem::take(&mut level.rides) { + if let Some(c) = all.iter_mut().find(|m| m.id == chicken) { + c.extra.jockey = true; + c.extra.rider = Some(rider); + } + } + all.sort_by_key(|m| m.id); + let mut parts: Vec = all.iter().map(|m| describe(m, &all, ®istries)).collect(); + for m in &mut all { + parts.push(format!("rng {}", m.random.next_long())); + } + parts.push(format!("next {}", random.next_long())); + let _ = writeln!(out, "{name} {}", parts.join(" | ")); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index cd387342f..33b9905a0 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -144,6 +144,7 @@ pub(super) fn player_type(root: &Path) -> Option> { armor_toughness: 0.0, knockback_resistance: 0.0, jump_strength: 0.42, + attributes: Default::default(), gravity: 0.08, safe_fall_distance: 3.0, fall_damage_multiplier: 1.0, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5200e465b..41bb8f4be 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -22,6 +22,7 @@ pub mod drops; pub mod enderman; pub mod equine; pub mod farm; +pub mod finalize; pub mod gear; pub mod goals; pub mod golem; @@ -201,6 +202,8 @@ pub struct MobType { pub armor_toughness: f32, pub knockback_resistance: f64, pub jump_strength: f64, + /// Every default attribute value of the type (`entity-types.json`). + pub attributes: Arc>, pub gravity: f64, pub safe_fall_distance: f64, pub fall_damage_multiplier: f64, @@ -234,12 +237,35 @@ impl MobType { self.layers.get(key) } } +/// Each type's default attribute values, parsed exactly (serde_json's +/// default float parsing can miss the nearest double by one ulp). +fn exact_attributes(bytes: &[u8]) -> HashMap> { + use serde_json::value::RawValue; + type Raw = HashMap>; + let Ok(types) = serde_json::from_slice::(bytes) else { + return HashMap::new(); + }; + types + .into_iter() + .filter_map(|(id, t)| { + let t: Raw = serde_json::from_str(t.get()).ok()?; + let attrs: Raw = serde_json::from_str(t.get("attributes")?.get()).ok()?; + let values = attrs + .into_iter() + .filter_map(|(k, v)| v.get().trim().parse::().ok().map(|v| (k, v))) + .collect(); + Some((id, values)) + }) + .collect() +} pub struct MobTypes { pub types: HashMap, } impl MobTypes { pub fn load(root: &Path) -> crate::Result { - let types: Value = serde_json::from_slice(&fs::read(root.join("entity-types.json"))?)?; + let bytes = fs::read(root.join("entity-types.json"))?; + let types: Value = serde_json::from_slice(&bytes)?; + let exact = exact_attributes(&bytes); let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json"))?)?; let item_tags = crate::items::load_tags(root, "item").unwrap_or_default(); sulfur_cube::load_archetype_items(&item_tags); @@ -264,7 +290,8 @@ impl MobTypes { let Some(model) = models.get(&model_key) else { continue; }; - let attr = |k: &str| t["attributes"][format!("minecraft:{k}")].as_f64(); + let defaults = exact.get(&id).cloned().unwrap_or_default(); + let attr = |k: &str| defaults.get(&format!("minecraft:{k}")).copied(); let mut layers = HashMap::new(); if let Some(all) = models.as_object() { for prefix in def.layer_prefixes() { @@ -298,6 +325,7 @@ impl MobTypes { armor_toughness: attr("armor_toughness").unwrap_or(0.0) as f32, knockback_resistance: attr("knockback_resistance").unwrap_or(0.0), jump_strength: attr("jump_strength").unwrap_or(0.42), + attributes: Arc::new(defaults.clone()), gravity: attr("gravity").unwrap_or(0.08), safe_fall_distance: attr("safe_fall_distance").unwrap_or(3.0), fall_damage_multiplier: attr("fall_damage_multiplier").unwrap_or(1.0), @@ -457,6 +485,9 @@ pub struct Attrs { pub attack_damage: f32, pub max_health: f32, pub follow_range: f64, + pub knockback_resistance: f64, + pub spawn_reinforcements: f64, + pub jump_strength: f64, } /// Species-specific persistent state (variants, colours, taming, ageing...). #[derive(Clone, Debug, Default)] @@ -555,6 +586,24 @@ pub struct Extra { /// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set /// explicitly; None uses the defaults of `drops::drop_chance`. pub drop_chances: Option>, + /// `Mob.leftHanded`. + pub left_handed: bool, + /// The sound variant: index in the species' `*_sound_variant` registry. + pub sound_variant: u8, + /// `Zombie.canBreakDoors`. + pub can_break_doors: bool, + /// A goat's `IsScreamingGoat` and the horns it lost (left, right). + pub screaming: bool, + pub lost_horns: [bool; 2], + /// Attribute bases and permanent modifiers set by `finalizeSpawn`. + pub attributes: Option>, + /// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry). + pub memories: Vec<(&'static str, i64, i64)>, + /// A camel's `LAST_POSE_CHANGE_TICK`. + pub pose_change_tick: i64, + /// The school leader a fish follows, and a tropical fish that swims alone. + pub leader: Option, + pub lone: bool, } #[derive(Clone, Debug)] pub struct Mob { @@ -1066,6 +1115,13 @@ impl Mob { attack_damage: kind.attack_damage, max_health: kind.max_health, follow_range: kind.follow_range, + knockback_resistance: kind.knockback_resistance, + spawn_reinforcements: kind + .attributes + .get("minecraft:spawn_reinforcements") + .copied() + .unwrap_or(0.0), + jump_strength: kind.jump_strength, }, kind, }; diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 667802b26..cdcd13000 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -445,35 +445,35 @@ impl Goal for PufferfishPuff { } } /// finalizeSpawn variants (tropical fish patterns and colours). +/// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour). +pub const COMMON_TROPICAL: [(u8, u8, u8); 22] = [ + (7, 1, 7), + (6, 7, 7), + (6, 7, 11), + (11, 0, 7), + (1, 11, 7), + (0, 1, 0), + (5, 6, 3), + (9, 10, 4), + (11, 0, 14), + (5, 0, 4), + (8, 0, 7), + (11, 0, 1), + (3, 9, 6), + (4, 5, 3), + (10, 14, 0), + (2, 7, 14), + (9, 14, 0), + (6, 0, 4), + (0, 14, 0), + (1, 7, 0), + (3, 9, 4), + (6, 4, 4), +]; pub fn finalize(m: &mut Mob) { if m.species() == Species::TropicalFish { - // TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour). - const COMMON: [(u8, u8, u8); 22] = [ - (7, 1, 7), - (6, 7, 7), - (6, 7, 11), - (11, 0, 7), - (1, 11, 7), - (0, 1, 0), - (5, 6, 3), - (9, 10, 4), - (11, 0, 14), - (5, 0, 4), - (8, 0, 7), - (11, 0, 1), - (3, 9, 6), - (4, 5, 3), - (10, 14, 0), - (2, 7, 14), - (9, 14, 0), - (6, 0, 4), - (0, 14, 0), - (1, 7, 0), - (3, 9, 4), - (6, 4, 4), - ]; let (p, b, c) = if m.random.next_float() < 0.9 { - COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize] + COMMON_TROPICAL[m.random.next_int_bound(COMMON_TROPICAL.len() as i32).unwrap_or(0) as usize] } else { ( m.random.next_int_bound(12).unwrap_or(0) as u8, diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs new file mode 100644 index 000000000..8e5992260 --- /dev/null +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -0,0 +1,1972 @@ +//! `Mob.finalizeSpawn` and its overrides, for every spawn path (natural +//! spawning, chunk generation, spawners, trial spawners, spawn eggs, +//! commands, structures, patrols, raids, jockeys, conversions...). +//! +//! Every draw vanilla takes from `level.getRandom()` comes from the random +//! the caller passes (the level's random for a running level, the region's +//! for chunk generation); the few that come from the entity's own random +//! (`Zombie.handleAttributes`, `Piglin.createSpawnWeapon`, salmon sizes) come +//! from `Mob::random`. The order of the draws follows vanilla's class chain: +//! each species runs its own part before or after its superclass as vanilla +//! does. Jockeys a mob brings (`EntityType.create` inside finalizeSpawn) are +//! made through [`FinalizeLevel::create`], finalized with the same random and +//! returned in [`Ctx::created`]. +//! +//! Variant state kept in [`super::Extra`]: `variant` is the registry or enum +//! index of the species' variant (cat, wolf, frog, farm animals by climate, +//! zombie nautilus, horse, llama, fox, rabbit, parrot, axolotl, salmon, +//! tropical fish pattern, panda main gene, villager type), `variant2` the +//! second part (horse markings, llama strength, panda hidden gene, tropical +//! fish base colour), `variant3` the tropical fish pattern colour, and +//! `sound_variant` the index in the species' sound variant registry. +use super::{Mob, Species, farm::Climate, gear, spawning::LocalDifficulty}; +use crate::{enchant::Enchantments, items::Items}; +use horizon_core::{geometry::Aabb, random::RandomSource}; +use serde_json::Value; +use std::{fs, path::Path, sync::Arc}; + +/// `EntitySpawnReason`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Reason { + Natural, + ChunkGeneration, + Spawner, + Structure, + Breeding, + MobSummoned, + Jockey, + Event, + Conversion, + Reinforcement, + Triggered, + Bucket, + SpawnItemUse, + Command, + Dispenser, + Patrol, + TrialSpawner, + Load, + DimensionTravel, +} +impl Reason { + pub const ALL: [Self; 19] = [ + Self::Natural, + Self::ChunkGeneration, + Self::Spawner, + Self::Structure, + Self::Breeding, + Self::MobSummoned, + Self::Jockey, + Self::Event, + Self::Conversion, + Self::Reinforcement, + Self::Triggered, + Self::Bucket, + Self::SpawnItemUse, + Self::Command, + Self::Dispenser, + Self::Patrol, + Self::TrialSpawner, + Self::Load, + Self::DimensionTravel, + ]; + pub fn name(self) -> &'static str { + match self { + Self::Natural => "NATURAL", + Self::ChunkGeneration => "CHUNK_GENERATION", + Self::Spawner => "SPAWNER", + Self::Structure => "STRUCTURE", + Self::Breeding => "BREEDING", + Self::MobSummoned => "MOB_SUMMONED", + Self::Jockey => "JOCKEY", + Self::Event => "EVENT", + Self::Conversion => "CONVERSION", + Self::Reinforcement => "REINFORCEMENT", + Self::Triggered => "TRIGGERED", + Self::Bucket => "BUCKET", + Self::SpawnItemUse => "SPAWN_ITEM_USE", + Self::Command => "COMMAND", + Self::Dispenser => "DISPENSER", + Self::Patrol => "PATROL", + Self::TrialSpawner => "TRIAL_SPAWNER", + Self::Load => "LOAD", + Self::DimensionTravel => "DIMENSION_TRAVEL", + } + } + pub fn parse(name: &str) -> Option { + Self::ALL.into_iter().find(|r| r.name() == name) + } +} + +/// The level as finalizeSpawn reads it. +pub trait FinalizeLevel { + /// The biome id at a block. + fn biome(&self, pos: [i32; 3]) -> String; + /// The biome at a block is in a biome tag (`minecraft:...`). + fn biome_tag(&self, tag: &str, pos: [i32; 3]) -> bool; + /// The structures with a piece at a block. + fn structures_with_piece_at(&self, pos: [i32; 3]) -> Vec; + /// `EnvironmentAttributes.MOON_PHASE` at a block (0 full moon to 7). + fn moon_phase(&self, pos: [i32; 3]) -> usize; + /// `ServerLevel.isSpawningMonsters`. + fn spawning_monsters(&self) -> bool; + /// `Level.noCollision(AABB)`. + fn no_collision(&self, bounds: Aabb) -> bool; + /// The first chicken (in entity order) whose box meets `bounds` and + /// that is not being ridden (`Zombie.finalizeSpawn`'s chicken jockeys). + fn free_chicken(&self, bounds: Aabb) -> Option; + /// A chicken found by `free_chicken` carries the zombie `rider` + /// (`setChickenJockey(true)` and `startRiding`). + fn ride_chicken(&mut self, chicken: u32, rider: u32); + /// `getGameTime`. + fn game_time(&self) -> i64; + /// `SpecialDates.isHalloween`. + fn halloween(&self) -> bool; + /// `EntityType.create(level, reason)`: a new mob of a type (an id and an + /// own random from the caller), or None where it cannot exist (monsters + /// in peaceful). + fn create(&mut self, kind: &str, reason: Reason) -> Option; +} + +/// `AgeableMob.AgeableMobGroupData`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ageable { + pub size: i32, + pub should_spawn_baby: bool, + pub baby_chance: f32, +} +impl Ageable { + pub fn new(should_spawn_baby: bool, baby_chance: f32) -> Self { + Self { + size: 0, + should_spawn_baby, + baby_chance, + } + } + /// `AgeableMobGroupData(boolean)`. + pub fn babies(should_spawn_baby: bool) -> Self { + Self::new(should_spawn_baby, 0.05) + } + /// `AgeableMobGroupData(float)`. + pub fn chance(baby_chance: f32) -> Self { + Self::new(true, baby_chance) + } +} +/// `SpawnGroupData`: what the mobs of a pack share. +#[derive(Clone, Debug, PartialEq)] +pub enum Group { + Ageable(Ageable), + /// `Zombie.ZombieGroupData`, and `Husk.HuskGroupData` with `tried_camel`. + Zombie { + baby: bool, + jockey: bool, + husk: Option, + }, + /// `Spider.SpiderEffectsGroupData`. + Spider(Option<&'static str>), + Horse(Ageable, u8), + Llama(Ageable, u8), + Fox(Ageable, u8), + Rabbit(Ageable, u8), + Axolotl(Ageable, [u8; 2]), + Wolf(Ageable, u8), + /// `AbstractSchoolingFish.SchoolSpawnGroupData` (the leader's id), and + /// `TropicalFishGroupData` with its variant. + School(u32, Option<(u8, u8, u8)>), +} +impl Group { + fn ageable(&mut self) -> Option<&mut Ageable> { + match self { + Self::Ageable(a) + | Self::Horse(a, _) + | Self::Llama(a, _) + | Self::Fox(a, _) + | Self::Rabbit(a, _) + | Self::Axolotl(a, _) + | Self::Wolf(a, _) => Some(a), + _ => None, + } + } +} + +/// A variant registry entry's spawn conditions (`SpawnPrioritySelectors`). +#[derive(Clone, Debug)] +enum Condition { + Biome(Vec), + Structure(Vec), + Moon(Option, Option), +} +#[derive(Clone, Debug)] +pub struct VariantRegistry { + /// Entry names in registry order (sorted by id). + pub names: Vec, + selectors: Vec<(usize, Option, i32)>, +} +impl VariantRegistry { + fn load(dir: &Path, structure_tags: &dyn Fn(&str) -> Vec) -> Self { + let mut names: Vec = fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + e.file_name() + .to_str() + .and_then(|n| n.strip_suffix(".json")) + .map(str::to_owned) + }) + .collect(); + names.sort(); + let mut selectors = Vec::new(); + for (i, name) in names.iter().enumerate() { + let Ok(bytes) = fs::read(dir.join(format!("{name}.json"))) else { + continue; + }; + let Ok(v) = serde_json::from_slice::(&bytes) else { + continue; + }; + for s in v["spawn_conditions"].as_array().into_iter().flatten() { + let priority = s["priority"].as_i64().unwrap_or(0) as i32; + let c = &s["condition"]; + let list = |v: &Value| -> Vec { + match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a + .iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect(), + _ => Vec::new(), + } + }; + let condition = match c["type"].as_str() { + Some("minecraft:biome") => Some(Condition::Biome(list(&c["biomes"]))), + Some("minecraft:structure") => Some(Condition::Structure( + list(&c["structures"]) + .into_iter() + .flat_map(|s| match s.strip_prefix('#') { + Some(tag) => structure_tags(tag), + None => vec![s], + }) + .collect(), + )), + Some("minecraft:moon_brightness") => { + let r = &c["range"]; + Some(match r.as_f64() { + Some(x) => Condition::Moon(Some(x), Some(x)), + None => Condition::Moon(r["min"].as_f64(), r["max"].as_f64()), + }) + } + _ => None, + }; + selectors.push((i, condition, priority)); + } + } + Self { names, selectors } + } + pub fn index(&self, name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + self.names.iter().position(|n| n == name) + } + /// `VariantUtils.selectVariantToSpawn`: the entries of the highest + /// priority whose condition holds, one of them at random. + pub fn select( + &self, + level: &L, + pos: [i32; 3], + random: &mut impl RandomSource, + ) -> Option { + let mut unpacked: Vec<&(usize, Option, i32)> = self.selectors.iter().collect(); + unpacked.sort_by_key(|s| std::cmp::Reverse(s.2)); + let mut highest = i32::MIN; + let mut selected = Vec::new(); + for (entry, condition, priority) in unpacked { + if *priority < highest { + continue; + } + let ok = match condition { + None => true, + Some(Condition::Biome(list)) => list.iter().any(|b| match b.strip_prefix('#') { + Some(tag) => level.biome_tag(tag, pos), + None => level.biome(pos) == *b, + }), + Some(Condition::Structure(list)) => { + let here = level.structures_with_piece_at(pos); + here.iter().any(|s| list.contains(s)) + } + Some(Condition::Moon(min, max)) => { + let b = f64::from(super::spawning::MOON_BRIGHTNESS[level.moon_phase(pos) & 7]); + min.is_none_or(|m| b >= m) && max.is_none_or(|m| b <= m) + } + }; + if ok { + highest = *priority; + selected.push(*entry); + } + } + if selected.is_empty() { + return None; + } + Some(selected[random.next_int_bound(selected.len() as i32).unwrap_or(0) as usize]) + } + /// `Registry.getRandom`: any entry. + pub fn random(&self, random: &mut impl RandomSource) -> usize { + if self.names.is_empty() { + return 0; + } + random.next_int_bound(self.names.len() as i32).unwrap_or(0) as usize + } +} + +/// The registries finalizeSpawn reads. +pub struct SpawnRegistries { + pub pig: VariantRegistry, + pub cow: VariantRegistry, + pub chicken: VariantRegistry, + pub cat: VariantRegistry, + pub wolf: VariantRegistry, + pub frog: VariantRegistry, + pub zombie_nautilus: VariantRegistry, + pub pig_sound: VariantRegistry, + pub cow_sound: VariantRegistry, + pub chicken_sound: VariantRegistry, + pub cat_sound: VariantRegistry, + pub wolf_sound: VariantRegistry, +} +impl SpawnRegistries { + /// Loads the variant registries from a resources directory + /// (`data/minecraft//`). + pub fn load(root: &Path) -> Self { + let data = root.join("data/minecraft"); + let structure_tag = |tag: &str| -> Vec { + let path = tag.strip_prefix("minecraft:").unwrap_or(tag); + let file = data.join(format!("tags/worldgen/structure/{path}.json")); + let Ok(bytes) = fs::read(file) else { + return Vec::new(); + }; + serde_json::from_slice::(&bytes) + .ok() + .and_then(|v| v["values"].as_array().cloned()) + .into_iter() + .flatten() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect() + }; + let r = |name: &str| VariantRegistry::load(&data.join(name), &structure_tag); + Self { + pig: r("pig_variant"), + cow: r("cow_variant"), + chicken: r("chicken_variant"), + cat: r("cat_variant"), + wolf: r("wolf_variant"), + frog: r("frog_variant"), + zombie_nautilus: r("zombie_nautilus_variant"), + pig_sound: r("pig_sound_variant"), + cow_sound: r("cow_sound_variant"), + chicken_sound: r("chicken_sound_variant"), + cat_sound: r("cat_sound_variant"), + wolf_sound: r("wolf_sound_variant"), + } + } +} + +/// What finalizeSpawn needs besides the level: registries, enchantments. +pub struct SpawnData<'a> { + pub registries: &'a SpawnRegistries, + pub enchantments: &'a Enchantments, + pub items: &'a Items, + /// `EntityTypes.CAMEL_HUSK` dimensions (width, height). + pub camel_husk_size: (f32, f32), +} + +/// A finalizeSpawn call and the entities it made. +pub struct Ctx<'a, L: FinalizeLevel + ?Sized, R: RandomSource> { + pub level: &'a mut L, + pub random: &'a mut R, + pub difficulty: LocalDifficulty, + pub data: &'a SpawnData<'a>, + /// Jockeys and mounts made along the way, finalized, with their riding + /// links set (`Extra::mount` / `Extra::rider`). + pub created: Vec, +} + +// ---- attributes ----------------------------------------------------------- + +/// The attributes finalizeSpawn changes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Attr { + MaxHealth, + MovementSpeed, + FollowRange, + AttackDamage, + KnockbackResistance, + SpawnReinforcements, + JumpStrength, + Armor, +} +impl Attr { + pub const ALL: [Self; 8] = [ + Self::MaxHealth, + Self::MovementSpeed, + Self::FollowRange, + Self::AttackDamage, + Self::KnockbackResistance, + Self::SpawnReinforcements, + Self::JumpStrength, + Self::Armor, + ]; + pub fn name(self) -> &'static str { + match self { + Self::MaxHealth => "max_health", + Self::MovementSpeed => "movement_speed", + Self::FollowRange => "follow_range", + Self::AttackDamage => "attack_damage", + Self::KnockbackResistance => "knockback_resistance", + Self::SpawnReinforcements => "spawn_reinforcements", + Self::JumpStrength => "jump_strength", + Self::Armor => "armor", + } + } + /// `RangedAttribute` bounds. + fn range(self) -> (f64, f64) { + match self { + Self::MaxHealth => (1.0, 1024.0), + Self::MovementSpeed => (0.0, 1024.0), + Self::FollowRange => (0.0, 2048.0), + Self::AttackDamage => (0.0, 2048.0), + Self::KnockbackResistance | Self::SpawnReinforcements => (0.0, 1.0), + Self::JumpStrength => (0.0, 32.0), + Self::Armor => (0.0, 30.0), + } + } +} +/// `AttributeModifier.Operation`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + AddValue, + AddMultipliedBase, + AddMultipliedTotal, +} +/// A permanent attribute modifier (`AttributeModifier`). +#[derive(Clone, Debug, PartialEq)] +pub struct Modifier { + pub attr: Attr, + pub id: &'static str, + pub amount: f64, + pub op: Op, +} +/// Attribute base values that differ from the type's and the permanent +/// modifiers finalizeSpawn added, in the order vanilla adds them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Attributes { + pub bases: Vec<(Attr, f64)>, + pub modifiers: Vec, +} +/// The type's default value of an attribute, if the mob has it. +pub fn default_value(m: &Mob, a: Attr) -> Option { + m.kind + .attributes + .get(&format!("minecraft:{}", a.name())) + .copied() +} +pub fn base_value(m: &Mob, a: Attr) -> f64 { + m.extra + .attributes + .as_ref() + .and_then(|s| s.bases.iter().find(|(x, _)| *x == a).map(|(_, v)| *v)) + .or_else(|| default_value(m, a)) + .unwrap_or(0.0) +} +/// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`). +fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { + if a != Attr::MovementSpeed || !m.is_baby() { + return None; + } + match m.species() { + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin => Some((0.5, Op::AddMultipliedBase)), + Species::Piglin => Some((f64::from(0.2f32), Op::AddMultipliedBase)), + _ => None, + } +} +/// `AttributeInstance.getValue`: the base, then the modifiers by operation. +pub fn value(m: &Mob, a: Attr) -> f64 { + compute(m, a, true) +} +fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 { + let mut base = base_value(m, a); + let empty = Vec::new(); + let mods = m.extra.attributes.as_ref().map_or(&empty, |s| &s.modifiers); + let mut ops: Vec<(f64, Op)> = mods + .iter() + .filter(|x| x.attr == a) + .map(|x| (x.amount, x.op)) + .collect(); + if with_transient && let Some(t) = transient(m, a) { + ops.push(t); + } + for (amount, op) in &ops { + if *op == Op::AddValue { + base += amount; + } + } + let mut result = base; + for (amount, op) in &ops { + if *op == Op::AddMultipliedBase { + result += base * amount; + } + } + for (amount, op) in &ops { + if *op == Op::AddMultipliedTotal { + result *= 1.0 + amount; + } + } + let (lo, hi) = a.range(); + if result.is_nan() { lo } else { result.clamp(lo, hi) } +} +/// Copies the attribute values into the fields the game reads. +fn refresh(m: &mut Mob, a: Attr) { + match a { + Attr::MaxHealth => m.attrs.max_health = value(m, a) as f32, + Attr::MovementSpeed => m.attrs.speed = base_with_modifiers(m, a), + Attr::FollowRange => m.attrs.follow_range = value(m, a), + Attr::AttackDamage => m.attrs.attack_damage = value(m, a) as f32, + Attr::KnockbackResistance => m.attrs.knockback_resistance = value(m, a), + Attr::SpawnReinforcements => m.attrs.spawn_reinforcements = value(m, a), + Attr::JumpStrength => m.attrs.jump_strength = value(m, a), + Attr::Armor => {} + } +} +/// The value without the transient baby modifier (`speed_bonus` applies +/// that one to movement speed). +fn base_with_modifiers(m: &Mob, a: Attr) -> f64 { + compute(m, a, false) +} +/// `AttributeInstance.setBaseValue`. +pub fn set_base(m: &mut Mob, a: Attr, v: f64) { + let s = m.extra.attributes.get_or_insert_with(Box::default); + match s.bases.iter_mut().find(|(x, _)| *x == a) { + Some(b) => b.1 = v, + None => s.bases.push((a, v)), + } + refresh(m, a); +} +pub fn has_modifier(m: &Mob, a: Attr, id: &str) -> bool { + m.extra + .attributes + .as_ref() + .is_some_and(|s| s.modifiers.iter().any(|x| x.attr == a && x.id == id)) +} +/// `addOrReplacePermanentModifier`. +pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) { + let s = m.extra.attributes.get_or_insert_with(Box::default); + let new = Modifier { + attr: a, + id, + amount, + op, + }; + match s.modifiers.iter_mut().find(|x| x.attr == a && x.id == id) { + Some(x) => *x = new, + None => s.modifiers.push(new), + } + refresh(m, a); +} +pub fn max_health(m: &Mob) -> f32 { + value(m, Attr::MaxHealth) as f32 +} + +// ---- species facts -------------------------------------------------------- + +/// `AgeableMob` subclasses. +pub fn ageable(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Pig + | S::Cow + | S::Mooshroom + | S::Sheep + | S::Chicken + | S::Rabbit + | S::Horse + | S::Donkey + | S::Mule + | S::Llama + | S::TraderLlama + | S::Goat + | S::Panda + | S::PolarBear + | S::Fox + | S::Wolf + | S::Cat + | S::Ocelot + | S::Parrot + | S::Bee + | S::Turtle + | S::Armadillo + | S::Frog + | S::Axolotl + | S::Squid + | S::GlowSquid + | S::Dolphin + | S::Villager + | S::WanderingTrader + | S::Slime + | S::MagmaCube + | S::SulfurCube + | S::Hoglin + | S::Strider + | S::Camel + | S::CamelHusk + | S::Sniffer + | S::HappyGhast + | S::Nautilus + | S::ZombieNautilus + | S::ZombieHorse + | S::SkeletonHorse + ) +} +fn zombie(s: Species) -> bool { + matches!( + s, + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + ) +} +fn skeleton(s: Species) -> bool { + matches!( + s, + Species::Skeleton + | Species::Stray + | Species::Bogged + | Species::Parched + | Species::WitherSkeleton + ) +} +fn raider(s: Species) -> bool { + super::raider::is_raider(s) +} +/// `EntityType.isAllowedInPeaceful`: the types built with `notInPeaceful`. +pub fn allowed_in_peaceful(kind: &str) -> bool { + !matches!( + kind.strip_prefix("minecraft:").unwrap_or(kind), + "blaze" + | "bogged" + | "breeze" + | "cave_spider" + | "creaking" + | "creeper" + | "drowned" + | "elder_guardian" + | "enderman" + | "endermite" + | "evoker" + | "ghast" + | "giant" + | "guardian" + | "hoglin" + | "husk" + | "illusioner" + | "magma_cube" + | "parched" + | "phantom" + | "piglin_brute" + | "pillager" + | "ravager" + | "silverfish" + | "skeleton" + | "slime" + | "spider" + | "stray" + | "vex" + | "vindicator" + | "warden" + | "witch" + | "wither" + | "wither_skeleton" + | "zoglin" + | "zombie" + | "zombie_villager" + | "zombified_piglin" + ) +} +/// `getBabyStartAge`. +fn baby_start_age(s: Species) -> i32 { + if s == Species::Sniffer { + super::sniffer::BABY_START_AGE + } else { + -24000 + } +} +/// The age a non-ageable baby (zombies, piglins, zoglins) keeps. +pub const NON_AGEABLE_BABY: i32 = i32::MIN / 2; + +/// `AgeableMob.setAge`, with each class's `ageBoundaryReached`. +pub fn set_age(m: &mut Mob, age: i32) { + let old = m.extra.age; + m.extra.age = age; + if (old < 0) != (age < 0) { + age_boundary_reached(m); + } +} +fn age_boundary_reached(m: &mut Mob) { + let baby = m.is_baby(); + match m.species() { + Species::Goat => set_base(m, Attr::AttackDamage, if baby { 1.0 } else { 2.0 }), + Species::Hoglin => set_base(m, Attr::AttackDamage, if baby { 0.5 } else { 6.0 }), + Species::SulfurCube if !baby => super::sulfur_cube::set_size(m, 2, true), + _ => {} + } +} +/// `setBaby`: AgeableMob through its age, zombies, piglins and zoglins. +pub fn set_baby(m: &mut Mob, baby: bool) { + let s = m.species(); + if ageable(s) { + set_age(m, if baby { baby_start_age(s) } else { 0 }); + return; + } + match s { + _ if zombie(s) || s == Species::Piglin => { + m.extra.age = if baby { NON_AGEABLE_BABY } else { 0 }; + } + Species::Zoglin => { + m.extra.age = if baby { NON_AGEABLE_BABY } else { 0 }; + if baby { + set_base(m, Attr::AttackDamage, 0.5); + } + } + _ => {} + } +} + +// ---- equipment ------------------------------------------------------------ + +/// `EquipmentSlot` names (the `drops::SLOTS` order). +pub const SLOT_NAMES: [&str; 8] = super::drops::SLOTS; +const MAINHAND: usize = 0; +const OFFHAND: usize = 1; +const FEET: usize = 2; +const LEGS: usize = 3; +const CHEST: usize = 4; +const HEAD: usize = 5; +const SADDLE: usize = 7; +/// The `gear` slot of an `EquipmentSlot`. +fn gear_slot(slot: usize) -> usize { + match slot { + MAINHAND => gear::MAIN, + OFFHAND => gear::OFF, + FEET => gear::FEET, + LEGS => gear::LEGS, + CHEST => gear::CHEST, + _ => gear::HEAD, + } +} +pub fn item(m: &Mob, slot: usize) -> Option> { + match slot { + MAINHAND => m.extra.main_hand.clone(), + OFFHAND => m.extra.off_hand.clone(), + FEET => m.extra.feet.clone(), + LEGS => m.extra.legs.clone(), + CHEST => m.extra.chest.clone(), + HEAD => m.extra.head.clone(), + SADDLE => m.extra.saddled.then(|| Arc::from("minecraft:saddle")), + _ => None, + } +} +/// `setItemSlot` with a fresh stack (enchantments cleared). +pub fn set_item(m: &mut Mob, slot: usize, id: &str) { + let v = Some(Arc::from(id)); + match slot { + MAINHAND => m.extra.main_hand = v, + OFFHAND => m.extra.off_hand = v, + FEET => m.extra.feet = v, + LEGS => m.extra.legs = v, + CHEST => m.extra.chest = v, + HEAD => m.extra.head = v, + SADDLE => { + m.extra.saddled = true; + m.extra.saddle_stack = None; + return; + } + _ => return, + } + gear::set(m, gear_slot(slot), Vec::new()); +} +/// `Mob.setDropChance`. +pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) { + let c = m + .extra + .drop_chances + .get_or_insert_with(|| Box::new([super::drops::DEFAULT_DROP_CHANCE; 8])); + c[slot] = chance; +} +/// The drop chance stored for a slot (`DropChances.byEquipment`). +pub fn stored_drop_chance(m: &Mob, slot: usize) -> f32 { + m.extra + .drop_chances + .as_ref() + .map_or(super::drops::DEFAULT_DROP_CHANCE, |c| c[slot]) +} + +impl Ctx<'_, L, R> { + fn float(&mut self) -> f32 { + self.random.next_float() + } + fn int(&mut self, bound: i32) -> i32 { + self.random.next_int_bound(bound).unwrap_or(0) + } + fn special(&self) -> f32 { + self.difficulty.special() + } + /// `UniformInt.sample`. + fn uniform(&mut self, min: i32, max: i32) -> i32 { + self.random + .next_int_between_inclusive(min, max) + .unwrap_or(min) + } + + // ---- Mob ---------------------------------------------------------- + + /// `Mob.finalizeSpawn`: the follow range spawn bonus and left-handedness. + fn mob(&mut self, m: &mut Mob, g: Option) -> Option { + if !has_modifier(m, Attr::FollowRange, "minecraft:random_spawn_bonus") { + let bonus = self.random.triangle(0.0, 0.114_850_000_000_000_01); + add_modifier( + m, + Attr::FollowRange, + "minecraft:random_spawn_bonus", + bonus, + Op::AddMultipliedBase, + ); + } + m.extra.left_handed = self.float() < 0.05; + g + } + /// `AgeableMob.finalizeSpawn`. + fn ageable(&mut self, m: &mut Mob, g: Option) -> Option { + let mut g = g.unwrap_or(Group::Ageable(Ageable::babies(true))); + if let Some(a) = g.ageable() { + let (should, size, chance) = (a.should_spawn_baby, a.size, a.baby_chance); + if should && size > 0 && self.float() <= chance { + let start = baby_start_age(m.species()); + set_age(m, start); + } + if let Some(a) = g.ageable() { + a.size += 1; + } + } + self.mob(m, Some(g)) + } + /// `Mob.populateDefaultEquipmentSlots`: a set of armour from the head + /// down, of one material. + fn armor(&mut self, m: &mut Mob) { + if self.float() >= 0.15 * self.special() { + return; + } + let mut kind = self.int(3); + for _ in 1..=3 { + if self.float() < 0.1087 { + kind += 1; + } + } + let partial = if self.difficulty.hard { 0.1 } else { 0.25 }; + const MATERIAL: [&str; 6] = ["leather", "copper", "golden", "chainmail", "iron", "diamond"]; + let mut first = true; + // EQUIPMENT_POPULATION_ORDER: head, chest, legs, feet. + for (slot, piece) in [ + (HEAD, "helmet"), + (CHEST, "chestplate"), + (LEGS, "leggings"), + (FEET, "boots"), + ] { + if !first && self.float() < partial { + break; + } + first = false; + if item(m, slot).is_none() + && let Some(material) = MATERIAL.get(kind as usize) + { + set_item(m, slot, &format!("minecraft:{material}_{piece}")); + } + } + } + /// `populateDefaultEquipmentSlots` of each class. + fn populate(&mut self, m: &mut Mob) { + use Species as S; + match m.species() { + S::Zombie | S::Husk | S::ZombieVillager => { + self.armor(m); + let chance = if self.difficulty.hard { 0.05 } else { 0.01 }; + if self.float() < chance { + let weapon = match self.int(6) { + 0 => "minecraft:iron_sword", + 1 => "minecraft:iron_spear", + _ => "minecraft:iron_shovel", + }; + set_item(m, MAINHAND, weapon); + } + } + S::Drowned => { + if f64::from(self.float()) > 0.9 { + let weapon = if self.int(16) < 10 { + "minecraft:trident" + } else { + "minecraft:fishing_rod" + }; + set_item(m, MAINHAND, weapon); + } + } + S::ZombifiedPiglin => { + let weapon = if self.int(20) == 0 { + "minecraft:golden_spear" + } else { + "minecraft:golden_sword" + }; + set_item(m, MAINHAND, weapon); + } + S::WitherSkeleton => set_item(m, MAINHAND, "minecraft:stone_sword"), + s if skeleton(s) => { + self.armor(m); + set_item(m, MAINHAND, "minecraft:bow"); + } + S::Pillager => set_item(m, MAINHAND, "minecraft:crossbow"), + S::Vindicator => { + if super::raider::state(m).is_none_or(|s| s.raid_id.is_none()) { + set_item(m, MAINHAND, "minecraft:iron_axe"); + } + } + S::Piglin => { + if !m.is_baby() { + for (slot, piece) in [ + (HEAD, "helmet"), + (CHEST, "chestplate"), + (LEGS, "leggings"), + (FEET, "boots"), + ] { + if self.float() < 0.1 { + set_item(m, slot, &format!("minecraft:golden_{piece}")); + } + } + } + } + S::PiglinBrute => set_item(m, MAINHAND, "minecraft:golden_axe"), + S::Vex => { + set_item(m, MAINHAND, "minecraft:iron_sword"); + set_drop_chance(m, MAINHAND, 0.0); + } + S::Fox => { + if self.float() < 0.2 { + let odds = self.float(); + let held = if odds < 0.05 { + "minecraft:emerald" + } else if odds < 0.2 { + "minecraft:egg" + } else if odds < 0.4 { + if self.random.next_boolean() { + "minecraft:rabbit_foot" + } else { + "minecraft:rabbit_hide" + } + } else if odds < 0.6 { + "minecraft:wheat" + } else if odds < 0.8 { + "minecraft:leather" + } else { + "minecraft:feather" + }; + set_item(m, MAINHAND, held); + } + } + _ => self.armor(m), + } + } + /// `Mob.populateDefaultEquipmentEnchantments`: the weapon one time in + /// four and each piece of armour one time in two, scaled by the local + /// difficulty, through the `mob_spawn_equipment` provider. + fn enchant(&mut self, m: &mut Mob) { + if m.species() == Species::WitherSkeleton { + return; + } + self.enchant_slot(m, MAINHAND, 0.25); + // Pillager.enchantSpawnedWeapon: one crossbow in 300 pierces + // (`pillager_spawn_crossbow`). + if m.species() == Species::Pillager + && self.int(300) == 0 + && item(m, MAINHAND).as_deref() == Some("minecraft:crossbow") + { + gear::upgrade(m, gear::MAIN, "minecraft:piercing", 1); + } + // EquipmentSlot.VALUES order: feet, legs, chest, head. + for slot in [FEET, LEGS, CHEST, HEAD] { + self.enchant_slot(m, slot, 0.5); + } + } + fn enchant_slot(&mut self, m: &mut Mob, slot: usize, chance: f32) { + let Some(id) = item(m, slot) else { return }; + if self.float() >= chance * self.special() { + return; + } + self.enchant_by_cost(m, slot, &id); + } + /// `EnchantmentsByCostWithDifficulty.enchant` (`mob_spawn_equipment`: + /// cost 5 to 5 + 17 x the special multiplier, `#on_mob_spawn_equipment`). + fn enchant_by_cost(&mut self, m: &mut Mob, slot: usize, id: &str) { + let top = 5 + (self.special() * 17.0) as i32; + let cost = self.random.next_int_between_inclusive(5, top).unwrap_or(5); + let e = self.data.enchantments; + let pool = e.tag("minecraft:on_mob_spawn_equipment"); + let picked = e.select(self.data.items, self.random, id, cost, pool); + for (enchantment, level) in picked { + gear::upgrade(m, gear_slot(slot), &enchantment, level); + } + } + fn halloween(&mut self, m: &mut Mob) { + if m.extra.head.is_none() && self.level.halloween() && self.float() < 0.25 { + let head = if self.float() < 0.1 { + "minecraft:jack_o_lantern" + } else { + "minecraft:carved_pumpkin" + }; + set_item(m, HEAD, head); + set_drop_chance(m, HEAD, 0.0); + } + } + + // ---- jockeys ------------------------------------------------------ + + fn create(&mut self, kind: &str, reason: Reason, at: &Mob) -> Option { + let mut j = self.level.create(kind, reason)?; + // snapTo(x, y, z, yRot, 0). + j.position = at.position; + j.previous = at.position; + j.yaw = at.yaw; + j.previous_yaw = at.yaw; + j.body_yaw = at.yaw; + j.head_yaw = at.yaw; + j.head_pitch = 0.0; + Some(j) + } + /// `startRiding`: the rider leaves the vehicle it was on. + fn ride(&mut self, rider: &mut Mob, vehicle: &mut Mob) { + if let Some(old) = rider.extra.mount + && let Some(v) = self.created.iter_mut().find(|c| c.id == old) + && v.extra.rider == Some(rider.id) + { + v.extra.rider = None; + } + rider.extra.mount = Some(vehicle.id); + rider.extra.passenger = true; + if vehicle.extra.rider.is_none() { + vehicle.extra.rider = Some(rider.id); + } + } + + // ---- the classes -------------------------------------------------- + + fn zombie(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { + let mut g = self.mob(m, g); + let special = self.special(); + if reason != Reason::Conversion { + m.extra.pick_up_loot = self.float() < 0.55 * special; + } + if g.is_none() { + g = Some(Group::Zombie { + baby: self.float() < 0.05, + jockey: true, + husk: None, + }); + } + if let Some(Group::Zombie { baby, jockey, .. }) = g { + if baby { + set_baby(m, true); + if jockey { + if f64::from(self.float()) < 0.05 { + let search = m + .bounds() + .inflate(horizon_core::geometry::Vec3::new(5.0, 3.0, 5.0)); + if let Some(chicken) = self.level.free_chicken(search) { + self.level.ride_chicken(chicken, m.id); + m.extra.mount = Some(chicken); + m.extra.passenger = true; + } + } else if f64::from(self.float()) < 0.05 + && let Some(mut chicken) = self.create("minecraft:chicken", Reason::Jockey, m) + { + self.finalize(&mut chicken, Reason::Jockey, None); + chicken.extra.jockey = true; + self.ride(m, &mut chicken); + self.created.push(chicken); + } + } + } + m.extra.can_break_doors = self.float() < special * 0.1; + if reason != Reason::Conversion { + self.populate(m); + self.enchant(m); + } + } + self.halloween(m); + self.zombie_attributes(m, special, reason); + g + } + /// `Zombie.handleAttributes`, from the zombie's own random. + fn zombie_attributes(&mut self, m: &mut Mob, special: f32, reason: Reason) { + let r = &mut m.random; + let reinforcements = if m.kind.species == Species::ZombifiedPiglin { + 0.0 + } else { + r.next_double() * f64::from(0.1f32) + }; + let knockback = r.next_double() * f64::from(0.05f32); + let follow = r.next_double() * 1.5 * f64::from(special); + let leader = r.next_float() < special * 0.05; + let leader_rolls = leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); + set_base(m, Attr::SpawnReinforcements, reinforcements); + add_modifier( + m, + Attr::KnockbackResistance, + "minecraft:random_spawn_bonus", + knockback, + Op::AddValue, + ); + if follow > 1.0 { + add_modifier( + m, + Attr::FollowRange, + "minecraft:zombie_random_spawn_bonus", + follow, + Op::AddMultipliedTotal, + ); + } + if let Some((reinforce, health)) = leader_rolls { + add_modifier( + m, + Attr::SpawnReinforcements, + "minecraft:leader_zombie_bonus", + reinforce, + Op::AddValue, + ); + add_modifier( + m, + Attr::MaxHealth, + "minecraft:leader_zombie_bonus", + health, + Op::AddMultipliedTotal, + ); + if !matches!( + reason, + Reason::Conversion | Reason::Load | Reason::DimensionTravel + ) { + m.health = max_health(m); + } + m.extra.can_break_doors = true; + } + } + fn husk(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { + let mut g = self.zombie(m, g, reason); + if reason != Reason::Conversion { + m.extra.pick_up_loot = self.float() < 0.55 * self.special(); + } + if let Some(Group::Zombie { baby, jockey, .. }) = g { + g = Some(Group::Zombie { + baby, + jockey, + husk: Some(reason != Reason::Natural), + }); + } + if let Some(Group::Zombie { + husk: Some(tried @ false), + .. + }) = &mut g + { + let (bx, by, bz) = ( + m.position.x.floor(), + m.position.y.floor(), + m.position.z.floor(), + ); + let (w, h) = self.data.camel_husk_size; + let half = w / 2.0; + let bounds = Aabb::new( + horizon_core::geometry::Vec3::new(bx + 0.5 - f64::from(half), by, bz + 0.5 - f64::from(half)), + horizon_core::geometry::Vec3::new( + bx + 0.5 + f64::from(half), + by + f64::from(h), + bz + 0.5 + f64::from(half), + ), + ); + if self.level.no_collision(bounds) { + *tried = true; + if self.float() < 0.1 { + set_item(m, MAINHAND, "minecraft:iron_spear"); + if let Some(mut camel) = self.level.create("minecraft:camel_husk", Reason::Natural) { + // setPos: the husk's position, the camel's own rotation. + camel.position = m.position; + camel.previous = m.position; + self.finalize(&mut camel, reason, None); + self.ride(m, &mut camel); + if let Some(mut parched) = self.create("minecraft:parched", Reason::Natural, m) { + self.finalize(&mut parched, reason, None); + self.ride(&mut parched, &mut camel); + self.created.push(camel); + self.created.push(parched); + } else { + self.created.push(camel); + } + } + } + } + } + g + } + fn drowned(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { + let g = self.zombie(m, g, reason); + if m.extra.off_hand.is_none() && self.float() < 0.03 { + set_item(m, OFFHAND, "minecraft:nautilus_shell"); + set_drop_chance(m, OFFHAND, 2.0); + } + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if matches!(reason, Reason::Natural | Reason::Structure) + && m.extra.main_hand.as_deref() == Some("minecraft:trident") + && self.float() < 0.5 + && !m.is_baby() + && !self + .level + .biome_tag("minecraft:more_frequent_drowned_spawns", at) + && let Some(mut nautilus) = self.create("minecraft:zombie_nautilus", Reason::Jockey, m) + { + if reason == Reason::Structure { + nautilus.persistent = true; + } + self.finalize(&mut nautilus, reason, None); + self.ride(m, &mut nautilus); + self.created.push(nautilus); + } + g + } + fn skeleton(&mut self, m: &mut Mob, g: Option) -> Option { + let g = self.mob(m, g); + self.populate(m); + self.enchant(m); + m.extra.pick_up_loot = self.float() < 0.55 * self.special(); + self.halloween(m); + if m.species() == Species::WitherSkeleton { + set_base(m, Attr::AttackDamage, 4.0); + } + g + } + fn spider(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { + let mut g = self.mob(m, g); + if self.int(100) == 0 + && let Some(mut skeleton) = self.create("minecraft:skeleton", Reason::Jockey, m) + { + self.finalize(&mut skeleton, reason, None); + self.ride(&mut skeleton, m); + self.created.push(skeleton); + } + if g.is_none() { + let mut effect = None; + if self.difficulty.hard && self.float() < 0.1 * self.special() { + effect = Some(match self.int(5) { + 0 | 1 => "minecraft:speed", + 2 => "minecraft:strength", + 3 => "minecraft:regeneration", + _ => "minecraft:invisibility", + }); + } + g = Some(Group::Spider(effect)); + } + if let Some(Group::Spider(Some(effect))) = g { + m.add_effect(effect, -1, 0); + } + g + } + /// `Raider` then `PatrollingMonster.finalizeSpawn`. + fn raider(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { + let witch = m.species() == Species::Witch; + super::raider::state_mut(m).can_join_raid = !witch || reason != Reason::Natural; + if !matches!(reason, Reason::Patrol | Reason::Event | Reason::Structure) + && self.float() < 0.06 + && super::raider::can_be_leader(m.species()) + { + super::raider::state_mut(m).patrol_leader = true; + } + if super::raider::state(m).is_some_and(|s| s.patrol_leader) { + set_item(m, HEAD, super::raider::BANNER); + set_drop_chance(m, HEAD, 2.0); + } + if reason == Reason::Patrol { + super::raider::state_mut(m).patrolling = true; + } + self.mob(m, g) + } + fn piglin(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { + if reason != Reason::Structure { + if self.float() < 0.2 { + set_baby(m, true); + } else if !m.is_baby() { + // createSpawnWeapon, from the piglin's own random. + let r = &mut m.random; + let weapon = if f64::from(r.next_float()) < 0.5 { + "minecraft:crossbow" + } else if r.next_int_bound(10).unwrap_or(1) == 0 { + "minecraft:golden_spear" + } else { + "minecraft:golden_sword" + }; + set_item(m, MAINHAND, weapon); + } + } + // PiglinAi.initMemories: HUNTED_RECENTLY for 30 to 120 seconds. + let hunt = self.uniform(600, 2400); + set_memory(m, "hunted_recently", 1, i64::from(hunt)); + self.populate(m); + self.enchant(m); + self.mob(m, g) + } + fn strider(&mut self, m: &mut Mob, g: Option) -> Option { + if m.is_baby() { + return self.ageable(m, g); + } + let mut g = g; + if self.int(30) == 0 && self.level.spawning_monsters() { + if let Some(mut jockey) = self.create("minecraft:zombified_piglin", Reason::Jockey, m) { + let baby = self.float() < 0.05; + g = Some(self.strider_jockey( + m, + &mut jockey, + Some(Group::Zombie { + baby, + jockey: false, + husk: None, + }), + )); + set_item(&mut jockey, MAINHAND, "minecraft:warped_fungus_on_a_stick"); + set_item(m, SADDLE, "minecraft:saddle"); + set_drop_chance(m, SADDLE, 2.0); + self.created.push(jockey); + } + } else if self.int(10) == 0 { + if let Some(mut jockey) = self.create("minecraft:strider", Reason::Jockey, m) { + set_age(&mut jockey, -24000); + g = Some(self.strider_jockey(m, &mut jockey, None)); + self.created.push(jockey); + } + } else { + g = Some(Group::Ageable(Ageable::chance(0.5))); + } + self.ageable(m, g) + } + /// `Strider.spawnJockey`. + fn strider_jockey(&mut self, m: &mut Mob, jockey: &mut Mob, g: Option) -> Group { + jockey.position = m.position; + jockey.yaw = m.yaw; + self.finalize(jockey, Reason::Jockey, g); + self.ride(jockey, m); + Group::Ageable(Ageable::chance(0.0)) + } + /// `AbstractHorse.finalizeSpawn` with each `randomizeAttributes`. + fn horse(&mut self, m: &mut Mob, g: Option) -> Option { + let g = g.or(Some(Group::Ageable(Ageable::chance(0.2)))); + use Species as S; + match m.species() { + S::Horse => { + let health = self.horse_health(); + set_base(m, Attr::MaxHealth, f64::from(health)); + let speed = self.horse_speed(); + set_base(m, Attr::MovementSpeed, speed); + let jump = self.horse_jump(); + set_base(m, Attr::JumpStrength, jump); + } + S::Donkey | S::Mule | S::Llama | S::TraderLlama => { + let health = self.horse_health(); + set_base(m, Attr::MaxHealth, f64::from(health)); + } + S::SkeletonHorse => { + let jump = self.horse_jump(); + set_base(m, Attr::JumpStrength, jump); + } + S::ZombieHorse => { + let d = 0.066_666_666_666_666_67; + let jump = 0.5 + + self.random.next_double() * d + + self.random.next_double() * d + + self.random.next_double() * d; + set_base(m, Attr::JumpStrength, jump); + let speed = (9.0 + + self.random.next_double() + + self.random.next_double() + + self.random.next_double()) + / f64::from(42.16f32); + set_base(m, Attr::MovementSpeed, speed); + } + _ => {} + } + self.ageable(m, g) + } + fn horse_health(&mut self) -> f32 { + 15.0 + self.int(8) as f32 + self.int(9) as f32 + } + fn horse_speed(&mut self) -> f64 { + (f64::from(0.45f32) + + self.random.next_double() * 0.3 + + self.random.next_double() * 0.3 + + self.random.next_double() * 0.3) + * 0.25 + } + fn horse_jump(&mut self) -> f64 { + f64::from(0.4f32) + + self.random.next_double() * 0.2 + + self.random.next_double() * 0.2 + + self.random.next_double() * 0.2 + } + fn villager_type(&mut self, m: &mut Mob) { + let at = block(m); + m.extra.variant = villager_type(&self.level.biome(at)); + } + /// `VariantUtils.selectVariantToSpawn` into `variant`, by registry name. + fn variant(&mut self, m: &mut Mob, registry: fn(&SpawnRegistries) -> &VariantRegistry) { + let r = registry(self.data.registries); + let at = block(m); + if let Some(i) = r.select(&*self.level, at, self.random) { + let name = r.names[i].clone(); + m.extra.variant = variant_index(m.species(), &name); + } + } + fn sound(&mut self, m: &mut Mob, registry: fn(&SpawnRegistries) -> &VariantRegistry) { + let r = registry(self.data.registries); + m.extra.sound_variant = r.random(self.random) as u8; + } + + /// `finalizeSpawn` of the mob's class. + pub fn finalize(&mut self, m: &mut Mob, reason: Reason, g: Option) -> Option { + use Species as S; + let s = m.species(); + match s { + S::Pig | S::Cow | S::Chicken => { + let (v, sound): (fn(&SpawnRegistries) -> &VariantRegistry, fn(&SpawnRegistries) -> &VariantRegistry) = match s { + S::Pig => (|r| &r.pig, |r| &r.pig_sound), + S::Cow => (|r| &r.cow, |r| &r.cow_sound), + _ => (|r| &r.chicken, |r| &r.chicken_sound), + }; + self.variant(m, v); + self.sound(m, sound); + self.ageable(m, g) + } + S::Cat => { + let g = self.ageable(m, g); + self.variant(m, |r| &r.cat); + self.sound(m, |r| &r.cat_sound); + g + } + S::Wolf => { + let g = match g { + Some(Group::Wolf(a, v)) => { + m.extra.variant = v; + Some(Group::Wolf(a, v)) + } + other => { + let r = &self.data.registries.wolf; + let at = block(m); + match r.select(&*self.level, at, self.random) { + Some(i) => { + let v = variant_index(s, &r.names[i]); + m.extra.variant = v; + Some(Group::Wolf(Ageable::babies(false), v)) + } + None => other, + } + } + }; + self.sound(m, |r| &r.wolf_sound); + self.ageable(m, g) + } + S::Frog => { + self.variant(m, |r| &r.frog); + let jump = self.uniform(100, 140); + set_memory(m, "long_jump_cooldown", i64::from(jump), i64::MAX); + self.ageable(m, g) + } + S::ZombieNautilus => { + self.variant(m, |r| &r.zombie_nautilus); + let cooldown = self.uniform(2400, 3600); + set_memory(m, "attack_target_cooldown", i64::from(cooldown), i64::MAX); + m.extra.counter = cooldown; + self.ageable(m, g) + } + S::Nautilus => { + let cooldown = self.uniform(2400, 3600); + set_memory(m, "attack_target_cooldown", i64::from(cooldown), i64::MAX); + m.extra.counter = cooldown; + self.ageable(m, g) + } + S::Sheep => { + let climate = if self + .level + .biome_tag("minecraft:spawns_warm_variant_farm_animals", block(m)) + { + Climate::Warm + } else if self + .level + .biome_tag("minecraft:spawns_cold_variant_farm_animals", block(m)) + { + Climate::Cold + } else { + Climate::Temperate + }; + m.extra.color = super::farm::sheep_color(climate, self.random); + self.ageable(m, g) + } + S::Rabbit => { + let at = block(m); + let roll = self.int(100); + let mut variant = if self.level.biome_tag("minecraft:spawns_white_rabbits", at) { + if roll < 80 { 1 } else { 3 } + } else if self.level.biome_tag("minecraft:spawns_gold_rabbits", at) { + 4 + } else if roll < 50 { + 0 + } else if roll < 90 { + 5 + } else { + 2 + }; + let g = match g { + Some(Group::Rabbit(a, v)) => { + variant = v; + Group::Rabbit(a, v) + } + _ => Group::Rabbit(Ageable::chance(1.0), variant), + }; + m.extra.variant = variant; + self.ageable(m, Some(g)) + } + S::Horse => { + let (g, variant) = match g { + Some(Group::Horse(a, v)) => (Group::Horse(a, v), v), + _ => { + let v = self.int(7) as u8; + (Group::Horse(Ageable::babies(true), v), v) + } + }; + let markings = self.int(5) as u8; + m.extra.variant = variant; + m.extra.variant2 = markings; + self.horse(m, Some(g)) + } + S::Llama | S::TraderLlama => { + let mut g = g; + if s == S::TraderLlama { + if reason == Reason::Event { + set_age(m, 0); + } + if g.is_none() { + g = Some(Group::Ageable(Ageable::babies(false))); + } + } + let max = if self.float() < 0.04 { 5 } else { 3 }; + m.extra.variant2 = (1 + self.int(max)) as u8; + let g = match g { + Some(Group::Llama(a, v)) => { + m.extra.variant = v; + Group::Llama(a, v) + } + _ => { + let v = self.int(4) as u8; + m.extra.variant = v; + Group::Llama(Ageable::babies(true), v) + } + }; + self.horse(m, Some(g)) + } + S::Donkey | S::Mule | S::SkeletonHorse => self.horse(m, g), + S::ZombieHorse => { + if reason == Reason::Natural + && let Some(mut zombie) = self.create("minecraft:zombie", Reason::Jockey, m) + { + self.finalize(&mut zombie, reason, None); + set_item(&mut zombie, MAINHAND, "minecraft:iron_spear"); + self.ride(&mut zombie, m); + self.created.push(zombie); + } + self.horse(m, g) + } + S::Camel | S::CamelHusk => { + let now = self.level.game_time(); + m.extra.pose_change_tick = (now - 52 - 1).max(0); + super::camel::stand_up_instantly(m); + self.horse(m, g) + } + S::Goat => { + let jump = self.uniform(600, 1200); + set_memory(m, "long_jump_cooldown", i64::from(jump), i64::MAX); + let ram = self.uniform(600, 6000); + set_memory(m, "ram_cooldown", i64::from(ram), i64::MAX); + m.extra.screaming = self.random.next_double() < 0.02; + age_boundary_reached(m); + if !m.is_baby() && self.float() < 0.1 { + let left = self.random.next_boolean(); + m.extra.lost_horns[usize::from(!left)] = true; + } + self.ageable(m, g) + } + S::Panda => { + let main = panda_gene(self.int(16)); + let hidden = panda_gene(self.int(16)); + m.extra.variant = main; + m.extra.variant2 = hidden; + let shown = panda_variant(main, hidden); + if shown == 5 { + set_base(m, Attr::MaxHealth, 10.0); + } + if shown == 1 { + set_base(m, Attr::MovementSpeed, f64::from(0.07f32)); + } + self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(0.2))))) + } + S::PolarBear | S::Ocelot => { + self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(1.0))))) + } + S::Fox => { + let at = block(m); + let mut variant = u8::from(self.level.biome_tag("minecraft:spawns_snow_foxes", at)); + let mut baby = false; + let g = match g { + Some(Group::Fox(a, v)) => { + variant = v; + baby = a.size >= 2; + Group::Fox(a, v) + } + _ => Group::Fox(Ageable::babies(false), variant), + }; + m.extra.variant = variant; + if baby { + set_age(m, -24000); + } + self.populate(m); + self.ageable(m, Some(g)) + } + S::Parrot => { + m.extra.variant = self.int(5) as u8; + self.ageable(m, g.or(Some(Group::Ageable(Ageable::babies(false))))) + } + S::Axolotl => { + if reason == Reason::Bucket { + return g; + } + let mut baby = false; + let g = match g { + Some(Group::Axolotl(a, types)) => { + baby = a.size >= 2; + Group::Axolotl(a, types) + } + _ => { + let a = self.int(4) as u8; + let b = self.int(4) as u8; + Group::Axolotl(Ageable::babies(false), [a, b]) + } + }; + if let Group::Axolotl(_, types) = g { + m.extra.variant = types[self.int(2) as usize]; + } + if baby { + set_age(m, -24000); + } + self.ageable(m, Some(g)) + } + S::Squid | S::GlowSquid => { + self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(0.05))))) + } + S::Dolphin => { + m.air = 4800; + m.head_pitch = 0.0; + self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(0.1))))) + } + S::Turtle => { + m.extra.home = Some(block(m)); + self.ageable(m, g) + } + S::Villager | S::WanderingTrader => { + if s == S::Villager { + if reason == Reason::Breeding { + m.extra.variant2 = 0; + } + self.villager_type(m); + } + self.ageable(m, g.or(Some(Group::Ageable(Ageable::babies(false))))) + } + S::Hoglin => { + if self.float() < 0.2 { + set_baby(m, true); + } + self.ageable(m, g) + } + S::Zoglin => { + if self.float() < 0.2 { + set_baby(m, true); + } + self.mob(m, g) + } + S::Strider => self.strider(m, g), + S::Slime | S::MagmaCube | S::SulfurCube => { + let g = if s == S::SulfurCube { + g + } else { + g.or(Some(Group::Ageable(Ageable::babies(false)))) + }; + let g = self.ageable(m, g); + if s == S::SulfurCube { + let size = if m.is_baby() { 1 } else { 2 }; + super::sulfur_cube::set_size(m, size, true); + } else { + let mut scale = self.int(3); + if scale < 2 && self.float() < 0.5 * self.special() { + scale += 1; + } + cube_size(m, 1 << scale); + } + g + } + S::Cod | S::Salmon | S::TropicalFish => { + if s == S::Salmon { + // A weighted list (small 30, medium 50, large 15) on the + // salmon's own random. + let r = m.random.next_int_bound(95).unwrap_or(0); + m.extra.variant = if r < 30 { + 0 + } else if r < 80 { + 1 + } else { + 2 + }; + } + let given = g; + self.mob(m, None); + let g = match given { + None => Group::School(m.id, None), + Some(Group::School(leader, v)) => { + m.extra.leader = Some(leader); + Group::School(leader, v) + } + Some(other) => other, + }; + if s != S::TropicalFish { + return Some(g); + } + let (g, (p, b, c)) = match g { + Group::School(leader, Some(v)) => (Group::School(leader, Some(v)), v), + other => { + if f64::from(self.float()) < 0.9 { + let v = super::aquatic::COMMON_TROPICAL[self.int(22) as usize]; + (Group::School(m.id, Some(v)), v) + } else { + m.extra.lone = true; + let p = self.int(12) as u8; + let b = self.int(16) as u8; + let c = self.int(16) as u8; + (other, (p, b, c)) + } + } + }; + m.extra.variant = p; + m.extra.variant2 = b; + m.extra.variant3 = c; + Some(g) + } + S::Zombie | S::ZombifiedPiglin => self.zombie(m, g, reason), + S::ZombieVillager => { + self.villager_type(m); + m.extra.variant2 = m.random.next_int_bound(15).unwrap_or(0) as u8; + self.zombie(m, g, reason) + } + S::Husk => self.husk(m, g, reason), + S::Drowned => self.drowned(m, g, reason), + s if skeleton(s) => self.skeleton(m, g), + S::Spider => self.spider(m, g, reason), + // CaveSpider.finalizeSpawn returns at once. + S::CaveSpider => g, + S::Pillager => { + self.populate(m); + self.enchant(m); + self.raider(m, g, reason) + } + S::Vindicator => { + let g = self.raider(m, g, reason); + self.populate(m); + self.enchant(m); + g + } + S::Illusioner => { + set_item(m, MAINHAND, "minecraft:bow"); + self.raider(m, g, reason) + } + s if raider(s) => self.raider(m, g, reason), + S::Piglin => self.piglin(m, g, reason), + S::PiglinBrute => { + let home = block(m); + m.extra.home = Some(home); + set_memory(m, "home", 0, i64::MAX); + self.populate(m); + self.mob(m, g) + } + S::Vex => { + self.populate(m); + self.enchant(m); + self.mob(m, g) + } + S::Warden => { + super::warden::finalize(m, reason == Reason::Triggered, &mut Vec::new()); + set_memory(m, "dig_cooldown", 0, 1200); + if reason == Reason::Triggered { + set_memory(m, "is_emerging", 0, i64::from(super::warden::EMERGE_DURATION)); + } + self.mob(m, g) + } + S::Phantom => { + let at = block(m); + m.extra.home = Some([at[0], at[1] + 5, at[2]]); + m.extra.size = 0; + self.mob(m, g) + } + S::Shulker => { + m.yaw = 0.0; + m.head_yaw = 0.0; + m.previous_yaw = 0.0; + m.previous_head_yaw = 0.0; + self.mob(m, g) + } + _ if ageable(s) => self.ageable(m, g), + _ => self.mob(m, g), + } + } +} + +/// `Mob.finalizeSpawn` of a fresh mob. Returns the group data for the next +/// mob of the pack. +pub fn finalize( + cx: &mut Ctx<'_, L, R>, + m: &mut Mob, + reason: Reason, + g: Option, +) -> Option { + cx.finalize(m, reason, g) +} + +fn block(m: &Mob) -> [i32; 3] { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] +} +/// A brain memory finalizeSpawn sets: value and ticks until it expires. +fn set_memory(m: &mut Mob, name: &'static str, value: i64, ttl: i64) { + match m.extra.memories.iter_mut().find(|x| x.0 == name) { + Some(x) => *x = (name, value, ttl), + None => m.extra.memories.push((name, value, ttl)), + } +} +/// `Panda.Gene.getRandom` (enum order: normal, lazy, worried, playful, +/// brown, weak, aggressive). +fn panda_gene(roll: i32) -> u8 { + match roll { + 0 => 1, + 1 => 2, + 2 => 3, + 4 => 6, + r if r < 9 => 5, + r if r < 11 => 4, + _ => 0, + } +} +/// `Panda.Gene.getVariantFromGenes`: a recessive gene shows when both match. +pub fn panda_variant(main: u8, hidden: u8) -> u8 { + let recessive = matches!(main, 4 | 5); + if recessive && main != hidden { 0 } else { main } +} +/// `AbstractCubeMob.setSize(size, true)` for slimes and magma cubes. +fn cube_size(m: &mut Mob, size: i32) { + let size = size.clamp(1, 127); + m.extra.size = size; + set_base(m, Attr::MaxHealth, f64::from(size * size)); + set_base(m, Attr::MovementSpeed, f64::from(0.2f32 + 0.1f32 * size as f32)); + set_base(m, Attr::AttackDamage, f64::from(size)); + if m.species() == Species::MagmaCube { + set_base(m, Attr::Armor, f64::from(size * 3)); + } + m.health = max_health(m); +} +/// The index the game keeps for a variant registry entry. +pub fn variant_index(s: Species, name: &str) -> u8 { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + let i = match s { + Species::Cat => super::tame::CAT_VARIANTS.iter().position(|v| *v == name), + Species::Wolf => super::tame::WOLF_VARIANTS.iter().position(|v| v.0 == name), + Species::ZombieNautilus => super::nautilus::VARIANTS.iter().position(|v| *v == name), + _ => ["temperate", "warm", "cold"].iter().position(|v| *v == name), + }; + i.unwrap_or(0) as u8 +} +/// The registry name of the game's variant index. +pub fn variant_name(s: Species, index: u8) -> &'static str { + let i = index as usize; + match s { + Species::Cat => super::tame::CAT_VARIANTS.get(i).copied().unwrap_or("tabby"), + Species::Wolf => super::tame::WOLF_VARIANTS.get(i).map_or("pale", |v| v.0), + Species::ZombieNautilus => super::nautilus::VARIANTS.get(i).copied().unwrap_or("temperate"), + _ => ["temperate", "warm", "cold"].get(i).copied().unwrap_or("temperate"), + } +} +/// `VillagerType.byBiome` (index into `render::VILLAGER_TYPES`: plains, +/// desert, jungle, savanna, snow, swamp, taiga). +pub fn villager_type(biome: &str) -> u8 { + match biome.strip_prefix("minecraft:").unwrap_or(biome) { + "badlands" | "desert" | "eroded_badlands" | "wooded_badlands" => 1, + "bamboo_jungle" | "jungle" | "sparse_jungle" => 2, + "savanna_plateau" | "savanna" | "windswept_savanna" => 3, + "deep_frozen_ocean" | "frozen_ocean" | "frozen_river" | "ice_spikes" | "snowy_beach" + | "snowy_taiga" | "snowy_plains" | "grove" | "snowy_slopes" | "frozen_peaks" + | "jagged_peaks" => 4, + "swamp" | "mangrove_swamp" => 5, + "old_growth_spruce_taiga" | "old_growth_pine_taiga" | "windswept_gravelly_hills" + | "windswept_hills" | "taiga" | "windswept_forest" => 6, + _ => 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn panda_genes_follow_the_vanilla_table() { + assert_eq!(panda_gene(0), 1); + assert_eq!(panda_gene(3), 5); + assert_eq!(panda_gene(4), 6); + assert_eq!(panda_gene(9), 4); + assert_eq!(panda_gene(15), 0); + assert_eq!(panda_variant(4, 0), 0); + assert_eq!(panda_variant(4, 4), 4); + assert_eq!(panda_variant(6, 0), 6); + } + #[test] + fn reasons_round_trip() { + for r in Reason::ALL { + assert_eq!(Reason::parse(r.name()), Some(r)); + } + } + #[test] + fn villager_types_by_biome() { + assert_eq!(villager_type("minecraft:badlands"), 1); + assert_eq!(villager_type("minecraft:grove"), 4); + assert_eq!(villager_type("minecraft:plains"), 0); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java new file mode 100644 index 000000000..753ebbc54 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java @@ -0,0 +1,525 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.Difficulty; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.ai.Brain; +import net.minecraft.world.entity.ai.attributes.Attribute; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.memory.MemoryModuleType; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.ItemEnchantments; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +/** + * Original oracle: Mob.finalizeSpawn as vanilla runs it, for every mob type, + * spawn reason, difficulty and local difficulty, on a stand-in ServerLevel + * (one biome, an optional structure piece, a floor and an optional roof, + * chickens standing by, the moon phase). + * + * Each case seeds the level random (what finalizeSpawn reads through + * level.getRandom()) and the entities' own randoms: every entity created + * in the case, the case's mobs and the jockeys finalizeSpawn makes, gets + * a LegacyRandomSource seeded eseed + its creation index, swapped in + * through each EntityType's factory. A pack of mobs is finalized in turn + * with the group data passed along, as NaturalSpawner does, each added to + * the level with its passengers. + * + * The log lists every entity of the case in creation order (equipment and + * enchantments, drop chances, CanPickUpLoot, LeftHanded, persistence, age, + * health, attribute values, effects, the species' variant state and spawn + * memories, its vehicle) and the next draws of the level random and of each + * entity's random, which pin every draw in between. + */ +public final class VanillaFinalizeSpawnOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value); + } + + static Object get(Object target, Class owner, String field) { + try { + Field f = owner.getDeclaredField(field); + f.setAccessible(true); + return f.get(target); + } catch (Exception e) { throw new RuntimeException(e); } + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + RegistryAccess registries; + net.minecraft.server.MinecraftServer fake; + BlockState floor; + int floorY, roofY; + Holder biome; + Difficulty difficulty; + DimensionType dimensionType; + ResourceKey dimensionKey; + List entities = new ArrayList<>(); + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + BiomeManager biomeManager; + WorldBorder border = new WorldBorder(); + GameRules rules; + Structures structures; + RandomSource levelRandom; + long time; + int next = 1; + @Override public net.minecraft.server.MinecraftServer getServer() { return fake; } + @Override public RegistryAccess registryAccess() { return registries; } + @Override public Difficulty getDifficulty() { return difficulty; } + @Override public long getGameTime() { return time; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public BlockState getBlockState(BlockPos pos) { + if (pos.getY() == floorY) return floor; + if (pos.getY() == roofY) return Blocks.STONE.defaultBlockState(); + return Blocks.AIR.defaultBlockState(); + } + @Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } + @Override public DimensionType dimensionType() { return dimensionType; } + @Override public ResourceKey dimension() { return dimensionKey; } + @Override public Holder getBiome(BlockPos pos) { return biome; } + @Override public BiomeManager getBiomeManager() { return biomeManager; } + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public WorldBorder getWorldBorder() { return border; } + @Override public GameRules getGameRules() { return rules; } + @Override public RandomSource getRandom() { return levelRandom; } + @Override public int getSeaLevel() { return 63; } + net.minecraft.server.ServerScoreboard scoreboard; + @Override public net.minecraft.server.ServerScoreboard getScoreboard() { return scoreboard; } + @Override public net.minecraft.world.level.StructureManager structureManager() { return structures; } + @Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; } + @Override public boolean isSpawningMonsters() { return rules.get(GameRules.SPAWN_MOBS) && rules.get(GameRules.SPAWN_MONSTERS); } + @Override public void playSeededSound(Entity except, double x, double y, double z, Holder sound, SoundSource source, float volume, float pitch, long seed) {} + @Override public void playSeededSound(Entity except, Entity sourceEntity, Holder sound, SoundSource source, float volume, float pitch, long seed) {} + @Override public void gameEvent(Holder gameEvent, Vec3 position, net.minecraft.world.level.gameevent.GameEvent.Context context) {} + @Override public void broadcastEntityEvent(Entity entity, byte event) {} + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override public List players() { return List.of(); } + @Override public Iterable getAllEntities() { return entities; } + @Override public List getEntities(Entity except, AABB bb, Predicate selector) { + List out = new ArrayList<>(); + for (Entity e : entities) if (e != except && e.getBoundingBox().intersects(bb) && selector.test(e)) out.add(e); + return out; + } + @Override public List getEntities(EntityTypeTest type, AABB bb, Predicate selector) { + List out = new ArrayList<>(); + for (Entity e : entities) { + T t = type.tryCast(e); + if (t != null && e.getBoundingBox().intersects(bb) && selector.test(t)) out.add(t); + } + return out; + } + @Override public boolean addFreshEntity(Entity entity) { if (!entities.contains(entity)) entities.add(entity); return true; } + @Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); } + @Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) { return null; } + } + + /** One structure start whose single piece covers a box around the spawn point. */ + static final class Structures extends net.minecraft.world.level.StructureManager { + Structures() { super(null, null, null); } + Lvl level; + Structure structure; + StructureStart start; + @Override public List startsForStructure(int sectionX, int sectionZ, Predicate matcher) { + return start != null && matcher.test(structure) ? List.of(start) : List.of(); + } + @Override public List startsForStructure(int sectionX, int sectionZ, Structure s) { + return start != null && s == structure ? List.of(start) : List.of(); + } + @Override public RegistryAccess registryAccess() { return level.registries; } + } + + static final class Piece extends StructurePiece { + Piece(BoundingBox box) { super(null, 0, box); } + @Override protected void addAdditionalSaveData(net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext context, net.minecraft.nbt.CompoundTag tag) {} + @Override public void postProcess(WorldGenLevel level, net.minecraft.world.level.StructureManager structureManager, net.minecraft.world.level.chunk.ChunkGenerator generator, RandomSource random, + BoundingBox chunkBB, ChunkPos chunkPos, BlockPos referencePos) {} + } + + /** Entities created in the current case, and the seed base of their randoms. */ + static List created = new ArrayList<>(); + static long entitySeed; + static boolean seeding; + static int otherIds; + + @SuppressWarnings({"unchecked", "rawtypes"}) + static void wrapFactories() throws Exception { + Field factory = EntityType.class.getDeclaredField("factory"); + long offset = (long) objectFieldOffset.invoke(unsafe, factory); + factory.setAccessible(true); + for (EntityType type : BuiltInRegistries.ENTITY_TYPE) { + EntityType.EntityFactory original = (EntityType.EntityFactory) factory.get(type); + EntityType.EntityFactory wrapped = (t, level) -> { + Entity e = original.create(t, level); + if (e != null && !seeding) e.setId(1000000 + otherIds++); + if (e != null && seeding) { + try { + put(e, Entity.class, "random", RandomSource.create(entitySeed + created.size())); + } catch (Exception ex) { throw new RuntimeException(ex); } + created.add(e); + e.setId(created.size()); + } + return e; + }; + putObject.invoke(unsafe, type, offset, wrapped); + } + } + + static String hex(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } + static String hex(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); } + static String id(Holder h) { return h.unwrapKey().map(k -> k.identifier().toString()).orElse("?"); } + + static final EquipmentSlot[] SLOTS = {EquipmentSlot.MAINHAND, EquipmentSlot.OFFHAND, EquipmentSlot.FEET, EquipmentSlot.LEGS, + EquipmentSlot.CHEST, EquipmentSlot.HEAD, EquipmentSlot.BODY, EquipmentSlot.SADDLE}; + + static String stack(ItemStack s) { + StringBuilder b = new StringBuilder(BuiltInRegistries.ITEM.getKey(s.getItem()).toString()); + if (s.getCount() != 1) b.append('x').append(s.getCount()); + ItemEnchantments e = s.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY); + if (!e.isEmpty()) { + List list = new ArrayList<>(); + for (var entry : e.entrySet()) list.add(id(entry.getKey()) + "=" + entry.getIntValue()); + list.sort(null); + b.append('[').append(String.join(",", list)).append(']'); + } + // Components besides enchantments (the ominous banner's). + int other = s.getComponentsPatch().forget(t -> t == DataComponents.ENCHANTMENTS).size(); + if (other > 0) b.append('*').append(other); + return b.toString(); + } + + /** Loaded after the bootstrap. */ + static final class Lists { + static final List>> ATTRIBUTES = List.of( + Map.entry("max_health", Attributes.MAX_HEALTH), Map.entry("movement_speed", Attributes.MOVEMENT_SPEED), + Map.entry("follow_range", Attributes.FOLLOW_RANGE), Map.entry("attack_damage", Attributes.ATTACK_DAMAGE), + Map.entry("knockback_resistance", Attributes.KNOCKBACK_RESISTANCE), Map.entry("spawn_reinforcements", Attributes.SPAWN_REINFORCEMENTS_CHANCE), + Map.entry("jump_strength", Attributes.JUMP_STRENGTH)); + + static final List>> MEMORIES = List.of( + Map.entry("long_jump_cooldown", MemoryModuleType.LONG_JUMP_COOLDOWN_TICKS), Map.entry("ram_cooldown", MemoryModuleType.RAM_COOLDOWN_TICKS), + Map.entry("attack_target_cooldown", MemoryModuleType.ATTACK_TARGET_COOLDOWN), Map.entry("hunted_recently", MemoryModuleType.HUNTED_RECENTLY), + Map.entry("dig_cooldown", MemoryModuleType.DIG_COOLDOWN), Map.entry("is_emerging", MemoryModuleType.IS_EMERGING), + Map.entry("home", MemoryModuleType.HOME)); + } + + /** The species state finalizeSpawn sets. */ + static void variant(Entity e, List v) { + if (e instanceof net.minecraft.world.entity.animal.pig.Pig p) { + v.add(id(p.getVariant())); + v.add(id((Holder) data(p, p.getClass(), "DATA_SOUND_VARIANT_ID"))); + } else if (e instanceof net.minecraft.world.entity.animal.cow.Cow c) { + v.add(id(c.getVariant())); + v.add(id((Holder) data(c, net.minecraft.world.entity.animal.cow.Cow.class, "DATA_SOUND_VARIANT_ID"))); + } else if (e instanceof net.minecraft.world.entity.animal.cow.MushroomCow m) { + v.add(m.getVariant().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.chicken.Chicken c) { + v.add(id(c.getVariant())); + v.add(id((Holder) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID"))); + v.add("jockey=" + c.isChickenJockey()); + } else if (e instanceof net.minecraft.world.entity.animal.feline.Cat c) { + v.add(id(c.getVariant())); + v.add(id((Holder) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID"))); + } else if (e instanceof net.minecraft.world.entity.animal.wolf.Wolf w) { + v.add(id((Holder) call(w, net.minecraft.world.entity.animal.wolf.Wolf.class, "getVariant"))); + v.add(id((Holder) data(w, w.getClass(), "DATA_SOUND_VARIANT_ID"))); + } else if (e instanceof net.minecraft.world.entity.animal.frog.Frog f) { + v.add(id(f.getVariant())); + } else if (e instanceof net.minecraft.world.entity.animal.nautilus.ZombieNautilus n) { + v.add(id(n.getVariant())); + } else if (e instanceof net.minecraft.world.entity.animal.sheep.Sheep s) { + v.add(s.getColor().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.equine.Horse h) { + v.add(h.getVariant().getSerializedName() + "/" + h.getMarkings().name().toLowerCase(Locale.ROOT)); + } else if (e instanceof net.minecraft.world.entity.animal.equine.Llama l) { + v.add(l.getVariant().getSerializedName() + "/" + l.getStrength()); + } else if (e instanceof net.minecraft.world.entity.animal.equine.SkeletonHorse h) { + v.add("trap=" + h.isTrap()); + } else if (e instanceof net.minecraft.world.entity.animal.fox.Fox f) { + v.add(f.getVariant().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.rabbit.Rabbit r) { + v.add(r.getVariant().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.parrot.Parrot p) { + v.add(p.getVariant().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.axolotl.Axolotl a) { + v.add(a.getVariant().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.fish.TropicalFish f) { + v.add(String.valueOf(call(f, net.minecraft.world.entity.animal.fish.TropicalFish.class, "getPackedVariant"))); + } else if (e instanceof net.minecraft.world.entity.animal.fish.Salmon s) { + v.add(s.getVariant().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.panda.Panda p) { + v.add(p.getMainGene().getSerializedName() + "/" + p.getHiddenGene().getSerializedName()); + } else if (e instanceof net.minecraft.world.entity.animal.goat.Goat g) { + v.add("scream=" + g.isScreamingGoat() + " horns=" + g.hasLeftHorn() + "," + g.hasRightHorn()); + } else if (e instanceof net.minecraft.world.entity.monster.cubemob.AbstractCubeMob s) { + v.add("size=" + s.getSize()); + } else if (e instanceof net.minecraft.world.entity.npc.villager.Villager vi) { + v.add(id(vi.getVillagerData().type()) + "/" + id(vi.getVillagerData().profession()) + "/" + vi.getVillagerData().level()); + } else if (e instanceof net.minecraft.world.entity.monster.zombie.ZombieVillager z) { + // The profession comes from the constructor's unseeded random. + v.add(id(z.getVillagerData().type()) + "/" + z.getVillagerData().level()); + } else if (e instanceof net.minecraft.world.entity.monster.Phantom p) { + v.add("size=" + p.getPhantomSize()); + } else if (e instanceof net.minecraft.world.entity.animal.turtle.Turtle t) { + BlockPos h = (BlockPos) get(t, net.minecraft.world.entity.animal.turtle.Turtle.class, "homePos"); + v.add("home=" + (h == null ? "-" : h.getX() + "," + h.getY() + "," + h.getZ())); + } else if (e instanceof net.minecraft.world.entity.animal.dolphin.Dolphin d) { + v.add("air=" + d.getAirSupply()); + } + if (e instanceof net.minecraft.world.entity.monster.zombie.Zombie z) v.add("doors=" + z.canBreakDoors()); + if (e instanceof net.minecraft.world.entity.monster.PatrollingMonster p) v.add("leader=" + p.isPatrolLeader() + " patrolling=" + call(p, net.minecraft.world.entity.monster.PatrollingMonster.class, "isPatrolling")); + if (e instanceof net.minecraft.world.entity.raid.Raider r) v.add("raid=" + r.canJoinRaid()); + if (e instanceof net.minecraft.world.entity.monster.Strider s) v.add("saddled=" + s.isSaddled()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static Object data(Entity e, Class owner, String name) { + return e.getEntityData().get((net.minecraft.network.syncher.EntityDataAccessor) fieldValue(owner, name)); + } + + static Object call(Object target, Class owner, String name) { + try { + Method m = owner.getDeclaredMethod(name); + m.setAccessible(true); + return m.invoke(target); + } catch (Exception ex) { throw new RuntimeException(ex); } + } + + static Object fieldValue(Class owner, String name) { + try { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + return f.get(null); + } catch (Exception ex) { throw new RuntimeException(ex); } + } + + static String describe(Entity e, List all) { + List t = new ArrayList<>(); + t.add(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()).toString()); + Entity vehicle = e.getVehicle(); + t.add("veh=" + (vehicle == null ? "-" : Integer.toString(all.indexOf(vehicle)))); + if (e instanceof AgeableMob a) t.add("age=" + a.getAge()); + else if (e instanceof LivingEntity l) t.add("baby=" + l.isBaby()); + if (e instanceof LivingEntity l) t.add("hp=" + hex(l.getHealth())); + if (e instanceof Mob m) { + t.add("lh=" + m.isLeftHanded()); + t.add("loot=" + m.canPickUpLoot()); + t.add("persist=" + m.isPersistenceRequired()); + List eq = new ArrayList<>(); + for (EquipmentSlot s : SLOTS) { + ItemStack st = m.getItemBySlot(s); + if (!st.isEmpty()) eq.add(s.getSerializedName() + ":" + stack(st)); + } + t.add("eq=" + (eq.isEmpty() ? "-" : String.join(";", eq))); + List drops = new ArrayList<>(); + for (EquipmentSlot s : SLOTS) { + float d = m.getDropChances().byEquipment(s); + if (d != 0.085F) drops.add(s.getSerializedName() + ":" + hex(d)); + } + t.add("drop=" + (drops.isEmpty() ? "-" : String.join(";", drops))); + } + if (e instanceof LivingEntity l) { + List attrs = new ArrayList<>(); + for (var a : Lists.ATTRIBUTES) { + AttributeInstance inst = l.getAttribute(a.getValue()); + if (inst != null) attrs.add(a.getKey() + ":" + hex(inst.getValue())); + } + t.add("a=" + String.join(",", attrs)); + List fx = new ArrayList<>(); + for (MobEffectInstance i : l.getActiveEffects()) fx.add(id(i.getEffect()) + ":" + i.getAmplifier() + ":" + i.getDuration()); + fx.sort(null); + t.add("fx=" + (fx.isEmpty() ? "-" : String.join(",", fx))); + Brain brain = l.getBrain(); + List mem = new ArrayList<>(); + for (var m : Lists.MEMORIES) { + if (!brain.hasMemoryValue(m.getValue())) continue; + Object value = brain.getMemory(m.getValue()).orElse(null); + String text = value instanceof GlobalPos g ? g.pos().getX() + "," + g.pos().getY() + "," + g.pos().getZ() : String.valueOf(value); + mem.add(m.getKey() + ":" + text + ":" + brain.getTimeUntilExpiry(m.getValue())); + } + if (!mem.isEmpty()) t.add("mem=" + String.join(",", mem)); + } + List v = new ArrayList<>(); + variant(e, v); + if (!v.isEmpty()) t.add("v=" + String.join(" ", v).replace(' ', '_')); + return String.join(" ", t); + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = net.minecraft.server.ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + RegistryAccess access = loaded.layers().compositeAccess(); + var biomes = access.lookupOrThrow(Registries.BIOME); + var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE); + var blockLookup = access.lookupOrThrow(Registries.BLOCK); + var structureLookup = access.lookupOrThrow(Registries.STRUCTURE); + + var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class); + put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class)); + Lvl level = (Lvl) alloc(Lvl.class); + level.fake = server; + put(level, ServerLevel.class, "server", server); + level.registries = access; + level.entities = new ArrayList<>(); + level.scoreboard = new net.minecraft.server.ServerScoreboard(server); + level.border = new WorldBorder(); + level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) { + @Override public Holder getBiome(BlockPos pos) { return level.biome; } + @Override public Holder getBiome(int x, int y, int z) { return level.biome; } + }; + Structures structures = (Structures) alloc(Structures.class); + structures.level = level; + level.structures = structures; + wrapFactories(); + + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + w.println("halloween " + net.minecraft.util.SpecialDates.isHalloween()); + for (String raw : lines) { + if (raw.isBlank()) continue; + Map c = new LinkedHashMap<>(); + for (String token : raw.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1)); + } + try { + level.dimensionKey = ResourceKey.create(Registries.DIMENSION, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld"))); + level.dimensionType = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, level.dimensionKey.identifier())).value(); + level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains")))); + level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal")); + level.time = Long.parseLong(c.getOrDefault("time", "0")); + level.rules.set(GameRules.SPAWN_MONSTERS, !c.getOrDefault("monsters", "1").equals("0"), null); + int phase = Integer.parseInt(c.getOrDefault("phase", "0")); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level) + .addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder() + .set(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, MoonPhase.values()[phase]).build()) + .build(); + String[] p = c.get("pos").split(","); + double x = Double.parseDouble(p[0]), y = Double.parseDouble(p[1]), z = Double.parseDouble(p[2]); + BlockPos block = BlockPos.containing(x, y, z); + level.floorY = block.getY() - 1; + level.floor = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, c.getOrDefault("floor", "minecraft:grass_block"), false).blockState(); + level.roofY = c.containsKey("roof") ? block.getY() + Integer.parseInt(c.get("roof")) : Integer.MIN_VALUE; + structures.start = null; + if (c.containsKey("structure")) { + structures.structure = structureLookup.getValue(Identifier.parse(c.get("structure"))); + BoundingBox box = new BoundingBox(block.getX() - 8, block.getY() - 8, block.getZ() - 8, block.getX() + 8, block.getY() + 8, block.getZ() + 8); + structures.start = new StructureStart(structures.structure, new ChunkPos(block.getX() >> 4, block.getZ() >> 4), 0, + new PiecesContainer(List.of(new Piece(box)))); + } + level.entities.clear(); + level.levelRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0"))); + put(level, Level.class, "random", level.levelRandom); + created = new ArrayList<>(); + entitySeed = Long.parseLong(c.getOrDefault("eseed", "0")); + seeding = true; + // Chickens already standing by (zombie jockeys look for one). + int chickens = Integer.parseInt(c.getOrDefault("chickens", "0")); + for (int i = 0; i < chickens; i++) { + Entity chicken = EntityTypes.CHICKEN.create(level, EntitySpawnReason.LOAD); + chicken.setPos(x + i, y, z); + level.entities.add(chicken); + } + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type"))); + EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "NATURAL")); + float moon = DimensionType.MOON_BRIGHTNESS_PER_PHASE[phase]; + DifficultyInstance difficulty = new DifficultyInstance(level.difficulty, level.time, Long.parseLong(c.getOrDefault("inhabited", "0")), moon); + int pack = Integer.parseInt(c.getOrDefault("pack", "1")); + SpawnGroupData group = null; + for (int i = 0; i < pack; i++) { + Entity e = type.create(level, reason); + if (e == null) break; // monsters do not exist in peaceful + if (!(e instanceof Mob mob)) throw new IllegalStateException("not a mob"); + mob.snapTo(x, y, z, 0.0F, 0.0F); + group = mob.finalizeSpawn(level, difficulty, reason, group); + level.addFreshEntityWithPassengers(mob); + } + seeding = false; + List out = new ArrayList<>(); + for (Entity e : created) out.add(describe(e, created)); + for (Entity e : created) out.add("rng " + e.getRandom().nextLong()); + out.add("next " + level.levelRandom.nextLong()); + w.println(c.get("name") + " " + String.join(" | ", out)); + } catch (Throwable t) { + seeding = false; + Throwable cause = t; + while ((cause instanceof InvocationTargetException || cause instanceof RuntimeException && cause.getCause() != null) && cause.getCause() != null) cause = cause.getCause(); + StringBuilder line = new StringBuilder(c.get("name") + " error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame); + w.println(line); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_finalize_spawn_parity.py b/tools/test_finalize_spawn_parity.py new file mode 100644 index 000000000..23948d7b9 --- /dev/null +++ b/tools/test_finalize_spawn_parity.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Compare Mob.finalizeSpawn (spawned mob gear, enchantments and state) with vanilla. + +Java (VanillaFinalizeSpawnOracle) creates each case's mobs on a stand-in +ServerLevel and runs vanilla's finalizeSpawn with a seeded level random (what +finalizeSpawn reads through level.getRandom()) and seeded entity randoms; Rust +(finalize_spawn_fixture) runs horizon_client::mobs::finalize on the same case. +Cases cover every mob type, every spawn reason, peaceful to hard, game times, +inhabited times and moon phases (the local difficulty and its special +multiplier), packs sharing group data, biomes (variants, villager types, +sheep colours, rabbit and fox types), structures (black cats), roofs (camel +husk room) and chickens standing by (zombie jockeys). + +Each entity created in a case, the mobs and the jockeys finalizeSpawn makes, +is compared: equipment with its enchantments, drop chances, CanPickUpLoot, +LeftHanded, persistence, age, health, attribute values, effects, variants, +the memories finalizeSpawn sets and the vehicle it rides; then the next draw +of every entity random and of the level random, which pins every draw in +between. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +REASONS = ['NATURAL', 'CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'BREEDING', 'MOB_SUMMONED', 'JOCKEY', 'EVENT', + 'CONVERSION', 'REINFORCEMENT', 'TRIGGERED', 'BUCKET', 'SPAWN_ITEM_USE', 'COMMAND', 'DISPENSER', 'PATROL', + 'TRIAL_SPAWNER', 'LOAD', 'DIMENSION_TRAVEL'] +# Mobs whose finalizeSpawn draws, by how often the corpus picks them. +GEARED = ['zombie', 'husk', 'drowned', 'zombie_villager', 'zombified_piglin', 'skeleton', 'stray', 'bogged', 'parched', + 'wither_skeleton', 'pillager', 'vindicator', 'piglin', 'piglin_brute', 'vex', 'fox', 'spider', 'illusioner', + 'evoker', 'ravager', 'witch'] +OTHERS = ['pig', 'cow', 'mooshroom', 'sheep', 'chicken', 'rabbit', 'horse', 'donkey', 'mule', 'llama', 'trader_llama', + 'goat', 'panda', 'polar_bear', 'wolf', 'cat', 'ocelot', 'parrot', 'bee', 'turtle', 'armadillo', 'frog', + 'axolotl', 'squid', 'glow_squid', 'cod', 'salmon', 'tropical_fish', 'pufferfish', 'dolphin', 'bat', 'villager', + 'wandering_trader', 'iron_golem', 'snow_golem', 'creeper', 'cave_spider', 'enderman', 'endermite', + 'silverfish', 'slime', 'magma_cube', 'phantom', 'hoglin', 'zoglin', 'ghast', 'blaze', 'strider', 'guardian', + 'elder_guardian', 'shulker', 'camel', 'allay', 'breeze', 'sniffer', 'happy_ghast', 'warden', 'creaking', + 'camel_husk', 'nautilus', 'zombie_nautilus', 'sulfur_cube', 'zombie_horse', 'skeleton_horse', 'tadpole', + 'giant', 'wither'] +BIOMES = ['minecraft:plains', 'minecraft:desert', 'minecraft:snowy_plains', 'minecraft:snowy_taiga', 'minecraft:taiga', + 'minecraft:jungle', 'minecraft:bamboo_jungle', 'minecraft:swamp', 'minecraft:mangrove_swamp', + 'minecraft:savanna', 'minecraft:badlands', 'minecraft:forest', 'minecraft:grove', 'minecraft:old_growth_pine_taiga', + 'minecraft:old_growth_spruce_taiga', 'minecraft:sparse_jungle', 'minecraft:windswept_savanna', + 'minecraft:mushroom_fields', 'minecraft:river', 'minecraft:frozen_river', 'minecraft:ocean', + 'minecraft:warm_ocean', 'minecraft:lukewarm_ocean', 'minecraft:cold_ocean', 'minecraft:frozen_ocean', + 'minecraft:ice_spikes', 'minecraft:cherry_grove', 'minecraft:pale_garden', 'minecraft:dripstone_caves', + 'minecraft:lush_caves', 'minecraft:deep_dark', 'minecraft:nether_wastes', 'minecraft:crimson_forest', + 'minecraft:soul_sand_valley', 'minecraft:the_end', 'minecraft:snowy_slopes', 'minecraft:frozen_peaks', + 'minecraft:wooded_badlands', 'minecraft:beach', 'minecraft:snowy_beach', 'minecraft:meadow', + 'minecraft:sulfur_caves'] +STRUCTURES = ['minecraft:swamp_hut', 'minecraft:village_plains', 'minecraft:pillager_outpost', 'minecraft:fortress', + 'minecraft:trial_chambers'] +FLOORS = ['minecraft:grass_block', 'minecraft:sand', 'minecraft:stone', 'minecraft:snow_block', 'minecraft:netherrack'] + + +def dimension(biome): + if biome in ('minecraft:nether_wastes', 'minecraft:crimson_forest', 'minecraft:soul_sand_valley'): + return 'minecraft:the_nether' + if biome == 'minecraft:the_end': + return 'minecraft:the_end' + return 'minecraft:overworld' + + +def corpus(): + rng = random.Random(0x46494E414C) + cases = [] + for k in range(int(os.environ.get('FINALIZE_SPAWN_CASES', '24000'))): + kind = rng.choice(GEARED) if rng.random() < 0.55 else rng.choice(OTHERS) + reason = rng.choice(['NATURAL'] * 10 + ['CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'COMMAND', 'SPAWN_ITEM_USE', + 'TRIAL_SPAWNER', 'PATROL', 'EVENT', 'JOCKEY'] * 2 + REASONS) + biome = rng.choice(BIOMES) + kv = { + 'type': f'minecraft:{kind}', + 'reason': reason, + 'difficulty': rng.choice(['hard', 'hard', 'normal', 'normal', 'easy', 'peaceful']), + 'time': rng.choice([0, 0, 50000, 72000, 400000, 800000, 1512000, 3000000, rng.randrange(0, 4000000)]), + 'inhabited': rng.choice([0, 0, 0, 100000, 1000000, 3600000, 5000000, rng.randrange(0, 4000000)]), + 'phase': rng.randrange(8), + 'seed': rng.randrange(-2**63, 2**63), + 'eseed': rng.randrange(-2**47, 2**47), + 'pack': rng.choice([1, 1, 1, 2, 3, 4, 6]), + 'pos': f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.25, 0.0]):.2f},{rng.randrange(-30, 120)},' + f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.75, 0.0]):.2f}', + 'biome': biome, + 'dim': dimension(biome), + 'floor': rng.choice(FLOORS), + } + if rng.random() < 0.15: + kv['structure'] = rng.choice(STRUCTURES) + if rng.random() < 0.2: + kv['roof'] = rng.choice([1, 2, 3]) + if rng.random() < 0.15: + kv['chickens'] = rng.choice([1, 2]) + if rng.random() < 0.05: + kv['monsters'] = 0 + cases.append(f'case/{k} ' + ' '.join(f'{a}={b}' for a, b in kv.items())) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + parser.add_argument('--java-only', action='store_true', help='run the oracle and stop') + args = parser.parse_args() + build = lab.LOCAL / 'rust-finalize-spawn-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs'] + tested = base.source_hashes([s for s in sources if s.exists()]) + inputs = build / 'inputs.txt' + cases = corpus() + inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + path = build / (name + '.log') + with path.open('w', encoding='utf-8') as log: + try: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError: + log.flush() + raise SystemExit(f'{name} failed:\n' + path.read_text(errors='replace')[-4000:]) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaFinalizeSpawnOracle', inputs, build / 'server.txt'], 'server') + vanilla = (build / 'server.txt').read_text().splitlines() + errors = [l for l in vanilla if ' error ' in l] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + if args.java_only: + print(f'{len(vanilla)} oracle lines') + return + halloween = vanilla[0].split()[1] + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples/finalize_spawn_fixture' + run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust') + rust = (build / 'rust.txt').read_text().splitlines() + bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] + if bad or len(vanilla) != len(rust): + report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12]) + raise SystemExit(f'{len(bad)} of {len(vanilla)} lines differ (rust {len(rust)} lines):\n{report}') + base.ensure_sources_unchanged([s for s in sources if s.exists()], tested) + entities = sum(line.count(' | ') for line in vanilla) // 2 + enchanted = sum(line.count('[minecraft:') for line in vanilla) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'entities': entities, 'enchanted_items': enchanted, 'sources_sha256': tested, + 'scope': 'Mob.finalizeSpawn for every mob type and spawn reason: populateDefaultEquipmentSlots, ' + 'populateDefaultEquipmentEnchantments through the mob_spawn_equipment and pillager_spawn_crossbow ' + 'providers, drop chances, CanPickUpLoot, LeftHanded, the follow range spawn bonus, babies and ' + 'group data, jockeys (chicken, spider, strider, zombie horse, camel husk, zombie nautilus), ' + 'variants and sound variants, zombie attributes, spider effects, patrol leaders, villager types, ' + 'cube sizes, horse and llama attributes and the memories finalizeSpawn sets, with every draw of the ' + 'level random and of the entities\' own randoms.'}) + print(f'{len(cases):,} finalizeSpawn cases match vanilla ({entities:,} entities, {enchanted:,} enchanted items)') + + +if __name__ == '__main__': + main() From df0c1ad36e72fcb905bd4b58eaff680218ceeb54 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:16:52 +0200 Subject: [PATCH 03/14] Seed a summoned warden before its first tick, and keep its heartbeat off the server random The shrieker summons the warden during the block ticks, so it ticks in the same tick's entity phase: the oracle and the fixture now seed it (its random, sensor delays and RunOne shuffles) before that phase, not after. The heartbeat is a client sound: its pitch no longer draws from the level random, and the fixture leaves it out as vanilla's server never sends it. sculk: 435/435. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 5 +- .../horizon-client/src/game/sculk_fixture.rs | 50 ++++++++++++++--- crates/horizon-client/src/mobs/warden.rs | 5 +- .../horizon-client/src/mobs/warden_brain.rs | 56 ++++++++++++++----- .../horizonlab/parity/VanillaSculkOracle.java | 42 +++++++++++--- 5 files changed, 128 insertions(+), 30 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 94231b9be..d7f710d40 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -698,7 +698,10 @@ impl Game<'_> { volume, spread, } => { - let r = &mut self.world.random; + // The client's own level random: nothing drawn from the server's. + let mut r = horizon_core::random::LegacyRandom::new( + self.world.game_time.wrapping_mul(341_873_128_712), + ); let pitch = (r.next_float() - r.next_float()) * spread + 1.0; self.audio .play(&format!("minecraft:{sound}"), Some(at), volume, pitch) diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 740d42e93..2cdb820b0 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -130,6 +130,13 @@ fn parse(text: &str) -> Vec { out } +/// An entity's own random is unseeded in vanilla, and so are its sensors' +/// first delays and its brain's `RunOne` shuffles: the oracle seeds what +/// appeared, and so does this. +fn seed_fresh(m: &mut Mob, seed: i64) { + m.random = LegacyRandom::new(seed); + horizon_client::mobs::warden::init_brain(m, seed); +} fn d(v: f64) -> String { format!("{:x}", v.to_bits()) } @@ -138,10 +145,12 @@ fn f(v: f32) -> String { } /// Sounds the client plays for level events (3006 sculk charge, 3007 -/// shriek): vanilla's server never sends them. +/// shriek) and for itself (the warden's heartbeat): vanilla's server never +/// sends them. const CLIENT_SOUNDS: &[&str] = &[ "minecraft:block.sculk_shrieker.shriek", "minecraft:block.sculk.charge", + "minecraft:entity.warden.heartbeat", ]; impl Game<'_> { @@ -469,6 +478,7 @@ impl Game<'_> { self.world.random = LegacyRandom::new(s.level_seed); self.audio.capture = Some(Vec::new()); let mut known: HashSet = self.mobs.iter().map(|m| m.id).collect(); + let mut seeded: HashSet = HashSet::new(); let mut known_items = self.dropped.len(); let mut known_orbs = self.orbs.len(); let mut last: HashMap<[i32; 3], String> = HashMap::new(); @@ -478,7 +488,7 @@ impl Game<'_> { for t in 0..=s.ticks { dispense_fixture::start_recording(); if t > 0 { - self.sculk_fixture_tick(t, s, &sources)?; + self.sculk_fixture_tick(t, s, &sources, &known, names.len(), &mut seeded)?; } let mut lines: Vec = Vec::new(); for p in &s.watch { @@ -540,12 +550,11 @@ impl Game<'_> { for (id, line) in fresh { known.insert(id); names.insert(id, format!("n{}", names.len())); - // An entity's own random is unseeded in vanilla: the oracle - // seeds what appeared, and so does this. let seed = 0x5eed + names.len() as i64; - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - m.random = LegacyRandom::new(seed); - horizon_client::mobs::warden::delay_sensors(m); + if seeded.insert(id) { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + seed_fresh(m, seed); + } } lines.push(line); } @@ -599,7 +608,15 @@ impl Game<'_> { } /// One `ServerLevel.tick` of a scenario. - fn sculk_fixture_tick(&mut self, t: i32, s: &Scenario, sources: &[u32]) -> Result<()> { + fn sculk_fixture_tick( + &mut self, + t: i32, + s: &Scenario, + sources: &[u32], + known: &HashSet, + named: usize, + seeded: &mut HashSet, + ) -> Result<()> { self.world.game_time += 1; // Scheduled block and fluid ticks, then block events. self.tick_scheduled()?; @@ -662,6 +679,23 @@ impl Game<'_> { other => return Err(format!("unknown action {other}").into()), } } + // Mobs that appeared during the block ticks (a summoned warden) tick + // in this tick's entity phase: seed them now, as they are seeded + // after the tick. + let mut born: Vec = self + .mobs + .iter() + .map(|m| m.id) + .filter(|id| !known.contains(id)) + .collect(); + born.sort_unstable(); + for (i, id) in born.into_iter().enumerate() { + if seeded.insert(id) { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + seed_fresh(m, 0x5eed + (named + i + 1) as i64); + } + } + } // Entities: the player's warden spawn tracker, then the mobs. self.tick_sculk_entities(); // (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.) diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 44ef96dd0..546952d9c 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -523,7 +523,10 @@ pub fn server_ai_step( .extra .warden .as_mut() - .map(|st| st.vibration.tick(w.game_time, true, false, |d| d.floor() as i32)) + .map(|st| { + st.vibration + .tick(w.game_time, true, false, |d| d.floor() as i32) + }) .unwrap_or_default(); if let Some((info, travel)) = tick.started { let eye = [m.position.x, m.position.y + m.kind.eye_height, m.position.z]; diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index a513bd6b7..a79fe1477 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -324,23 +324,43 @@ fn activities(seed: i64) -> Vec { speed: 0.0, }, ), - (5, Act::Emerge, B::Emerging(Timed::new(EMERGE_DURATION, EMERGE_DURATION))), + ( + 5, + Act::Emerge, + B::Emerging(Timed::new(EMERGE_DURATION, EMERGE_DURATION)), + ), (0, Act::Dig, B::ForceUnmount(Timed::new(60, 60))), - (1, Act::Dig, B::Digging(Timed::new(DIGGING_DURATION, DIGGING_DURATION))), + ( + 1, + Act::Dig, + B::Digging(Timed::new(DIGGING_DURATION, DIGGING_DURATION)), + ), (10, Act::Idle, B::SetRoarTarget(false)), (11, Act::Idle, B::TryToSniff(false)), (12, Act::Idle, B::RunOne(Box::new(gate))), - (10, Act::Roar, B::Roar(Timed::new(ROAR_DURATION, ROAR_DURATION))), + ( + 10, + Act::Roar, + B::Roar(Timed::new(ROAR_DURATION, ROAR_DURATION)), + ), (10, Act::Fight, B::DigCooldownSetter(false)), (11, Act::Fight, B::StopAttackingIfTargetInvalid(false)), (12, Act::Fight, B::SetEntityLookTarget(false)), (13, Act::Fight, B::SetWalkTargetFromAttackTarget(false)), - (14, Act::Fight, B::SonicBoom(Timed::new(SONIC_DURATION, SONIC_DURATION))), + ( + 14, + Act::Fight, + B::SonicBoom(Timed::new(SONIC_DURATION, SONIC_DURATION)), + ), (15, Act::Fight, B::MeleeAttack(false)), (5, Act::Investigate, B::SetRoarTarget(false)), (6, Act::Investigate, B::GoToDisturbance(false)), (5, Act::Sniff, B::SetRoarTarget(false)), - (6, Act::Sniff, B::Sniffing(Timed::new(SNIFFING_DURATION, SNIFFING_DURATION))), + ( + 6, + Act::Sniff, + B::Sniffing(Timed::new(SNIFFING_DURATION, SNIFFING_DURATION)), + ), ]; // A stable sort keeps each activity's own order. list.sort_by_key(|(prio, act, _)| (*prio, act.slot(), act.order())); @@ -561,7 +581,8 @@ pub(super) fn set_disturbance(m: &mut Mob, w: &MobWorld, position: [i32; 3]) { mm.sniff_cooldown.set_ttl((), DISTURBANCE_EXPIRY); mm.look_target .set_ttl(Tracker::Block(position), DISTURBANCE_EXPIRY); - mm.disturbance_location.set_ttl(position, DISTURBANCE_EXPIRY); + mm.disturbance_location + .set_ttl(position, DISTURBANCE_EXPIRY); mm.walk_target.clear(); } /// `Warden.setAttackTarget`. @@ -977,10 +998,9 @@ impl B { let Some(target) = mm.attack_target.value() else { return false; }; - let close = cx - .w - .target_info(target) - .is_some_and(|i| closer_than(m, i.position, 15.0, 20.0)); + let close = + cx.w.target_info(target) + .is_some_and(|i| closer_than(m, i.position, 15.0, 20.0)); if !close { return false; } @@ -1288,7 +1308,11 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { let unit = |_: &()| "u".to_string(); let list = |l: &Vec| format!("n{}", l.len()); slot!("nearest_players", mm.nearest_players, list); - slot!("nearest_visible_player", mm.nearest_visible_player, |e: &Who| who(*e)); + slot!( + "nearest_visible_player", + mm.nearest_visible_player, + |e: &Who| who(*e) + ); slot!( "nearest_visible_targetable_player", mm.nearest_visible_targetable_player, @@ -1303,7 +1327,9 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { "NearestVisibleLivingEntities".to_string() }); - slot!("nearest_attackable", mm.nearest_attackable, |e: &Who| who(*e)); + slot!("nearest_attackable", mm.nearest_attackable, |e: &Who| who( + *e + )); slot!("look_target", mm.look_target, |t: &Tracker| tracker(*t)); slot!("walk_target", mm.walk_target, |t: &WalkTarget| format!( "{}/{:x}/{}", @@ -1336,7 +1362,11 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { slot!("touch_cooldown", mm.touch_cooldown, unit); slot!("vibration_cooldown", mm.vibration_cooldown, unit); slot!("sonic_boom_cooldown", mm.sonic_boom_cooldown, unit); - slot!("sonic_boom_sound_cooldown", mm.sonic_boom_sound_cooldown, unit); + slot!( + "sonic_boom_sound_cooldown", + mm.sonic_boom_sound_cooldown, + unit + ); slot!("sonic_boom_sound_delay", mm.sonic_boom_sound_delay, unit); out.sort(); Some((acts.join("|"), out.join(" "))) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java index 137d7a4a3..3b9127379 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java @@ -269,6 +269,32 @@ public final class VanillaSculkOracle { static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); } + /** + * A mob's own random, its sensors' first delays and its gates' shuffles (RunOne's ShufflingList) + * are unseeded: seed what appeared, as Horizon does. + */ + static void seedFresh(Mob mob, long seed) throws Exception { + mob.getRandom().setSeed(seed); + @SuppressWarnings("unchecked") + Map> sensors = + (Map>) get(mob.getBrain(), "sensors"); + for (var sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); + @SuppressWarnings("unchecked") + Map>>> byPriority = + (Map>>>) get(mob.getBrain(), "availableBehaviorsByPriority"); + for (var byActivity : byPriority.values()) + for (var behaviors : byActivity.values()) + for (var behavior : behaviors) seedGate(behavior, seed); + } + + static void seedGate(Object behavior, long seed) throws Exception { + if (!(behavior instanceof net.minecraft.world.entity.ai.behavior.GateBehavior)) return; + var list = (net.minecraft.world.entity.ai.behavior.ShufflingList) + field(net.minecraft.world.entity.ai.behavior.GateBehavior.class, "behaviors").get(behavior); + field(net.minecraft.world.entity.ai.behavior.ShufflingList.class, "random").set(list, new LegacyRandomSource(seed)); + for (Object child : list) seedGate(child, seed); + } + static long seedOf(Object random) throws Exception { return ((java.util.concurrent.atomic.AtomicLong) field(LegacyRandomSource.class, "seed").get(random)).get(); } @@ -538,6 +564,7 @@ public final class VanillaSculkOracle { Method managerTick = method(manager.getClass(), "tick"); managerTick.invoke(manager); Set known = new HashSet<>(); + Set seeded = new HashSet<>(); for (Entity e : allEntities(level)) known.add(e); if (System.getenv("SCULK_TRACE") != null) field(Level.class, "random").set(level, new TracingRandom(0L)); level.getRandom().setSeed(s.levelSeed); @@ -563,6 +590,13 @@ public final class VanillaSculkOracle { }); runBlockEvents.invoke(level); for (Action a : s.actions) if (a.tick == t) act(level, a.words, mobs); + // Mobs that appeared during the block ticks (a summoned warden) tick in this + // tick's entity phase: seed them now, as they are seeded below. + List born = new ArrayList<>(); + for (Entity e : allEntities(level)) if (!known.contains(e)) born.add(e); + born.sort(Comparator.comparingInt(Entity::getId)); + for (int i = 0; i < born.size(); i++) + if (born.get(i) instanceof Mob mob && seeded.add(mob)) seedFresh(mob, 0x5eedL + names.size() + i + 1); // The player first (it joined first): only its warden spawn tracker. player.getWardenSpawnTracker().tick(); tickList.forEach(e -> { @@ -611,13 +645,7 @@ public final class VanillaSculkOracle { known.add(e); names.put(e, "n" + names.size()); // An entity's own random is unseeded: seed what appeared, as Horizon does. - if (e instanceof Mob mob) { - mob.getRandom().setSeed(0x5eedL + names.size()); - @SuppressWarnings("unchecked") - Map> sensors = - (Map>) get(mob.getBrain(), "sensors"); - for (var sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); - } + if (e instanceof Mob mob && seeded.add(mob)) seedFresh(mob, 0x5eedL + names.size()); if (e instanceof net.minecraft.world.entity.ExperienceOrb orb) { // Where an orb flies comes from its own unseeded random: its value only. lines.add("new minecraft:experience_orb value=" + orb.getValue()); From 1ea26de544644fabed9c1b2c6ef53612a474e856 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:47:25 +0200 Subject: [PATCH 04/14] Match finalizeSpawn for every case of the harness A zombie villager's profession comes from its constructor's random, not the one finalizeSpawn draws from. Allays and withers are no longer marked persistent to escape despawning: they are kept as removeWhenFarAway and the wither's checkDespawn keep them, and canPickUpLoot follows the allay's and the sulfur cube's overrides. A sulfur cube's size sets its attribute bases, and strength and speed effects count in attribute values. The oracle's stand-in level gets the sound seed random Level.playSound draws from. Co-Authored-By: Claude Opus 5.5 --- .../examples/finalize_spawn_fixture.rs | 69 ++++++++-- crates/horizon-client/src/entity_nbt.rs | 2 +- crates/horizon-client/src/mobs.rs | 15 ++- crates/horizon-client/src/mobs/ai.rs | 11 +- crates/horizon-client/src/mobs/allay.rs | 1 - crates/horizon-client/src/mobs/aquatic.rs | 5 +- crates/horizon-client/src/mobs/finalize.rs | 126 +++++++++++++++--- crates/horizon-client/src/mobs/wither.rs | 1 - .../parity/VanillaFinalizeSpawnOracle.java | 6 +- 9 files changed, 191 insertions(+), 45 deletions(-) diff --git a/crates/horizon-client/examples/finalize_spawn_fixture.rs b/crates/horizon-client/examples/finalize_spawn_fixture.rs index 0e9aa9a5a..9b1ba4f38 100644 --- a/crates/horizon-client/examples/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/finalize_spawn_fixture.rs @@ -74,7 +74,10 @@ impl FinalizeLevel for Level<'_> { fn no_collision(&self, bounds: Aabb) -> bool { // A floor under the spawn point and an optional roof layer. self.roof.is_none_or(|y| { - let (lo, hi) = (bounds.min(horizon_core::geometry::Axis::Y), bounds.max(horizon_core::geometry::Axis::Y)); + let (lo, hi) = ( + bounds.min(horizon_core::geometry::Axis::Y), + bounds.max(horizon_core::geometry::Axis::Y), + ); !(lo < f64::from(y) + 1.0 && hi > f64::from(y)) }) } @@ -115,13 +118,29 @@ fn hex64(v: f64) -> String { fn hex32(v: f32) -> String { format!("{:x}", v.to_bits()) } -const HORSE: [&str; 7] = ["white", "creamy", "chestnut", "brown", "black", "gray", "dark_brown"]; +const HORSE: [&str; 7] = [ + "white", + "creamy", + "chestnut", + "brown", + "black", + "gray", + "dark_brown", +]; const MARKINGS: [&str; 5] = ["none", "white", "white_field", "white_dots", "black_dots"]; const RABBITS: [&str; 6] = ["brown", "white", "black", "white_splotched", "gold", "salt"]; const PARROTS: [&str; 5] = ["red_blue", "blue", "green", "yellow_blue", "gray"]; const AXOLOTLS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"]; const SALMON: [&str; 3] = ["small", "medium", "large"]; -const GENES: [&str; 7] = ["normal", "lazy", "worried", "playful", "brown", "weak", "aggressive"]; +const GENES: [&str; 7] = [ + "normal", + "lazy", + "worried", + "playful", + "brown", + "weak", + "aggressive", +]; const MEMORIES: [&str; 7] = [ "long_jump_cooldown", "ram_cooldown", @@ -136,7 +155,10 @@ fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) { use Species as S; let s = m.species(); let named = |reg: &finalize::VariantRegistry, i: u8| { - format!("minecraft:{}", reg.names.get(i as usize).map_or("?", |n| n.as_str())) + format!( + "minecraft:{}", + reg.names.get(i as usize).map_or("?", |n| n.as_str()) + ) }; let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant)); match s { @@ -212,7 +234,9 @@ fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) { S::Phantom => v.push(format!("size={}", m.extra.size)), S::Turtle => v.push(format!( "home={}", - m.extra.home.map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2])) + m.extra + .home + .map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2])) )), S::Dolphin => v.push(format!("air={}", m.air)), _ => {} @@ -252,7 +276,7 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { } t.push(format!("hp={}", hex32(m.health))); t.push(format!("lh={}", m.extra.left_handed)); - t.push(format!("loot={}", m.extra.pick_up_loot)); + t.push(format!("loot={}", m.can_pick_up_loot())); t.push(format!("persist={}", m.persistent)); let mut eq = Vec::new(); for (slot, name) in finalize::SLOT_NAMES.iter().enumerate() { @@ -284,7 +308,14 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { } eq.push(format!("{name}:{text}")); } - t.push(format!("eq={}", if eq.is_empty() { "-".into() } else { eq.join(";") })); + t.push(format!( + "eq={}", + if eq.is_empty() { + "-".into() + } else { + eq.join(";") + } + )); let drops: Vec = finalize::SLOT_NAMES .iter() .enumerate() @@ -295,7 +326,11 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { .collect(); t.push(format!( "drop={}", - if drops.is_empty() { "-".into() } else { drops.join(";") } + if drops.is_empty() { + "-".into() + } else { + drops.join(";") + } )); let attrs: Vec = [ Attr::MaxHealth, @@ -318,7 +353,14 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { .map(|(e, d, a)| format!("{e}:{a}:{d}")) .collect(); fx.sort(); - t.push(format!("fx={}", if fx.is_empty() { "-".into() } else { fx.join(",") })); + t.push(format!( + "fx={}", + if fx.is_empty() { + "-".into() + } else { + fx.join(",") + } + )); let mem: Vec = MEMORIES .iter() .filter_map(|name| { @@ -380,13 +422,18 @@ fn main() -> horizon_client::Result<()> { None => name = token, } } - let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let get = + |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; let p: Vec = get("pos", "0,0,0") .split(',') .map(|x| x.parse().unwrap_or(0.0)) .collect(); let pos = Vec3::new(p[0], p[1], p[2]); - let block = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32]; + let block = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; let base = match get("difficulty", "normal").as_str() { "peaceful" => 0, "easy" => 1, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index b0fa1cc3b..6745c5335 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -140,7 +140,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, value) in [ ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), - ("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))), + ("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))), ("LeftHanded", Tag::Byte(0)), ( "Brain", diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 612cf14e6..b7414d3c5 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1215,14 +1215,14 @@ impl Mob { }, kind, }; - // setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay, - // Dolphin, Fox and Panda constructors. + // setCanPickUpLoot(true) in the Villager, AbstractPiglin, Dolphin, + // Fox and Panda constructors (an allay's is false until it holds + // something: it overrides canPickUpLoot). mob.extra.pick_up_loot = matches!( mob.species(), Species::Villager | Species::Piglin | Species::PiglinBrute - | Species::Allay | Species::Dolphin | Species::Fox | Species::Panda @@ -1230,6 +1230,15 @@ impl Mob { ai::register(&mut mob); mob } + /// `Mob.canPickUpLoot`, with the overrides: an allay that holds + /// something off its pickup cooldown, a sulfur cube with no block. + pub fn can_pick_up_loot(&self) -> bool { + match self.species() { + Species::Allay => self.extra.main_hand.is_some() && self.extra.ints[3] <= 0, + Species::SulfurCube => !sulfur_cube::has_body(self), + _ => self.extra.pick_up_loot, + } + } pub fn bounds(&self) -> Aabb { let w = f64::from(self.width()) / 2.0; Aabb::new( diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 9c825d61b..8d6c728fd 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -895,11 +895,14 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { || super::nautilus::is_nautilus(m.species()) && m.extra.tame || m.species() == Species::SulfurCube && (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. + // removeWhenFarAway: animals, wardens, allays, patrols and raiders, + // zombie villagers being cured and ridden mobs stay; the wither's + // checkDespawn never removes it for distance. let creature = m.kind.category == "creature"; - let removable = !(m.species() == Species::Warden - || creature && m.kind.flags.animal && !m.extra.jockey + let removable = !(matches!( + m.species(), + Species::Warden | Species::Allay | Species::Wither + ) || 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)); diff --git a/crates/horizon-client/src/mobs/allay.rs b/crates/horizon-client/src/mobs/allay.rs index 2b674fb87..3c25053ba 100644 --- a/crates/horizon-client/src/mobs/allay.rs +++ b/crates/horizon-client/src/mobs/allay.rs @@ -27,7 +27,6 @@ pub fn register(m: &mut Mob) { m.ai.nav.kind = NavKind::Flying; // FlyingPathNavigation.setRequiredPathLength(48). m.ai.nav.required_path_length = 48.0; - m.persistent = true; let g = &mut m.ai.goals; g.add(0, Panic::new(2.5)); g.add(1, Fetch); diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index cdcd13000..8cb1f7873 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -473,7 +473,10 @@ pub const COMMON_TROPICAL: [(u8, u8, u8); 22] = [ pub fn finalize(m: &mut Mob) { if m.species() == Species::TropicalFish { let (p, b, c) = if m.random.next_float() < 0.9 { - COMMON_TROPICAL[m.random.next_int_bound(COMMON_TROPICAL.len() as i32).unwrap_or(0) as usize] + COMMON_TROPICAL[m + .random + .next_int_bound(COMMON_TROPICAL.len() as i32) + .unwrap_or(0) as usize] } else { ( m.random.next_int_bound(12).unwrap_or(0) as u8, diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 8e5992260..ac1027098 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -21,7 +21,10 @@ //! `sound_variant` the index in the species' sound variant registry. use super::{Mob, Species, farm::Climate, gear, spawning::LocalDifficulty}; use crate::{enchant::Enchantments, items::Items}; -use horizon_core::{geometry::Aabb, random::RandomSource}; +use horizon_core::{ + geometry::Aabb, + random::{LegacyRandom, RandomSource}, +}; use serde_json::Value; use std::{fs, path::Path, sync::Arc}; @@ -490,6 +493,23 @@ fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { _ => None, } } +/// The attribute modifiers of the mob's effects (`MobEffect.addAttributeModifier`, +/// scaled by the amplifier plus one): strength and speed. +fn effect_modifiers(m: &Mob, a: Attr) -> impl Iterator + '_ { + m.extra + .effects + .iter() + .filter_map(move |&(effect, _, amplifier)| { + let level = f64::from(amplifier + 1); + match (effect.trim_start_matches("minecraft:"), a) { + ("strength", Attr::AttackDamage) => Some((3.0 * level, Op::AddValue)), + ("speed", Attr::MovementSpeed) => { + Some((f64::from(0.2f32) * level, Op::AddMultipliedTotal)) + } + _ => None, + } + }) +} /// `AttributeInstance.getValue`: the base, then the modifiers by operation. pub fn value(m: &Mob, a: Attr) -> f64 { compute(m, a, true) @@ -503,8 +523,9 @@ fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 { .filter(|x| x.attr == a) .map(|x| (x.amount, x.op)) .collect(); - if with_transient && let Some(t) = transient(m, a) { - ops.push(t); + if with_transient { + ops.extend(transient(m, a)); + ops.extend(effect_modifiers(m, a)); } for (amount, op) in &ops { if *op == Op::AddValue { @@ -523,7 +544,11 @@ fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 { } } let (lo, hi) = a.range(); - if result.is_nan() { lo } else { result.clamp(lo, hi) } + if result.is_nan() { + lo + } else { + result.clamp(lo, hi) + } } /// Copies the attribute values into the fields the game reads. fn refresh(m: &mut Mob, a: Attr) { @@ -719,7 +744,7 @@ fn age_boundary_reached(m: &mut Mob) { match m.species() { Species::Goat => set_base(m, Attr::AttackDamage, if baby { 1.0 } else { 2.0 }), Species::Hoglin => set_base(m, Attr::AttackDamage, if baby { 0.5 } else { 6.0 }), - Species::SulfurCube if !baby => super::sulfur_cube::set_size(m, 2, true), + Species::SulfurCube if !baby => sulfur_size(m, 2), _ => {} } } @@ -875,7 +900,14 @@ impl Ctx<'_, L, R> { } } let partial = if self.difficulty.hard { 0.1 } else { 0.25 }; - const MATERIAL: [&str; 6] = ["leather", "copper", "golden", "chainmail", "iron", "diamond"]; + const MATERIAL: [&str; 6] = [ + "leather", + "copper", + "golden", + "chainmail", + "iron", + "diamond", + ]; let mut first = true; // EQUIPMENT_POPULATION_ORDER: head, chest, legs, feet. for (slot, piece) in [ @@ -1095,7 +1127,8 @@ impl Ctx<'_, L, R> { m.extra.passenger = true; } } else if f64::from(self.float()) < 0.05 - && let Some(mut chicken) = self.create("minecraft:chicken", Reason::Jockey, m) + && let Some(mut chicken) = + self.create("minecraft:chicken", Reason::Jockey, m) { self.finalize(&mut chicken, Reason::Jockey, None); chicken.extra.jockey = true; @@ -1125,7 +1158,8 @@ impl Ctx<'_, L, R> { let knockback = r.next_double() * f64::from(0.05f32); let follow = r.next_double() * 1.5 * f64::from(special); let leader = r.next_float() < special * 0.05; - let leader_rolls = leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); + let leader_rolls = + leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); set_base(m, Attr::SpawnReinforcements, reinforcements); add_modifier( m, @@ -1192,7 +1226,11 @@ impl Ctx<'_, L, R> { let (w, h) = self.data.camel_husk_size; let half = w / 2.0; let bounds = Aabb::new( - horizon_core::geometry::Vec3::new(bx + 0.5 - f64::from(half), by, bz + 0.5 - f64::from(half)), + horizon_core::geometry::Vec3::new( + bx + 0.5 - f64::from(half), + by, + bz + 0.5 - f64::from(half), + ), horizon_core::geometry::Vec3::new( bx + 0.5 + f64::from(half), by + f64::from(h), @@ -1203,13 +1241,17 @@ impl Ctx<'_, L, R> { *tried = true; if self.float() < 0.1 { set_item(m, MAINHAND, "minecraft:iron_spear"); - if let Some(mut camel) = self.level.create("minecraft:camel_husk", Reason::Natural) { + if let Some(mut camel) = + self.level.create("minecraft:camel_husk", Reason::Natural) + { // setPos: the husk's position, the camel's own rotation. camel.position = m.position; camel.previous = m.position; self.finalize(&mut camel, reason, None); self.ride(m, &mut camel); - if let Some(mut parched) = self.create("minecraft:parched", Reason::Natural, m) { + if let Some(mut parched) = + self.create("minecraft:parched", Reason::Natural, m) + { self.finalize(&mut parched, reason, None); self.ride(&mut parched, &mut camel); self.created.push(camel); @@ -1452,7 +1494,10 @@ impl Ctx<'_, L, R> { let s = m.species(); match s { S::Pig | S::Cow | S::Chicken => { - let (v, sound): (fn(&SpawnRegistries) -> &VariantRegistry, fn(&SpawnRegistries) -> &VariantRegistry) = match s { + let (v, sound): ( + fn(&SpawnRegistries) -> &VariantRegistry, + fn(&SpawnRegistries) -> &VariantRegistry, + ) = match s { S::Pig => (|r| &r.pig, |r| &r.pig_sound), S::Cow => (|r| &r.cow, |r| &r.cow_sound), _ => (|r| &r.chicken, |r| &r.chicken_sound), @@ -1725,7 +1770,7 @@ impl Ctx<'_, L, R> { let g = self.ageable(m, g); if s == S::SulfurCube { let size = if m.is_baby() { 1 } else { 2 }; - super::sulfur_cube::set_size(m, size, true); + sulfur_size(m, size); } else { let mut scale = self.int(3); if scale < 2 && self.float() < 0.5 * self.special() { @@ -1784,7 +1829,13 @@ impl Ctx<'_, L, R> { S::Zombie | S::ZombifiedPiglin => self.zombie(m, g, reason), S::ZombieVillager => { self.villager_type(m); - m.extra.variant2 = m.random.next_int_bound(15).unwrap_or(0) as u8; + // ZombieVillager's constructor picks the profession from the + // fresh entity's random, before anything seeds it: an + // independent draw that leaves the mob's own random alone. + let mut fresh = LegacyRandom::new( + (m.random.state() as i64).wrapping_mul(0x5851_F42D_4C95_7F2D) ^ i64::from(m.id), + ); + m.extra.variant2 = fresh.next_int_bound(15).unwrap_or(0) as u8; self.zombie(m, g, reason) } S::Husk => self.husk(m, g, reason), @@ -1826,7 +1877,12 @@ impl Ctx<'_, L, R> { super::warden::finalize(m, reason == Reason::Triggered, &mut Vec::new()); set_memory(m, "dig_cooldown", 0, 1200); if reason == Reason::Triggered { - set_memory(m, "is_emerging", 0, i64::from(super::warden::EMERGE_DURATION)); + set_memory( + m, + "is_emerging", + 0, + i64::from(super::warden::EMERGE_DURATION), + ); } self.mob(m, g) } @@ -1893,11 +1949,27 @@ pub fn panda_variant(main: u8, hidden: u8) -> u8 { if recessive && main != hidden { 0 } else { main } } /// `AbstractCubeMob.setSize(size, true)` for slimes and magma cubes. +/// `SulfurCube.setSize(size, true)`, with the attribute bases it sets. +fn sulfur_size(m: &mut Mob, size: i32) { + super::sulfur_cube::set_size(m, size, true); + let size = m.extra.size; + set_base(m, Attr::MaxHealth, f64::from(4 * size)); + set_base( + m, + Attr::MovementSpeed, + f64::from(0.2f32 + 0.1f32 * size as f32), + ); + m.health = max_health(m); +} fn cube_size(m: &mut Mob, size: i32) { let size = size.clamp(1, 127); m.extra.size = size; set_base(m, Attr::MaxHealth, f64::from(size * size)); - set_base(m, Attr::MovementSpeed, f64::from(0.2f32 + 0.1f32 * size as f32)); + set_base( + m, + Attr::MovementSpeed, + f64::from(0.2f32 + 0.1f32 * size as f32), + ); set_base(m, Attr::AttackDamage, f64::from(size)); if m.species() == Species::MagmaCube { set_base(m, Attr::Armor, f64::from(size * 3)); @@ -1911,7 +1983,9 @@ pub fn variant_index(s: Species, name: &str) -> u8 { Species::Cat => super::tame::CAT_VARIANTS.iter().position(|v| *v == name), Species::Wolf => super::tame::WOLF_VARIANTS.iter().position(|v| v.0 == name), Species::ZombieNautilus => super::nautilus::VARIANTS.iter().position(|v| *v == name), - _ => ["temperate", "warm", "cold"].iter().position(|v| *v == name), + _ => ["temperate", "warm", "cold"] + .iter() + .position(|v| *v == name), }; i.unwrap_or(0) as u8 } @@ -1921,8 +1995,14 @@ pub fn variant_name(s: Species, index: u8) -> &'static str { match s { Species::Cat => super::tame::CAT_VARIANTS.get(i).copied().unwrap_or("tabby"), Species::Wolf => super::tame::WOLF_VARIANTS.get(i).map_or("pale", |v| v.0), - Species::ZombieNautilus => super::nautilus::VARIANTS.get(i).copied().unwrap_or("temperate"), - _ => ["temperate", "warm", "cold"].get(i).copied().unwrap_or("temperate"), + Species::ZombieNautilus => super::nautilus::VARIANTS + .get(i) + .copied() + .unwrap_or("temperate"), + _ => ["temperate", "warm", "cold"] + .get(i) + .copied() + .unwrap_or("temperate"), } } /// `VillagerType.byBiome` (index into `render::VILLAGER_TYPES`: plains, @@ -1936,8 +2016,12 @@ pub fn villager_type(biome: &str) -> u8 { | "snowy_taiga" | "snowy_plains" | "grove" | "snowy_slopes" | "frozen_peaks" | "jagged_peaks" => 4, "swamp" | "mangrove_swamp" => 5, - "old_growth_spruce_taiga" | "old_growth_pine_taiga" | "windswept_gravelly_hills" - | "windswept_hills" | "taiga" | "windswept_forest" => 6, + "old_growth_spruce_taiga" + | "old_growth_pine_taiga" + | "windswept_gravelly_hills" + | "windswept_hills" + | "taiga" + | "windswept_forest" => 6, _ => 0, } } diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index eda2b76c4..6702686c5 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -28,7 +28,6 @@ pub fn register(m: &mut Mob) { hovers: false, }; m.ai.nav.kind = NavKind::Flying; - m.persistent = true; let g = &mut m.ai.goals; g.add(0, DoNothing); g.add( diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java index 753ebbc54..fa520e409 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java @@ -138,8 +138,8 @@ public final class VanillaFinalizeSpawnOracle { @Override public net.minecraft.world.level.StructureManager structureManager() { return structures; } @Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; } @Override public boolean isSpawningMonsters() { return rules.get(GameRules.SPAWN_MOBS) && rules.get(GameRules.SPAWN_MONSTERS); } - @Override public void playSeededSound(Entity except, double x, double y, double z, Holder sound, SoundSource source, float volume, float pitch, long seed) {} - @Override public void playSeededSound(Entity except, Entity sourceEntity, Holder sound, SoundSource source, float volume, float pitch, long seed) {} + @Override public void playSeededSound(net.minecraft.world.entity.Entity except, double x, double y, double z, Holder sound, SoundSource source, float volume, float pitch, long seed) {} + @Override public void playSeededSound(net.minecraft.world.entity.Entity except, net.minecraft.world.entity.Entity sourceEntity, Holder sound, SoundSource source, float volume, float pitch, long seed) {} @Override public void gameEvent(Holder gameEvent, Vec3 position, net.minecraft.world.level.gameevent.GameEvent.Context context) {} @Override public void broadcastEntityEvent(Entity entity, byte event) {} @SuppressWarnings({"unchecked", "rawtypes"}) @@ -429,6 +429,8 @@ public final class VanillaFinalizeSpawnOracle { level.fake = server; put(level, ServerLevel.class, "server", server); level.registries = access; + // Level.playSound draws a sound seed before the (ignored) seeded sound. + put(level, net.minecraft.world.level.Level.class, "soundSeedGenerator", RandomSource.create(0L)); level.entities = new ArrayList<>(); level.scoreboard = new net.minecraft.server.ServerScoreboard(server); level.border = new WorldBorder(); From 0425843aa8ae6ccb523785672b3e773a4988d6b9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:50:50 +0200 Subject: [PATCH 05/14] Note finalizeSpawn's parity in the README Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 32ecb88c4..a186b804a 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ The client starts on the title screen. Command-line options (`--world`, `--seed` ## Project status -Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, spawned mob gear enchantments, the resource pack screen, a dedicated server mode, and worlds older than 1.17. +Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, the resource pack screen, a dedicated server mode, and worlds older than 1.17. ### Java parity: 88% @@ -134,7 +134,7 @@ 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), spawned mobs' gear, enchantments and state (`finalizeSpawn`, 24,000 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain and villager breeding and gossip 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 | | Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla | @@ -158,7 +158,7 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and ### Roadmap 1. Fix loading at render distance 2; finish the warden's brain and the sculk shrieker summoning it, and the tempted ghastling. -2. Villager breeding and gossip, and spawned mob gear enchantments (both started on their branches). +2. Villager breeding and gossip (started on its branch). 3. A dedicated server mode, and LAN hosting tested with a vanilla client. 4. Save upgrades from before 1.17, and the resource pack screen. 5. Platform-independent float math, so every harness also gives vanilla's results on macOS. From 3f4c39b057284cb3d94d650c0755d649d88e7329 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:52:12 +0200 Subject: [PATCH 06/14] Satisfy clippy Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/finalize.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index ac1027098..0e5a0a2ec 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1877,12 +1877,7 @@ impl Ctx<'_, L, R> { super::warden::finalize(m, reason == Reason::Triggered, &mut Vec::new()); set_memory(m, "dig_cooldown", 0, 1200); if reason == Reason::Triggered { - set_memory( - m, - "is_emerging", - 0, - i64::from(super::warden::EMERGE_DURATION), - ); + set_memory(m, "is_emerging", 0, super::warden::EMERGE_DURATION); } self.mob(m, g) } From 7fdbdcb3cb5568480c3ffc74fc811b37b12083ab Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:06:33 +0200 Subject: [PATCH 07/14] Warden footsteps and hearing, kills in the probe, and the ghastling's fly stroll - Warden.nextStep: a step every 0.55 walked; mob steps raise a step game event, which the mob AI probe delivers to wardens through the listener the game uses (warden::listen). - Warden.tick runs the vibration ticker before super.tick. - The probe applies melee hits on mobs, reads a warden's target from its brain, and plays the player's death sound for a lethal hit; warden_player and warden_cow stop before the killing blow. - getViewVector(0) uses the head's previous yaw, and AirAndWaterRandomPos the float quarter turn: tempted ghastlings stroll as vanilla's. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 55 ++++++++- crates/horizon-client/src/game/sculk.rs | 59 ++-------- crates/horizon-client/src/mobs.rs | 9 ++ crates/horizon-client/src/mobs/ai.rs | 1 + crates/horizon-client/src/mobs/goals.rs | 8 +- crates/horizon-client/src/mobs/living.rs | 23 +++- crates/horizon-client/src/mobs/warden.rs | 108 ++++++++++++++++-- tools/test_mob_ai_parity.py | 8 +- 8 files changed, 197 insertions(+), 74 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 7fe19f5b1..0601e6c6a 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -358,6 +358,13 @@ fn print_heart( ); } +/// The damage of a mob's direct hit on the player (others count as none). +fn player_damage(e: &MobEvent) -> f32 { + match e { + MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount, + _ => 0.0, + } +} /// Whether an event hurts the scenario's player (survival, normal difficulty, /// no armour, made hurtable again every tick by the oracle). fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { @@ -378,7 +385,9 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { } } -fn print(out: &mut String, t: i32, i: usize, m: &Mob) { +/// `player_down`: the scenario's player is no valid target (creative, or +/// killed this tick). +fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) { let _ = write!(out, "{t} {i}"); if m.removed { // Entity.RemovalReason: the end of the death animation, else a discard. @@ -418,7 +427,13 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { "\tgoals {}\ttargets {}\ttarget {}", goals(m, m.ai.goals.running_names()), goals(m, m.ai.targets.running_names()), - who(m.ai.target) + // Warden.getTarget: the brain's attack target, if still valid. + who(match horizon_client::mobs::warden::brain_target(m) { + Some(Who::Player) if player_down => None, + Some(target) => Some(target), + None if m.species() == Species::Warden => None, + None => m.ai.target, + }) ); let _ = write!(out, "\tnav "); match &m.ai.nav.path { @@ -674,7 +689,7 @@ fn main() -> horizon_client::Result<()> { }); let mut scratch = LegacyRandom::new(0); for (i, m) in mobs.iter().enumerate() { - print(&mut out, 0, i, m); + print(&mut out, 0, i, m, s.creative); } // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { @@ -801,6 +816,26 @@ fn main() -> horizon_client::Result<()> { m.removed = true; } horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); + horizon_client::mobs::warden::hear_mob_events(&mut mobs, &events, from, &w); + // Melee hits on other mobs land during the attacker's tick + // (LivingEntity.hurtServer), with the sounds they raise. + let mut k = from; + while k < events.len() { + if let MobEvent::AttackMob { + target, + amount, + source, + } = events[k] + && let Some(t) = mobs.iter_mut().find(|m| m.id == target) + && t.damage(amount, source) + { + let raised = std::mem::take(&mut t.outbox); + let n = raised.len(); + events.splice(k + 1..k + 1, raised); + k += n; + } + k += 1; + } // 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) { @@ -844,8 +879,13 @@ fn main() -> horizon_client::Result<()> { _ => {} } } + // A hit for the player's whole health kills it until the oracle + // heals it next tick. + let player_killed = events + .iter() + .any(|e| player_hurt(player.as_ref(), e) && player_damage(e) >= 20.0); for (i, m) in mobs.iter().enumerate() { - print(&mut out, t, i, m); + print(&mut out, t, i, m, s.creative || player_killed); } for e in &events { if let MobEvent::Sound(name, _, volume, pitch) = e { @@ -860,9 +900,14 @@ fn main() -> horizon_client::Result<()> { } else if player_hurt(player.as_ref(), e) { // The oracle's survival player, healed and made hurtable every tick, // takes the damage (LivingEntity.playHurtSound). + let sound = if player_damage(e) >= 20.0 { + "death" + } else { + "hurt" + }; let _ = writeln!( out, - "{t} sound minecraft:entity.player.hurt 3f800000 3f800000" + "{t} sound minecraft:entity.player.{sound} 3f800000 3f800000" ); } } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 4f5af29c3..c42a3aedf 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -638,54 +638,13 @@ impl Game<'_> { /// `Warden.VibrationUser`: accept a vibration for the warden at `index`. fn warden_listen(&mut self, index: usize, event: &'static str, pos: [f64; 3], ctx: &Context) { let now = self.world.game_time; - let (eye, busy) = { - let m = &self.mobs[index]; - let Some(st) = m.extra.warden.as_ref() else { - return; - }; - ( - [m.position.x, m.position.y + m.kind.eye_height, m.position.z], - st.vibration.current.is_some(), - ) - }; - if busy { - return; - } - let source_block = block_of(pos); - let eye_block = block_of(eye); - let d = [ - i64::from(source_block[0]) - i64::from(eye_block[0]), - i64::from(source_block[1]) - i64::from(eye_block[1]), - i64::from(source_block[2]) - i64::from(eye_block[2]), - ]; - if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 256 { - return; - } - if !sculk::valid_vibration(sculk::warden_can_listen(event), event, ctx) { - return; - } - if !warden::can_receive_vibration(&self.mobs[index], i64::from(self.mobs[index].age), ctx) { - return; - } - if self.occluded(pos, eye) { - return; - } - let distance = { - let d = [pos[0] - eye[0], pos[1] - eye[1], pos[2] - eye[2]]; - (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32 - }; - if let Some(st) = self.mobs[index].extra.warden.as_mut() { - st.vibration.schedule( - Info { - event, - distance, - pos, - source: ctx.source, - owner: ctx.owner, - }, - now, - ); - } + let (occludes, world) = (&self.sculk.tables.occludes, &self.world); + warden::listen(&mut self.mobs[index], now, event, pos, ctx, |a, b| { + sculk::is_occluded(a, b, |p| { + let state = world.block(p.x, p.y, p.z); + occludes.get(state.0 as usize).copied().unwrap_or(false) + }) + }); } // ---- ticking ---- @@ -1627,10 +1586,6 @@ impl Game<'_> { } else { (move_dist as i32).wrapping_add(1) as f32 }; - if warden { - self.audio - .play("minecraft:entity.warden.step", Some(at), 10.0, 1.0); - } let ctx = self.who_context(Some(who), Some(state)); self.post_game_event("minecraft:step", at, ctx); } else if in_water { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index b3c1ea7e1..986142b15 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -669,6 +669,15 @@ pub enum MobEvent { volume: f32, spread: f32, }, + /// `Level.gameEvent` from a mob's own movement (`GameEvent.STEP`): the + /// game's sculk layer tracks steps itself, the mob AI probe hears them + /// through the wardens (`warden::listen`). + GameEvent { + event: &'static str, + at: [f64; 3], + source: u32, + state: horizon_world::registry::BlockStateId, + }, AttackPlayer(f32, [f64; 3]), /// Damage of a given type to the player (guardian lasers, thorns). DamagePlayer { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 218056146..534c32d25 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -350,6 +350,7 @@ pub fn tick( if m.removed { return false; } + super::warden::pre_tick(m, w, events); base_tick(m, w, events); if m.death_time >= super::creaking::death_limit(m) { // Creaking.tickDeath: a heart's creaking crumbles away. diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 4dcd401c1..472154d35 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -346,12 +346,13 @@ impl Mob { let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water; (!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) } - /// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yRotO)`. + /// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yHeadRotO)`. pub fn view_vector(&self) -> [f64; 3] { use horizon_core::geometry::trig::Mth; let to_rad = std::f32::consts::PI / 180.0; let x = self.previous_head_pitch * to_rad; - let y = -self.previous_yaw * to_rad; + // LivingEntity.getViewYRot(0): the head's yaw of the last tick. + let y = -self.previous_head_yaw * to_rad; let (y_cos, y_sin, x_cos, x_sin) = (y.mcos(), y.msin(), x.mcos(), x.msin()); [ f64::from(y_sin * x_cos), @@ -378,7 +379,8 @@ impl Mob { fly_height, xd, zd, - std::f64::consts::FRAC_PI_2, + // Every caller passes `(float) (Math.PI / 2)`. + f64::from(std::f32::consts::FRAC_PI_2), )?; let mut p = m.toward(f64::from(h), d); if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 03d2f201f..a0b4b03a0 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -367,9 +367,18 @@ impl Mob { let at = [self.position.x, self.position.y, self.position.z]; events.push(MobEvent::Sound(sound, at, volume, pitch)); } - self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32; + // Entity.vibrationAndSoundEffectsFromBlock: the step's game + // event, with the supporting block's state when the effect + // block is another. + events.push(MobEvent::GameEvent { + event: "minecraft:step", + at: [self.position.x, self.position.y, self.position.z], + source: self.id, + state: if legacy == on { legacy_state } else { state }, + }); + self.ai.steps.next_step = self.next_step(); } else if self.fluids.in_water { - self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32; + self.ai.steps.next_step = self.next_step(); // Entity.waterSwimSound let v = self.velocity; let volume = 1.0_f32.min( @@ -393,6 +402,16 @@ impl Mob { } } } + /// `Entity.nextStep`: the next whole metre walked; a warden's steps come + /// every 0.55. + fn next_step(&self) -> f32 { + let walked = self.ai.steps.move_dist; + if self.kind.species == super::Species::Warden { + walked + 0.55 + } else { + (walked as i32).wrapping_add(1) as f32 + } + } /// Entity.isSwimming (mobs never swim in the player sense). fn fluids_swimming(&self) -> bool { false diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 546952d9c..454fbf10d 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -441,6 +441,11 @@ pub(super) fn do_hurt_target(m: &mut Mob, target: Who, w: &MobWorld, events: &mu super::ai::do_hurt_target(m, target, &mut cx); } +/// The brain's attack target (`Warden.getTarget` before `asValidTarget`). +pub fn brain_target(m: &Mob) -> Option { + warden_brain::mem_ref(m).and_then(|mem| mem.attack_target.value()) +} + // ---- vibrations ---- /// `Warden.VibrationUser.canReceiveVibration`. @@ -454,6 +459,85 @@ pub fn can_receive_vibration(m: &Mob, _now: i64, ctx: &Context) -> bool { && !digging_or_emerging(m) && !(ctx.living && !ctx.targetable) } +/// `VibrationSystem.Listener.handleGameEvent` for the warden: a free +/// listener within 16 blocks of its eyes schedules what it can hear. +/// `occluded` is `VibrationSystem.Listener.isOccluded`. +pub fn listen( + m: &mut Mob, + now: i64, + event: &'static str, + pos: [f64; 3], + ctx: &Context, + occluded: impl Fn([f64; 3], [f64; 3]) -> bool, +) { + let eye = [m.position.x, m.position.y + m.kind.eye_height, m.position.z]; + let Some(st) = m.extra.warden.as_ref() else { + return; + }; + if st.vibration.current.is_some() { + return; + } + let block = |p: [f64; 3]| p.map(|v| i64::from(v.floor() as i32)); + let (source, listener) = (block(pos), block(eye)); + let d = [0, 1, 2].map(|i| source[i] - listener[i]); + if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 256 + || !sculk::valid_vibration(sculk::warden_can_listen(event), event, ctx) + || !can_receive_vibration(m, i64::from(m.age), ctx) + || occluded(pos, eye) + { + return; + } + let d = [pos[0] - eye[0], pos[1] - eye[1], pos[2] - eye[2]]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; + if let Some(st) = m.extra.warden.as_mut() { + st.vibration.schedule( + Info { + event, + distance, + pos, + source: ctx.source, + owner: ctx.owner, + }, + now, + ); + } +} +/// `Level.gameEvent` for the mobs' own movement events from `from` on, as +/// the mob AI probe has no sculk layer: every warden's listener hears them. +pub fn hear_mob_events(mobs: &mut [Mob], events: &[MobEvent], from: usize, w: &MobWorld) { + for e in &events[from..] { + let MobEvent::GameEvent { + event, + at, + source, + state, + } = *e + else { + continue; + }; + let who = mobs.iter().find(|m| m.id == source); + let name = &w.facts.get(state).name; + let ctx = Context { + source: Some(Who::Mob(source)), + dampening_state: w.has_tag("minecraft:dampens_vibrations", name), + dampens: who.is_some_and(|m| m.species() == Species::Warden), + targetable: who.is_some_and(|m| m.alive() && m.species() != Species::Warden), + living: true, + ..Context::default() + }; + for m in mobs.iter_mut().filter(|m| m.extra.warden.is_some()) { + listen(m, w.game_time, event, at, &ctx, |a, b| { + sculk::is_occluded(a, b, |p| { + let block = w.world.block(p.x, p.y, p.z); + w.has_tag( + "minecraft:occludes_vibration_signals", + &w.facts.get(block).name, + ) + }) + }); + } + } +} /// `Warden.VibrationUser.onReceiveVibration`. fn receive_vibration(m: &mut Mob, w: &MobWorld, info: Info, events: &mut Vec) { if !m.alive() { @@ -507,15 +591,9 @@ fn receive_vibration(m: &mut Mob, w: &MobWorld, info: Info, events: &mut Vec, -) { +/// `Warden.tick` before `super.tick()`: the vibration ticker, and +/// persistence keeping the dig cooldown. +pub fn pre_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.extra.warden.is_none() { return; } @@ -542,6 +620,18 @@ pub fn server_ai_step( if m.persistent || m.custom_name.is_some() { warden_brain::set_dig_cooldown(m); } +} +/// `Warden.customServerAiStep`: the brain, the darkness pulse, anger and +/// the activity. +pub fn server_ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { + if m.extra.warden.is_none() { + return; + } handle_hurt(m, w, events); warden_brain::tick(m, w, level_random, events); if (i64::from(m.age) + i64::from(m.id)) % 120 == 0 { diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index e992e75a9..84dc7725a 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -78,15 +78,17 @@ def scenarios(): 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) # The warden: idle, sniffing out a player, roaring and fighting (WardenAi). - # Without finalizeSpawn's dig cooldown a warden digs straight back down. + # Without finalizeSpawn's dig cooldown a warden digs straight back down. warden_player + # and warden_cow stop before the first blow kills the player or the cow (the probe has no dying + # player, nor the attack knockback attribute or a target killed within the attacker's tick). add('warden_digs', 140, ['mob minecraft:warden 0.5 -60 0.5 0 60']) add('warden_alone', 400, ['mob minecraft:warden 0.5 -60 0.5 0 61 digcooldown']) - add('warden_player', 600, ['player 5.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 62 digcooldown']) + add('warden_player', 565, ['player 5.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 62 digcooldown']) add('warden_player_far', 600, ['player 14.5 -60 3.5', 'mob minecraft:warden 0.5 -60 0.5 90 63 digcooldown']) add('warden_creative', 300, ['player 4.5 -60 0.5 creative', 'mob minecraft:warden 0.5 -60 0.5 0 64 digcooldown']) add('warden_persistent', 400, ['player 7.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 65 persistent digcooldown']) add('warden_emerging', 300, ['player 6.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 66 emerge']) - add('warden_cow', 600, ['mob minecraft:warden 0.5 -60 0.5 0 67 digcooldown', 'mob minecraft:cow 4.5 -60 0.5 0 68 persistent']) + add('warden_cow', 176, ['mob minecraft:warden 0.5 -60 0.5 0 67 digcooldown', 'mob minecraft:cow 4.5 -60 0.5 0 68 persistent']) # Breezes: idle, and fighting a player near, in, and beyond the inner jump circle. add('breeze_alone', 200, ['mob minecraft:breeze 0.5 -60 0.5 90 61 persistent']) add('breeze_player', 200, ['player 8.5 -60 0.5', 'mob minecraft:breeze 0.5 -60 0.5 0 62 persistent']) From 8c784eaaa67ef7ab5eeebe575823eecac5ab4528 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:15:26 +0200 Subject: [PATCH 08/14] Ignore mob step game events in the game, whose sculk layer tracks steps Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d7f710d40..e17646f0d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -709,6 +709,9 @@ impl Game<'_> { MobEvent::SoundId(name, at, volume, pitch) => { self.audio.play(&name, Some(at), volume, pitch) } + // The sculk layer tracks the game's steps itself + // (`entity_motion_events`). + MobEvent::GameEvent { .. } => {} MobEvent::AttackPlayer(amount, from) => { self.mob_hits_player(amount, from, "minecraft:mob_attack") } From 5565cc3a4116ffc91e5eb0f6d2f7ce5b8df08992 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:26:25 +0200 Subject: [PATCH 09/14] Give player-less mob AI scenarios the oracle's far-away player The oracle's player stays 5000 blocks east between scenarios, and Mob.checkDespawn draws for it once a mob idles past 600 ticks (warden_alone). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/mob_ai_probe.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 0601e6c6a..08ca01a43 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -659,7 +659,10 @@ fn main() -> horizon_client::Result<()> { } mobs.push(m); } - let mut player = s.player.map(|p| { + // Without a player of its own a scenario still has the oracle's, + // 5000 blocks east (Mob.checkDespawn draws for it). + let far = [f64::from(s.origin[0] + 5000), -60.0, f64::from(s.origin[1])]; + let mut player = Some(s.player.unwrap_or(far)).map(|p| { let position = Vec3::new(p[0], p[1], p[2]); PlayerView { position, From 2b1981acbba1ab7cf7bfbe919324947c9e5c90e6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:45:07 +0200 Subject: [PATCH 10/14] Drop a stale warden memory test and collapse the fixture's seeding ifs Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/sculk_fixture.rs | 16 ++++++++-------- crates/horizon-client/src/mobs/warden.rs | 17 ----------------- 2 files changed, 8 insertions(+), 25 deletions(-) diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 2cdb820b0..0c12804ec 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -551,10 +551,10 @@ impl Game<'_> { known.insert(id); names.insert(id, format!("n{}", names.len())); let seed = 0x5eed + names.len() as i64; - if seeded.insert(id) { - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - seed_fresh(m, seed); - } + if seeded.insert(id) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + seed_fresh(m, seed); } lines.push(line); } @@ -690,10 +690,10 @@ impl Game<'_> { .collect(); born.sort_unstable(); for (i, id) in born.into_iter().enumerate() { - if seeded.insert(id) { - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - seed_fresh(m, 0x5eed + (named + i + 1) as i64); - } + if seeded.insert(id) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + seed_fresh(m, 0x5eed + (named + i + 1) as i64); } } // Entities: the player's warden spawn tracker, then the mobs. diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 454fbf10d..f78ceff25 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -1012,23 +1012,6 @@ mod tests { assert_eq!(heart_beat_delay(150), 10); } - #[test] - fn memories_expire_with_their_ttl() { - let mut st = Warden { - in_brain: true, - ..Warden::default() - }; - // Set during the brain: present for exactly the ttl. - let until = st.expiry(100, 5); - assert!(present(until, 104)); - assert!(!present(until, 105)); - // Set before the brain's tick: that tick already counts. - st.in_brain = false; - let until = st.expiry(100, 5); - assert!(present(until, 103)); - assert!(!present(until, 104)); - } - #[test] fn the_pose_codes_round_trip() { for p in [ From acdbb3d27ad666e7682029d3b2898844c51a86d2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:55:46 +0200 Subject: [PATCH 11/14] End gateways tick their beam in game: client beamAnimationTick beside the server copy's portalTick The anim harness now runs vanilla's TheEndGatewayBlockEntity on a client and a server stand-in (triggerCooldown every 2400 ticks and on entry, block event 1) and compares the beam render state; 40 cases match. Co-Authored-By: Claude Opus 5.5 --- .../examples/block_entity_anim_fixture.rs | 43 ++++++++- .../horizon-client/src/block_entity_anim.rs | 69 +++++++++++++- .../horizon-client/src/block_entity_render.rs | 93 +++++++++++-------- .../src/game/block_entity_anims.rs | 60 +++++++++++- crates/horizon-client/src/game/end.rs | 1 + crates/horizon-client/src/game/persist.rs | 10 ++ crates/horizon-client/src/save.rs | 2 +- .../parity/VanillaBlockEntityAnimOracle.java | 53 ++++++++++- tools/test_block_entity_anim_parity.py | 17 +++- 9 files changed, 299 insertions(+), 49 deletions(-) diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/block_entity_anim_fixture.rs index 3347a8104..e108c53b3 100644 --- a/crates/horizon-client/examples/block_entity_anim_fixture.rs +++ b/crates/horizon-client/examples/block_entity_anim_fixture.rs @@ -8,9 +8,10 @@ use horizon_client::{ assets::Assets, block_entity_anim::{ Bell, BellEntity, BlockEntityAnims, ChestLid, Conduit, ConduitTarget, DIRECTIONS, - PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, direction_index, + EndGateway, PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, + direction_index, }, - block_entity_render::BlockEntityRenderer, + block_entity_render::{BlockEntityRenderer, gateway_beam}, blocks::{BlockFacts, Fluid}, items::Items, }; @@ -188,6 +189,14 @@ fn main() -> Result<()> { let facing = prop(&block, "facing") .and_then(direction_index) .unwrap_or(1); + // End gateways: the saved age, the level's height range and the + // integrated server's copy. + let initial = EndGateway { + age: case["age"].as_i64().unwrap_or(0), + teleport_cooldown: 0, + }; + let max_y = int(&case["level"][0]) + int(&case["level"][1]) - 1; + let mut server = initial; let mut text = String::new(); for step in case["steps"].as_array().into_iter().flatten() { let time = step["time"].as_i64().unwrap_or(0); @@ -445,6 +454,36 @@ fn main() -> Result<()> { f(progress), style ); + } else if name == "minecraft:end_gateway" { + let client = anims.gateways.entry(pos).or_insert(initial); + if step["enter"].as_bool() == Some(true) && server.enter() { + log.push_str(" blockEvent 1 0"); + client.trigger_event(1, 0); + } + if server.portal_tick() { + log.push_str(" blockEvent 1 0"); + client.trigger_event(1, 0); + } + if let Some((e0, e1)) = event { + let handled = client.trigger_event(e0, e1); + let _ = write!(log, " event {handled}"); + } + client.tick(); + let g = *client; + let a = anims.block_anim(pos, time, partial, Default::default()); + let b = gateway_beam(a.gateway, partial, max_y, time); + let _ = write!( + text, + "{} {} server {} {} render {} {} {:x} {}", + g.age, + g.teleport_cooldown, + server.age, + server.teleport_cooldown, + b.height, + f(b.scale), + b.color, + f(b.animation_time) + ); } else { text = format!("unsupported {block}"); } diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index 70a57cc64..eefd1ba63 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -725,6 +725,55 @@ impl PotWobble { } } +/// `TheEndGatewayBlockEntity` fields the beam reads. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct EndGateway { + pub age: i64, + pub teleport_cooldown: i32, +} +impl EndGateway { + /// `beamAnimationTick` (the client ticker). + pub fn tick(&mut self) { + self.age = self.age.wrapping_add(1); + if self.teleport_cooldown > 0 { + self.teleport_cooldown -= 1; + } + } + /// `portalTick` on the server copy: whether it called `triggerCooldown`, + /// whose block event 1 reaches the client copy. + pub fn portal_tick(&mut self) -> bool { + let cooling = self.teleport_cooldown > 0; + self.age = self.age.wrapping_add(1); + if cooling { + self.teleport_cooldown -= 1; + false + } else if self.age % 2400 == 0 { + self.teleport_cooldown = 40; + true + } else { + false + } + } + /// `EndGatewayBlock.entityInside` on the server copy: an entity that can + /// use the portal starts the cooldown unless it is already running. + pub fn enter(&mut self) -> bool { + if self.teleport_cooldown > 0 { + return false; + } + self.teleport_cooldown = 40; + true + } + /// `triggerEvent`: event 1 starts the 40 tick cooldown. + pub fn trigger_event(&mut self, event: i32, _data: i32) -> bool { + if event == 1 { + self.teleport_cooldown = 40; + true + } else { + false + } + } +} + /// The client ticker a block entity runs (`getTicker` on a client level), /// or [`Ticker::Pot`] for decorated pots, which keep wobble state unticked. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -746,6 +795,8 @@ pub enum Ticker { powered: bool, }, Pot, + /// `TheEndGatewayBlockEntity.beamAnimationTick`. + Gateway, } /// The [`Ticker`] of a block state, by block name and property lookup. @@ -764,6 +815,7 @@ pub fn ticker(name: &str, prop: impl Fn(&str) -> Option) -> Option Ticker::Bell, "conduit" => Ticker::Conduit, "decorated_pot" => Ticker::Pot, + "end_gateway" => Ticker::Gateway, "dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull { powered: prop("powered").as_deref() == Some("true"), }, @@ -789,6 +841,9 @@ pub struct BlockEntityAnims { pub conduits: HashMap<[i32; 3], Conduit>, pub skulls: HashMap<[i32; 3], Skull>, pub pots: HashMap<[i32; 3], PotWobble>, + pub gateways: HashMap<[i32; 3], EndGateway>, + /// The integrated server's copies of the gateways (`portalTick`). + pub gateway_servers: HashMap<[i32; 3], EndGateway>, /// The client level's random (conduit particles). pub random: LegacyRandom, /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). @@ -805,6 +860,8 @@ impl Default for BlockEntityAnims { conduits: HashMap::new(), skulls: HashMap::new(), pots: HashMap::new(), + gateways: HashMap::new(), + gateway_servers: HashMap::new(), random: LegacyRandom::new(0x6c6576656c), kinds: Vec::new(), } @@ -839,6 +896,8 @@ impl BlockEntityAnims { self.skulls .retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. }))); self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot)); + self.gateways + .retain(|p, _| is(p, |t| *t == Ticker::Gateway)); } /// Drops the state of positions whose block entity is gone. pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) { @@ -849,6 +908,8 @@ impl BlockEntityAnims { self.conduits.retain(|p, _| keep(*p)); self.skulls.retain(|p, _| keep(*p)); self.pots.retain(|p, _| keep(*p)); + self.gateways.retain(|p, _| keep(*p)); + self.gateway_servers.retain(|p, _| keep(*p)); } /// `getOpenNess(partial)` of the chest or ender chest at `pos`. pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 { @@ -867,9 +928,11 @@ impl BlockEntityAnims { ) -> BlockAnim { let mut anim = BlockAnim { sherds, - // End gateway ages and cooldowns are not tracked on the client yet: - // gateways render settled (no beam). - gateway: (i64::MAX, 0), + // Gateways not ticked yet render settled (no beam). + gateway: self + .gateways + .get(&pos) + .map_or((i64::MAX, 0), |g| (g.age, g.teleport_cooldown)), ..BlockAnim::default() }; if let Some(b) = self.books.get(&pos) { diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 7380bb75e..399527b78 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -1292,44 +1292,24 @@ impl BlockEntityRenderer { } Kind::EndGateway { state } => { let anim = (scene.anim)(pos); - let (age, cooldown) = anim.gateway; - // TheEndGatewayRenderer.extractRenderState. - let spawning = age < 200; - if spawning || cooldown > 0 { - let a = scene.partial; - let percent = if spawning { - ((age as f32 + a) / 200.0).clamp(0.0, 1.0) - } else { - 1.0 - ((cooldown as f32 - a) / 40.0).clamp(0.0, 1.0) - }; - let distance = if spawning { - f64::from(scene.max_y) - } else { - 50.0 - }; - let scale = trig::sin(f64::from(percent * PI)); - let height = (f64::from(scale) * distance).floor() as i32; - // DyeColor.MAGENTA / PURPLE getTextureDiffuseColor. - let color = if spawning { 0xC7_4EBD } else { 0x89_32B8 }; - let time = scene.game_time.rem_euclid(40) as f32 + a; - if height > 0 - && let Some(s) = sprite("entity/end_portal/end_gateway_beam") - { - beam( - base, - BeamShape { - scale, - time, - start: -height, - height: height * 2, - color, - solid_radius: 0.15, - glow_radius: 0.175, - }, - s, - out, - ); - } + let b = gateway_beam(anim.gateway, scene.partial, scene.max_y, scene.game_time); + if b.height > 0 + && let Some(s) = sprite("entity/end_portal/end_gateway_beam") + { + beam( + base, + BeamShape { + scale: b.scale, + time: b.animation_time, + start: -b.height, + height: b.height * 2, + color: b.color, + solid_radius: 0.15, + glow_radius: 0.175, + }, + s, + out, + ); } // AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace. let faces: Vec = Direction::ALL @@ -1618,6 +1598,43 @@ impl BeamPart { } } +/// `EndGatewayRenderState`'s beam fields (zero when there is no beam). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct GatewayBeam { + pub height: i32, + pub scale: f32, + pub color: u32, + pub animation_time: f32, +} + +/// `TheEndGatewayRenderer.extractRenderState` from the block entity's age and +/// teleport cooldown, at `partial`, for a level whose top is `max_y`. +pub fn gateway_beam( + (age, cooldown): (i64, i32), + partial: f32, + max_y: i32, + game_time: i64, +) -> GatewayBeam { + let spawning = age < 200; + if !spawning && cooldown <= 0 { + return GatewayBeam::default(); + } + let percent = if spawning { + ((age as f32 + partial) / 200.0).clamp(0.0, 1.0) + } else { + 1.0 - ((cooldown as f32 - partial) / 40.0).clamp(0.0, 1.0) + }; + let distance = if spawning { f64::from(max_y) } else { 50.0 }; + let scale = trig::sin(f64::from(percent * PI)); + GatewayBeam { + height: (f64::from(scale) * distance).floor() as i32, + scale, + // DyeColor.MAGENTA / PURPLE getTextureDiffuseColor. + color: if spawning { 0xFFC7_4EBD } else { 0xFF89_32B8 }, + animation_time: game_time.rem_euclid(40) as f32 + partial, + } +} + /// Entity-shader layers for `rendertype_end_portal`: end portals draw 15 /// layers of `end_portal.png` over `end_sky.png`, End gateways 16. pub const END_PORTAL_LAYER: u32 = 9; diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index d1597a7a3..5444ea2fd 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -5,10 +5,11 @@ //! [`Game::block_anim`] and [`Game::chest_lid`]. use super::Game; use horizon_client::{ - block_entity_anim::{BellEntity, Shulker, ShulkerStatus, Ticker}, + block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker}, block_entity_render::BlockAnim, collisions::{SceneCollisions, no_collision_empty}, particles::{ParticleOptions, ParticleType}, + save::number, }; use horizon_core::geometry::{Aabb, Vec3}; use std::collections::HashMap; @@ -44,6 +45,14 @@ impl Game<'_> { .or_default() .trigger_event(a, b, time, || gathered); } + Some(Ticker::Gateway) => { + let initial = self.gateway_loaded(pos); + self.be_anims + .gateways + .entry(pos) + .or_insert(initial) + .trigger_event(a, b); + } Some(Ticker::Pot) => { self.be_anims .pots @@ -276,9 +285,58 @@ impl Game<'_> { } } Ticker::Pot => {} + Ticker::Gateway => { + // The server copy's portalTick runs first; its block event + // reaches the client copy before the client ticks it. + let initial = self.gateway_loaded(pos); + let anims = &mut self.be_anims; + let server = anims.gateway_servers.entry(pos).or_insert(initial); + let triggered = server.portal_tick(); + let client = anims.gateways.entry(pos).or_insert(initial); + if triggered { + client.trigger_event(1, 0); + } + client.tick(); + } } } } + /// `EndGatewayBlock.entityInside` on the server: whether the gateway at + /// `pos` let the entity in (`triggerCooldown`, with its block event). + pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool { + let initial = self.gateway_loaded(pos); + let entered = self + .be_anims + .gateway_servers + .entry(pos) + .or_insert(initial) + .enter(); + if entered { + self.block_entity_event(pos, 1, 0); + } + entered + } + /// The End gateway at `pos` as its chunk was loaded: `Age` from the saved + /// block entity (`getUpdateTag`), or a new gateway. + fn gateway_loaded(&self, pos: [i32; 3]) -> EndGateway { + let age = self + .world + .chunks + .get(&(pos[0] >> 4, pos[2] >> 4)) + .and_then(|c| c.saved.as_deref()) + .and_then(|saved| { + saved.block_entities.iter().find(|t| { + [t.get("x"), t.get("y"), t.get("z")] + .map(number) + .eq(&pos.map(|v| Some(i64::from(v)))) + }) + }) + .and_then(|t| number(t.get("Age"))); + EndGateway { + age: age.unwrap_or(0), + teleport_cooldown: 0, + } + } /// The renderer's view of the block entity at `pos`. pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { self.be_anims diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index e1a848a25..163c76e73 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -405,6 +405,7 @@ impl Game<'_> { } } else if let Some(g) = gateway && self.end.gateway_cooldown == 0 + && self.gateway_enter(g) { self.enter_gateway(g)?; } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index a72530e6a..659a87ce0 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -95,6 +95,16 @@ impl Game<'_> { extras.fluid_ticks.clear(); } extras.last_update = time; + // TheEndGatewayBlockEntity saves its Age (the server copy's). + for tag in &mut extras.block_entities { + let pos = [tag.get("x"), tag.get("y"), tag.get("z")] + .map(|v| horizon_client::save::number(v).unwrap_or(0) as i32); + if let Some(g) = self.be_anims.gateway_servers.get(&pos) + && let Some(age) = tag.get_mut("Age") + { + *age = horizon_world::nbt::Tag::Long(g.age); + } + } if let Some(t) = self.world.inhabited.get(&(chunk.x, chunk.z)) { extras .root diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index a9c538362..96965431f 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -53,7 +53,7 @@ pub(crate) fn text(tag: Option<&Tag>) -> Option { } } /// Any numeric tag as i64 (vanilla's `getIntOr` etc. accept every number type). -pub(crate) fn number(tag: Option<&Tag>) -> Option { +pub fn number(tag: Option<&Tag>) -> Option { Some(match tag? { Tag::Byte(v) => i64::from(*v), Tag::Short(v) => i64::from(*v), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java index 5c8c899db..a85bce1b4 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java @@ -33,13 +33,15 @@ import net.minecraft.world.phys.*; /** * Original oracle for the client-ticked animation state of chests and ender * chests (ChestLidController), enchanting table books, shulker boxes, bells, - * conduits, skulls and decorated pots. Each case builds the real + * conduits, skulls, decorated pots and End gateways. Each case builds the real * vanilla block entity on a stand-in client level (scripted blocks, entities, * game time and a seeded LegacyRandomSource), then per step applies the * scripted block event (triggerEvent), runs the block entity's own client * ticker (lidAnimateTick, bookAnimationTick with the class's static RANDOM * reseeded, ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick, - * ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none) + * ConduitBlockEntity.clientTick, SkullBlockEntity.animation, + * TheEndGatewayBlockEntity.beamAnimationTick after the server copy's portalTick + * on a server-side stand-in; pots have none) * and runs the real renderer's extractRenderState at the step's partial tick. * It prints the block entity's fields, the level calls the tick made * (neighbour updates, entity queries, sounds, particles) and the render state. @@ -100,6 +102,9 @@ public final class VanillaBlockEntityAnimOracle { static final class World extends Level { World() { super(null, null, null, null, false, false, 0L, 0); } long time; + boolean server; + int minY, height; + BlockEntity serverCopyOf; Map blocks = new HashMap<>(); List mobs = new ArrayList<>(); List gamers = new ArrayList<>(); @@ -108,7 +113,16 @@ public final class VanillaBlockEntityAnimOracle { StringBuilder log = new StringBuilder(); @Override public long getGameTime() { return time; } - @Override public boolean isClientSide() { return true; } + @Override public boolean isClientSide() { return !server; } + @Override public int getMinY() { return minY; } + @Override public int getHeight() { return height; } + @Override public void blockEvent(BlockPos p, Block block, int b0, int b1) { + // The integrated server's block event reaching the client copy. + log.append(" blockEvent ").append(b0).append(' ').append(b1); + serverCopyOf.triggerEvent(b0, b1); + } + @Override public void blockEntityChanged(BlockPos p) {} + @Override public void updateNeighbourForOutputSignal(BlockPos p, Block block) {} @Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); } @Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); } @Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; } @@ -236,6 +250,22 @@ public final class VanillaBlockEntityAnimOracle { if (c.has("target") && be instanceof ConduitBlockEntity) { put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world))); } + World serverWorld = null; + TheEndGatewayBlockEntity serverGateway = null; + if (be instanceof TheEndGatewayBlockEntity g) { + var level = c.getAsJsonArray("level"); + world.minY = level.get(0).getAsInt(); + world.height = level.get(1).getAsInt(); + field(TheEndGatewayBlockEntity.class, "age").setLong(g, c.get("age").getAsLong()); + serverWorld = make(World.class); + serverWorld.server = true; + serverWorld.blocks = world.blocks; + serverWorld.log = world.log; + serverWorld.serverCopyOf = g; + serverGateway = (TheEndGatewayBlockEntity) ((EntityBlock) state.getBlock()).newBlockEntity(pos, state); + serverGateway.setLevel(serverWorld); + field(TheEndGatewayBlockEntity.class, "age").setLong(serverGateway, c.get("age").getAsLong()); + } StringBuilder out = new StringBuilder(); for (var stepElement : c.getAsJsonArray("steps")) { var step = stepElement.getAsJsonObject(); @@ -251,6 +281,14 @@ public final class VanillaBlockEntityAnimOracle { world.gamers.clear(); for (var e : step.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject())); } + if (serverGateway != null) { + serverWorld.time = world.time; + // ServerLevel.tick: entities (EndGatewayBlock.entityInside), then block entities. + if (step.has("enter") && !serverGateway.isCoolingDown()) { + TheEndGatewayBlockEntity.triggerCooldown(serverWorld, pos, state, serverGateway); + } + TheEndGatewayBlockEntity.portalTick(serverWorld, pos, state, serverGateway); + } if (step.has("event")) { var ev = step.getAsJsonArray("event"); boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt()); @@ -327,6 +365,15 @@ public final class VanillaBlockEntityAnimOracle { make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null); fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle + " render " + f(r.wobbleProgress) + " " + r.wobbleStyle; + } else if (be instanceof TheEndGatewayBlockEntity g) { + TheEndGatewayBlockEntity.beamAnimationTick(world, pos, state, g); + var r = make(TheEndGatewayRenderer.class).createRenderState(); + make(TheEndGatewayRenderer.class).extractRenderState(g, r, partial, Vec3.ZERO, null); + fields = field(TheEndGatewayBlockEntity.class, "age").getLong(g) + + " " + field(TheEndGatewayBlockEntity.class, "teleportCooldown").getInt(g) + + " server " + field(TheEndGatewayBlockEntity.class, "age").getLong(serverGateway) + + " " + field(TheEndGatewayBlockEntity.class, "teleportCooldown").getInt(serverGateway) + + " render " + r.height + " " + f(r.scale) + " " + Integer.toHexString(r.color) + " " + f(r.animationTime); } else { throw new IllegalArgumentException("no animation for " + be); } diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py index 0e85d978a..eb47285d8 100755 --- a/tools/test_block_entity_anim_parity.py +++ b/tools/test_block_entity_anim_parity.py @@ -4,7 +4,7 @@ The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla block entity (chest, trapped/copper chest and the other half of a double chest, ender chest, enchanting table, shulker box, bell, conduit, dragon/piglin head, -decorated pot) +decorated pot, End gateway with the integrated server's copy ticking beside it) on a stand-in client level, then per scripted step applies the block event (triggerEvent), runs the entity's own client ticker and the renderer's extractRenderState, printing the fields, the level calls the tick made @@ -162,6 +162,21 @@ def cases(): step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])] steps.append(step) add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps) + # End gateways: the server copy's portalTick (triggerCooldown every 2400 + # ticks, entities entering) sends block event 1 to the client copy, whose + # beamAnimationTick and TheEndGatewayRenderer draw the beam; saved ages + # from new to long settled, both level heights. + for i in range(40): + age = rng.choice([0, 0, 150, 2390, 4790, rng.randint(200, 10 ** 6), 2399 + 2400 * rng.randint(1, 50)]) + steps = [] + for t in times(rng.randint(20, 90), gaps=(1, 1, 1, 2)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.06: + step['enter'] = True + if rng.random() < 0.04: + step['event'] = [rng.choice([1, 2, 0]), rng.choice([0, 3])] + steps.append(step) + add('gateway', 'minecraft:end_gateway', steps, age=age, level=rng.choice([[0, 256], [-64, 384]])) # Chests and ender chests: open counts from block event 1 (both halves of # a double chest), other events ignored; the neighbour a double half # connects to may be its other half or not (wrong block, type, facing). From d9054baf44dcaace1fb2324479117bd8d7366af5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 02:03:08 +0200 Subject: [PATCH 12/14] The loom's result preview draws vanilla's banner flag picture in picture GuiBannerResultRenderer's flag model and pattern layers, lit with Lighting.Entry.ITEMS_FLAT and clipped to the 20x40 rectangle, through the GUI item pipeline. The block entity render harness gains loom result cases (the oracle submits vanilla's renderToTexture under the PiP pose): 407/407. Co-Authored-By: Claude Opus 5.5 --- .../examples/block_entity_render_fixture.rs | 39 ++++++++ crates/horizon-client/src/game/loom.rs | 69 ++++---------- crates/horizon-client/src/item_render/gui.rs | 93 ++++++++++++++++--- .../horizon-client/src/item_render/special.rs | 27 ++++++ .../VanillaBlockEntityRenderOracle.java | 49 ++++++++-- tools/test_block_entity_render_parity.py | 26 +++++- 6 files changed, 230 insertions(+), 73 deletions(-) diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index aa4a14a58..d844c4e44 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -13,6 +13,7 @@ use horizon_client::{ }, chunk::{Chunk, Light}, hud::{HudAtlas, Rect}, + item_render::{ItemRenderer, gui}, signs::{DYE_TEXT, SignData, SignText}, world::World, }; @@ -119,6 +120,7 @@ fn main() -> Result<()> { let renderer = BlockEntityRenderer::load(root, registry)?; let atlas = HudAtlas::build(root)?; let banners = Banners::load(root); + let items = ItemRenderer::load(root)?; let (sprites, names, grid) = fake_sprites(textures)?; let air = registry.default_state("minecraft:air").ok_or("no air")?; let mut out = BufWriter::new(fs::File::create(output)?); @@ -128,6 +130,43 @@ fn main() -> Result<()> { { let case: Value = serde_json::from_str(line)?; let block = case["block"].as_str().unwrap_or_default(); + if let Some(loom) = case.get("loom") { + // The loom's result preview, as LoomScreen draws it at (0, 0). + let layers: Vec<(String, String)> = loom["patterns"] + .as_array() + .into_iter() + .flatten() + .map(|p| { + ( + banners.banner_texture(p[0].as_str().unwrap_or_default()), + p[1].as_str().unwrap_or_default().to_owned(), + ) + }) + .collect(); + let base = loom["base"].as_str().unwrap_or_default(); + let flat = gui::items_flat_lights(); + let quads: Vec = + gui::banner_result_quads(&items, &sprites, 0.0, 0.0, base, &layers) + .iter() + .map(|q| { + let (cu, cv) = ((q.uv[0][0] / 2.0).floor(), (q.uv[0][1] / 2.0).floor()); + let texture = names + .get(cu as usize + cv as usize * grid) + .cloned() + .unwrap_or_default(); + let v: Vec = (0..4) + .map(|k| { + let p = q.pos[k]; + json!([p.x, p.y, p.z, q.uv[k][0] - cu * 2.0, q.uv[k][1] - cv * 2.0]) + }) + .collect(); + // Full bright (15728880). + json!({"texture": texture, "v": v, "color": gui::lit_color(q, flat), "light": 0xF0F0}) + }) + .collect(); + writeln!(out, "{}", json!({"quads": quads, "texts": []}))?; + continue; + } if block == "minecraft:beacon" { // BeaconRenderer: the beam sections from the case, as Horizon's beacon keeps them. let int = |v: &Value| v.as_i64().unwrap_or(0); diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 759d6e0da..f6648c43b 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -44,24 +44,6 @@ const BUTTON: f32 = 14.0; fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h } -/// A sub-rectangle of a sprite given in texels. -fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect { - let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); - Rect { - u0: r.u0 + x * du, - v0: r.v0 + y * dv, - u1: r.u0 + (x + w) * du, - v1: r.v0 + (y + h) * dv, - w: w as u32, - h: h as u32, - } -} -/// A dye's tint as a HUD vertex colour. -pub(super) fn dye_color(name: &str) -> u32 { - let c = banner::dye_rgb(name); - rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255) -} - impl Game<'_> { /// `LoomScreen.containerChanged`: the error flag, whether the pattern /// buttons show (only when an input changed), and the scroller reset. @@ -182,30 +164,30 @@ impl Game<'_> { l.start_row = l.row_for(l.scroll); } } - /// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1)) - /// drawn flat: the cloth, the base colour and every layer. - pub(super) fn draw_flag( + /// `GuiGraphicsExtractor.bannerPattern`: the banner flag model with its + /// layers in a 20x40 picture in picture at `(x, y)`. + fn draw_banner_result( &self, batch: &mut HudBatch, - rect: [f32; 4], + x: f32, + y: f32, base: &str, layers: &[BannerLayer], ) { let banners = &self.res.stations.banners; - let mut paint = |name: &str, color: u32| { - if let Some(r) = self.res.atlas.sprites.get(name).copied() { - let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]); - batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color); - } - }; - paint("entity/banner/banner_base", u32::MAX); - paint("entity/banner/base", dye_color(base)); - for layer in layers.iter().take(16) { - paint( - &banners.banner_texture(&layer.pattern), - dye_color(&layer.color), - ); - } + let layers: Vec<(String, String)> = layers + .iter() + .map(|l| (banners.banner_texture(&l.pattern), l.color.to_string())) + .collect(); + horizon_client::item_render::gui::draw_banner_result( + &self.res.item_renderer, + &self.res.atlas.sprites, + batch, + x, + y, + base, + &layers, + ); } /// Paints `screen_layout` calls at the menu origin (ox, oy): the container /// background and the dimmed world are drawn by the caller. @@ -256,19 +238,8 @@ impl Game<'_> { layers, x0, y0, - x1, - y1, - } => self.draw_flag( - batch, - [ - ox + *x0 as f32, - oy + *y0 as f32, - (x1 - x0) as f32, - (y1 - y0) as f32, - ], - base, - layers, - ), + .. + } => self.draw_banner_result(batch, ox + *x0 as f32, oy + *y0 as f32, base, layers), ScreenDraw::Tooltip { key } => { tooltip = Some(vec![(self.translate(key, key), u32::MAX)]); } diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index 0000b2613..930524dce 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -89,7 +89,7 @@ fn clip_triangle(tri: [Point; 3], rect: [f32; 4]) -> Vec { } /// RGBA vertex colour of a lit quad: `minecraft_mix_light` on the tint. -fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 { +pub fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 { let light = crate::block_entity_render::diffuse(q.normal, lights); let [a, r, g, b] = q.color.to_be_bytes(); let c = |v: u8| (f32::from(v) * light) as u8; @@ -155,6 +155,28 @@ pub fn draw( } else { items_flat_lights() }; + let rect = if state.oversized_in_gui { + [ + f32::NEG_INFINITY, + f32::NEG_INFINITY, + f32::INFINITY, + f32::INFINITY, + ] + } else { + [x, y, x + 16.0, y + 16.0] + }; + draw_quads(&quads, lights, batch, rect, time); +} + +/// Lights, culls, sorts far to near and clips `quads` (GUI positions) to +/// `rect`. +fn draw_quads( + quads: &[ItemQuad], + lights: (Vec3, Vec3), + batch: &mut HudBatch, + rect: [f32; 4], + time: f32, +) { // Back-face culling: front faces wind counter-clockwise on screen with y up. let mut visible: Vec<(f32, usize)> = quads .iter() @@ -173,16 +195,6 @@ pub fn draw( .collect(); // Far to near; the depth buffer of the item atlas, approximated per quad. visible.sort_by(|a, b| a.0.total_cmp(&b.0)); - let rect = if state.oversized_in_gui { - [ - f32::NEG_INFINITY, - f32::NEG_INFINITY, - f32::INFINITY, - f32::INFINITY, - ] - } else { - [x, y, x + 16.0, y + 16.0] - }; for (_, i) in visible { let q = &quads[i]; let points: [Point; 4] = std::array::from_fn(|k| Point { @@ -206,6 +218,65 @@ pub fn draw( } } +/// `PictureInPictureRenderer.prepare` for the loom's 20x40 result rectangle +/// at `(x0, y0)` (`translate(w / 2, h)`, `scale(16, 16, -16)`, one texel per +/// GUI pixel), then `GuiBannerResultRenderer.renderToTexture`'s +/// `translate(0, 0.25, 0)`. +pub fn banner_result_pose(x0: f32, y0: f32) -> Mat4 { + Mat4::from_translation(Vec3::new(x0 + 10.0, y0 + 40.0, 0.0)) + * Mat4::from_scale(Vec3::new(16.0, 16.0, -16.0)) + * Mat4::from_translation(Vec3::new(0.0, 0.25, 0.0)) +} + +/// The quads of `GuiGraphicsExtractor.bannerPattern` (the loom's result +/// preview) at `(x0, y0)`: base dye and `(texture, dye)` layers. +pub fn banner_result_quads( + renderer: &ItemRenderer, + sprites: &HashMap, + x0: f32, + y0: f32, + base: &str, + layers: &[(String, String)], +) -> Vec { + let mut quads = Vec::new(); + super::special::submit_banner_result( + renderer, + banner_result_pose(x0, y0), + base, + layers, + sprites, + &mut quads, + ); + // The winding normal flips with the pose's mirrored axis; PoseStack's + // normal matrix only takes the scale's signs, so the lit normal is the + // opposite one. + for q in &mut quads { + q.normal = -q.normal; + } + quads +} + +/// Draws the loom's result preview: the picture in picture is lit with +/// `Lighting.Entry.ITEMS_FLAT` and holds only its 20x40 rectangle. +pub fn draw_banner_result( + renderer: &ItemRenderer, + sprites: &HashMap, + batch: &mut HudBatch, + x0: f32, + y0: f32, + base: &str, + layers: &[(String, String)], +) { + let quads = banner_result_quads(renderer, sprites, x0, y0, base, layers); + draw_quads( + &quads, + items_flat_lights(), + batch, + [x0, y0, x0 + 20.0, y0 + 40.0], + 0.0, + ); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index fe9f0cfa8..a36b5b118 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -379,6 +379,33 @@ fn pot_sides(v: &Value) -> [Option; 4] { } } +/// `GuiBannerResultRenderer.renderToTexture` under `pose`: the standing +/// banner flag (`BannerFlagModel.setupAnim(0)`) in the banner base texture, +/// then `BannerRenderer.submitPatterns` (the base colour and up to 16 layers +/// of `(texture, dye)`). +pub(super) fn submit_banner_result( + renderer: &ItemRenderer, + pose: Mat4, + base: &str, + layers: &[(String, String)], + sprites: &HashMap, + sink: &mut dyn ItemSink, +) { + let Some(flag) = renderer.part("standing_banner_flag") else { + return; + }; + let mut part = |texture: &str, color: u32| { + if let Some(r) = sprites.get(texture).copied() { + draw(flag, "root", pose, &flag_pose, r, color, Foil::None, sink); + } + }; + part("entity/banner/banner_base", argb(-1)); + part("entity/banner/base", dye(base)); + for (texture, color) in layers.iter().take(16) { + part(texture, dye(color)); + } +} + /// `SpecialModelRenderer.submit`. #[allow(clippy::too_many_arguments)] pub(super) fn submit( diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java index c7c40a477..1de892a29 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java @@ -11,6 +11,9 @@ import net.minecraft.client.gui.Font; import net.minecraft.client.model.Model; import net.minecraft.client.model.geom.EntityModelSet; import net.minecraft.client.model.geom.LayerDefinitions; +import net.minecraft.client.model.object.banner.BannerFlagModel; +import net.minecraft.client.renderer.Sheets; +import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.blockentity.*; import net.minecraft.client.renderer.blockentity.state.*; @@ -333,17 +336,39 @@ public final class VanillaBlockEntityRenderOracle { } be.setLevel(level); } else if (be instanceof BannerBlockEntity && c.has("patterns")) { - var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder(); - var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN); - for (var e : c.getAsJsonArray("patterns")) { - var p = e.getAsJsonArray(); - var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString()))); - builder.add(holder, dye(p.get(1).getAsString())); - } - field(BannerBlockEntity.class, "patterns").set(be, builder.build()); + field(BannerBlockEntity.class, "patterns").set(be, patterns(c.getAsJsonArray("patterns"))); } } + /** [[pattern id, dye], ...] as BannerPatternLayers. */ + static BannerPatternLayers patterns(JsonArray list) { + var builder = new BannerPatternLayers.Builder(); + var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN); + for (var e : list) { + var p = e.getAsJsonArray(); + var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString()))); + builder.add(holder, dye(p.get(1).getAsString())); + } + return builder.build(); + } + + /** + * LoomScreen's result preview (GuiGraphicsExtractor.bannerPattern): the + * picture-in-picture pose of PictureInPictureRenderer.prepare for its 20x40 + * rectangle at GUI scale 1 (translate(w / 2, h), scale(16, 16, -16)), then + * GuiBannerResultRenderer.renderToTexture without its lighting setup + * (Lighting.Entry.ITEMS_FLAT, applied by the harness). + */ + static void loomResult(JsonObject loom, BannerFlagModel flag, SpriteGetter sprites, SubmitNodeCollector collector) { + var pose = new PoseStack(); + pose.translate(20 / 2.0F, 40.0F, 0.0F); + pose.scale(16.0F, 16.0F, -16.0F); + pose.translate(0.0F, 0.25F, 0.0F); + collector.submitModel(flag, 0.0F, pose, 15728880, OverlayTexture.NO_OVERLAY, -1, Sheets.BANNER_BASE, sprites, 0); + BannerRenderer.submitPatterns(sprites, pose, collector, 15728880, OverlayTexture.NO_OVERLAY, flag, 0.0F, true, + dye(loom.get("base").getAsString()), patterns(loom.getAsJsonArray("patterns"))); + } + /** Render-state values vanilla reads from the level (absent here). */ static void patch(BlockEntityRenderState rs, BlockState state, JsonObject c) { if (rs instanceof ChestRenderState chest) { @@ -381,6 +406,7 @@ public final class VanillaBlockEntityRenderOracle { var items = new net.minecraft.client.renderer.item.ItemModelResolver(null); var context = new BlockEntityRendererProvider.Context(null, null, items, null, models, font, sprites, null); Map renderers = (Map) BlockEntityRenderers.createEntityRenderers(context); + var loomFlag = new BannerFlagModel(models.bakeLayer(net.minecraft.client.model.geom.ModelLayers.STANDING_BANNER_FLAG)); var gson = new Gson(); var out = new StringBuilder(); for (String line : Files.readAllLines(Path.of(args[0]))) { @@ -389,6 +415,13 @@ public final class VanillaBlockEntityRenderOracle { var result = new JsonObject(); result.add("case", c); try { + if (c.has("loom")) { + var submits = new JsonArray(); + loomResult(c.getAsJsonObject("loom"), loomFlag, sprites, collector(submits)); + result.add("submits", submits); + out.append(gson.toJson(result)).append('\n'); + continue; + } BlockState state = parseState(c.get("block").getAsString()); var p = c.getAsJsonArray("pos"); var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt()); diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index e4c32ca2a..8d11389fd 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -72,6 +72,11 @@ def cases(): add(f'minecraft:{color}_wall_banner[facing={f}]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))]) add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)]) + # The loom's result preview (GuiBannerResultRenderer in a 20x40 picture in + # picture, lit with Lighting.Entry.ITEMS_FLAT): up to the loom's six layers, and 17. + for n in [0, 1, 2, 3, 6, 6, 17]: + out.append({'block': 'loom_result', 'loom': {'base': rng.choice(DYES), + 'patterns': [[rng.choice(patterns), rng.choice(DYES)] for _ in range(n)]}}) for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head', 'piglin_head', 'player_head']: wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head') @@ -147,15 +152,26 @@ def lights(): return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7]) +def items_flat_lights(): + """Lighting.Entry.ITEMS_FLAT: rotationY(-PI/8).rotateX(3PI/4) of the diffuse lights.""" + def rotate(v): + a, b = -math.pi / 8, math.pi * 3 / 4 + x, y, z = v + y, z = y * math.cos(b) - z * math.sin(b), y * math.sin(b) + z * math.cos(b) + return [x * math.cos(a) + z * math.sin(a), y, -x * math.sin(a) + z * math.cos(a)] + return tuple(rotate(l) for l in lights()) + + L0, L1 = lights() +FLAT = items_flat_lights() -def mix(normal): +def mix(normal, lit=(L0, L1)): d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal))) - return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4) + return min(1.0, (d(lit[0]) + d(lit[1])) * 0.6 + 0.4) -def vanilla_quads(submits): +def vanilla_quads(submits, lit=(L0, L1)): quads, other = [], [] for s in submits: custom = s['type'] == 'submitCustomGeometry' @@ -167,7 +183,7 @@ def vanilla_quads(submits): q = verts[i:i + 4] tint = q[0][3] & 0xFFFFFFFF # Custom geometry (beacon beams) is unlit; models get the entity shader's mix light. - b = 1.0 if custom else mix(q[0][8:11]) + b = 1.0 if custom else mix(q[0][8:11], lit) ch = lambda shift: int(((tint >> shift) & 255) * b) quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q], 'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7], @@ -206,7 +222,7 @@ def pair(vq, rq): def compare_case(v, r, tol): problems = [] - vq, other = vanilla_quads(v['submits']) + vq, other = vanilla_quads(v['submits'], FLAT if 'loom' in v['case'] else (L0, L1)) for s in other: if s['type'] == 'submitText': continue From eec52f90558b478e3073026d95a683238640ee5a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 02:22:55 +0200 Subject: [PATCH 13/14] The recipe book draws as vanilla's widgets do; test_recipe_book_render_parity horizon_client::recipe_book_screen lays out RecipeBookComponent's drawing (background, search EditBox, tab buttons, the filter CycleButton, the page of RecipeButtons with its number and arrows, the alternatives overlay, tooltips) and GhostSlots as vanilla's GUI calls with their poses, and the game paints them. The new harness builds vanilla's widgets for 600 random states (VanillaRecipeBookScreenOracle) and compares every call: 600/600. Ingredients keep their HolderSet order (tags in TagLoader order), which is how the overlay and ghost slots cycle; the book centres over the menu on narrow screens as widthTooNarrow does. Co-Authored-By: Claude Opus 5.5 --- .../examples/recipe_book_render_fixture.rs | 263 +++++++ crates/horizon-client/src/crafting.rs | 27 +- crates/horizon-client/src/game.rs | 4 + crates/horizon-client/src/game/recipe_book.rs | 604 +++++++------- crates/horizon-client/src/items.rs | 33 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu/place.rs | 2 +- crates/horizon-client/src/recipe_book.rs | 9 +- .../horizon-client/src/recipe_book_screen.rs | 734 ++++++++++++++++++ crates/horizon-client/src/stations.rs | 17 +- crates/horizon-client/src/ui.rs | 6 + .../parity/VanillaRecipeBookScreenOracle.java | 366 +++++++++ tools/test_recipe_book_render_parity.py | 165 ++++ 13 files changed, 1859 insertions(+), 372 deletions(-) create mode 100644 crates/horizon-client/examples/recipe_book_render_fixture.rs create mode 100644 crates/horizon-client/src/recipe_book_screen.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookScreenOracle.java create mode 100644 tools/test_recipe_book_render_parity.py diff --git a/crates/horizon-client/examples/recipe_book_render_fixture.rs b/crates/horizon-client/examples/recipe_book_render_fixture.rs new file mode 100644 index 000000000..cd904db79 --- /dev/null +++ b/crates/horizon-client/examples/recipe_book_render_fixture.rs @@ -0,0 +1,263 @@ +//! The recipe book's drawing, for tools/test_recipe_book_render_parity.py: +//! reads one JSON case per line (book type, GUI size, tabs, search box, +//! filter, recipe collections and page, overlay, ghost slots, cycling index, +//! mouse) and writes the calls `horizon_client::recipe_book_screen` makes, +//! in the oracle's JSON form. +//! +//! usage: recipe_book_render_fixture RESOURCES CASES OUTPUT +use horizon_client::{ + crafting::Recipes, + hud::{HudAtlas, HudBatch}, + items::{ItemStack, Items}, + lang, + recipe_book::{Book, BookType, Entry}, + recipe_book_screen::{ + ButtonView, Call, GhostView, ItemCall, OverlayRecipe, OverlayView, Run, Screen, Search, + TabView, draw, overlay_cells, overlay_origin, + }, +}; +use serde_json::{Value, json}; +use std::{fmt::Write as _, fs, path::Path}; + +fn runs(r: &[Run]) -> Value { + Value::Array( + r.iter() + .map(|r| json!([r.text, r.color, r.italic])) + .collect(), + ) +} +fn round(v: f32) -> f32 { + (v * 1e4).round() / 1e4 +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT"; + let root = Path::new(args.get(1).ok_or(usage)?); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let book = Book::build(&recipes, &items); + let atlas = HudAtlas::build(root)?; + let root_buf = root.to_path_buf(); + lang::set(lang::Language::load(&[&root_buf], lang::DEFAULT)); + let translate = |key: &str| lang::get(key); + let text_width = |s: &str| HudBatch::text_width(&atlas, s) as i32; + let mut out = String::new(); + for line in cases.lines() { + let case: Value = serde_json::from_str(line)?; + let int = |v: &Value| v.as_i64().unwrap_or(0) as i32; + let kind = match case["type"].as_str().unwrap_or_default() { + "crafting" => BookType::Crafting, + "furnace" => BookType::Furnace, + "blast_furnace" => BookType::BlastFurnace, + _ => BookType::Smoker, + }; + let filtering = case["filtering"].as_bool().unwrap_or(false); + let tab_list = kind.tabs(); + let tabs: Vec = case["tabs"] + .as_array() + .into_iter() + .flatten() + .map(|t| { + let (a, b) = tab_list[t["tab"].as_u64().unwrap_or(0) as usize].icons(); + TabView { + icons: (a.to_owned(), b.map(str::to_owned)), + selected: t["selected"].as_bool().unwrap_or(false), + anim: t["anim"].as_f64().unwrap_or(0.0) as f32, + } + }) + .collect(); + let s = &case["search"]; + let search = Search { + value: s["value"].as_str().unwrap_or_default().to_owned(), + cursor: s["cursor"].as_u64().unwrap_or(0) as usize, + highlight: s["highlight"].as_u64().unwrap_or(0) as usize, + display: s["display"].as_u64().unwrap_or(0) as usize, + focused: s["focused"].as_bool().unwrap_or(false), + blink_ms: s["blink"].as_u64().unwrap_or(0), + }; + // Each collection's recipes and craftable flags. + let collections: Vec> = case["collections"] + .as_array() + .into_iter() + .flatten() + .map(|c| { + c["recipes"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| Some((book.entry(r[0].as_str()?)?, r[1].as_bool()?))) + .collect() + }) + .collect(); + let page = case["page"].as_u64().unwrap_or(0) as usize; + let pages = collections.len().div_ceil(20); + let anims = case["buttonAnims"].as_array().cloned().unwrap_or_default(); + let shown = &collections[(20 * page).min(collections.len())..]; + let buttons: Vec = shown + .iter() + .take(20) + .enumerate() + .map(|(i, c)| ButtonView { + has_craftable: c.iter().any(|e| e.1), + entries: c + .iter() + .filter(|e| e.1 || !filtering) + .map(|e| vec![e.0.result.clone()]) + .collect(), + anim: anims.get(i).and_then(Value::as_f64).unwrap_or(0.0) as f32, + }) + .collect(); + let (xo, yo) = Screen { + book: kind, + width: int(&case["width"]), + height: int(&case["height"]), + narrow: case["narrow"].as_bool().unwrap_or(false), + mouse: (0, 0), + index: 0, + filtering, + search: &search, + tabs: &[], + buttons: &[], + page, + pages, + overlay: None, + ghost: None, + translate: &translate, + text_width: &text_width, + } + .origin(); + let overlay = case["overlay"].as_u64().map(|i| { + let i = i as usize; + let c = &shown[i]; + let mut recipes: Vec = c + .iter() + .filter(|e| e.1) + .map(|e| OverlayRecipe { + craftable: true, + cells: overlay_cells(&book, e.0), + }) + .collect(); + if !filtering { + recipes.extend(c.iter().filter(|e| !e.1).map(|e| OverlayRecipe { + craftable: false, + cells: overlay_cells(&book, e.0), + })); + } + let (x, y) = overlay_origin( + xo + 11 + 25 * (i as i32 % 5), + yo + 31 + 25 * (i as i32 / 5), + recipes.len(), + xo, + yo, + ); + OverlayView { x, y, recipes } + }); + let ghosts: Vec = case["ghost"] + .as_array() + .into_iter() + .flatten() + .map(|g| GhostView { + x: int(&g["x"]), + y: int(&g["y"]), + result: g["result"].as_bool().unwrap_or(false), + items: g["items"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(|i| ItemStack::new(i, 1)) + .collect(), + }) + .collect(); + let screen = Screen { + book: kind, + width: int(&case["width"]), + height: int(&case["height"]), + narrow: case["narrow"].as_bool().unwrap_or(false), + mouse: (int(&case["mouse"][0]), int(&case["mouse"][1])), + index: case["index"].as_u64().unwrap_or(0) as usize, + filtering, + search: &search, + tabs: &tabs, + buttons: &buttons, + page, + pages, + overlay: overlay.as_ref(), + ghost: case.get("ghost").map(|_| { + ( + int(&case["left"]), + int(&case["top"]), + case["big"].as_bool().unwrap_or(false), + ghosts.as_slice(), + ) + }), + translate: &translate, + text_width: &text_width, + }; + let draws: Vec = draw(&screen) + .into_iter() + .filter_map(|d| { + let m: Vec = d.pose.iter().map(|v| round(*v)).collect(); + let mut o = match d.call { + Call::Blit { + texture, + x, + y, + w, + h, + u, + v, + tw, + th, + } => json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h, + "u": u, "v": v, "tw": tw, "th": th}), + Call::Sprite { id, x, y, w, h } => { + json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h}) + } + Call::Fill { + x0, + y0, + x1, + y1, + color, + } => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}), + Call::Highlight { x0, y0, x1, y1 } => { + json!({"t": "highlight", "x0": x0, "y0": y0, "x1": x1, "y1": y1}) + } + Call::Text { + runs: r, + x, + y, + color, + shadow, + } => json!({"t": "text", "runs": runs(&r), "x": x, "y": y, "color": color, "shadow": shadow}), + Call::Item { call, stack, x, y } => { + if stack.count == 0 || &*stack.item == "minecraft:air" { + return None; + } + let t = match call { + ItemCall::Item => "item", + ItemCall::Fake => "fake", + ItemCall::Decorations => "decorations", + }; + json!({"t": t, "id": &*stack.item, "count": stack.count, "x": x, "y": y}) + } + Call::Tooltip(lines) => { + json!({"t": "tooltip", "lines": lines.iter().map(|l| runs(l)).collect::>()}) + } + Call::ItemTooltip { stack, more } => { + json!({"t": "item_tooltip", "id": &*stack.item, "more": more}) + } + Call::Stratum => json!({"t": "stratum"}), + }; + o["m"] = json!(m); + Some(o) + }) + .collect(); + let _ = writeln!(out, "{}", json!({ "draws": draws })); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 44a8bf994..fbcbb1b11 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -24,17 +24,26 @@ const FIREWORK_COLORS: [u32; 16] = [ 11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019, ]; -/// A set of accepted items (expanded from an item, list or tag). +/// A set of accepted items (expanded from an item, list or tag), and the +/// items in its `HolderSet` order (`Ingredient.display`'s `TagSlotDisplay`). #[derive(Clone, Debug)] -pub struct Ingredient(pub HashSet); +pub struct Ingredient(pub HashSet, pub Vec); impl Ingredient { + /// The items of a list, in order. + pub fn of(items: Vec) -> Self { + Self(items.iter().cloned().collect(), items) + } fn parse(v: &Value, items: &Items) -> Option { - let mut set = HashSet::new(); + let mut list: Vec = Vec::new(); let mut add = |s: &str| { - if let Some(tag) = s.strip_prefix('#') { - set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()); - } else { - set.insert(s.to_owned()); + let more: Vec = match s.strip_prefix('#') { + Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(), + None => vec![s.to_owned()], + }; + for i in more { + if !list.contains(&i) { + list.push(i); + } } }; match v { @@ -50,7 +59,7 @@ impl Ingredient { } _ => return None, } - (!set.is_empty()).then_some(Self(set)) + (!list.is_empty()).then(|| Self::of(list)) } pub fn test(&self, stack: &ItemStack) -> bool { self.0.contains(&*stack.item) @@ -1525,7 +1534,7 @@ mod tests { use crate::banner::BannerLayer; fn ingredient(items: &[&str]) -> Ingredient { - Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect()) } fn patterned(item: &str) -> ItemStack { let mut s = ItemStack::new(item, 1); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f86435c9b..972ad6fb8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2930,6 +2930,10 @@ impl Game<'_> { // `GuiGraphics.renderItem`: the resolved item model (tints, foil and // special renderers included), then the decorations. self.draw_item_model(batch, stack, x, y); + self.draw_item_decorations(batch, stack, x, y); + } + /// `GuiGraphicsExtractor.itemDecorations`: the count and damage bar. + fn draw_item_decorations(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { // GuiGraphicsExtractor.itemDecorations, laid out at the origin and // moved to (x, y). Horizon tracks no item cooldowns to shade yet. let max_damage = self diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index ca9fe9d89..8bf4e3340 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -11,6 +11,11 @@ use horizon_client::{ items::ItemStack, menu::place::{PostPlace, Stacked}, recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab}, + recipe_book_screen::{ + self as screen, ButtonView, Call, Drawn, GhostView, ItemCall, OverlayRecipe, OverlayView, + Screen as Layout, Search, TabView, + }, + text::{Style, Text}, ui::EditBox, }; use std::{ @@ -444,9 +449,12 @@ impl Game<'_> { // ---- geometry ---- + /// `RecipeBookComponent.getXOrigin` / `getYOrigin` (`widthTooNarrow` + /// centres the book over the menu). fn book_origin(&self, batch: &HudBatch) -> (f32, f32) { + let offset = if batch.width < NARROW { 0.0 } else { 86.0 }; ( - ((batch.width - WIDTH) / 2.0).floor() - 86.0, + ((batch.width - WIDTH) / 2.0).floor() - offset, ((batch.height - HEIGHT) / 2.0).floor(), ) } @@ -623,25 +631,9 @@ impl Game<'_> { let mut entries: Vec<(usize, bool)> = button.entries.iter().copied().filter(|e| e.1).collect(); entries.extend(button.entries.iter().copied().filter(|e| !e.1)); - let total = entries.len(); - let maxrow = if total <= 16 { 4 } else { 5 }; - let rows = total.div_ceil(maxrow); - let (mut x, mut y) = (bx, by); - let (center_x, center_y) = (xo + WIDTH / 2.0, yo + 13.0 + HEIGHT / 2.0); - let right = x + (total.min(maxrow) * 25) as f32; - let max_left = center_x + 50.0; - if right > max_left { - x -= 25.0 * ((right - max_left) / 25.0).floor(); - } - let bottom = y + rows as f32 * 25.0; - let max_bottom = center_y + 50.0; - if bottom > max_bottom { - y -= 25.0 * ((bottom - max_bottom) / 25.0).ceil(); - } - let max_top = center_y - 100.0; - if y < max_top { - y -= 25.0 * ((y - max_top) / 25.0).ceil(); - } + let (x, y) = + screen::overlay_origin(bx as i32, by as i32, entries.len(), xo as i32, yo as i32); + let (x, y) = (x as f32, y as f32); self.recipe_ui.overlay = Some(Overlay { x, y, entries }); } @@ -821,359 +813,293 @@ impl Game<'_> { use winit::keyboard::KeyCode; self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight) } + /// `GhostSlots.extractRenderState`, among the container's slots. fn draw_ghost(&mut self, batch: &mut HudBatch, book_type: BookType) { if self.recipe_ui.ghost.is_empty() { return; } - // Ghosts show only while their slots are empty. let (ox, oy) = self.inventory_origin(batch); - let step = self.swap_index(); let big_result = book_type != BookType::Crafting || self.craft_size == 3; - let ghosts: Vec<(usize, ItemStack, bool)> = self + let ghosts: Vec = self .recipe_ui .ghost .iter() - .filter(|g| !g.items.is_empty()) - .map(|g| (g.slot, g.items[step % g.items.len()].clone(), g.result)) + .map(|g| { + let (sx, sy) = self.slot_position(g.slot); + GhostView { + x: sx as i32, + y: sy as i32, + items: g.items.clone(), + result: g.result, + } + }) .collect(); - for (slot, stack, result) in ghosts { - let (sx, sy) = self.slot_position(slot); - let (x, y) = (ox + sx, oy + sy); - let atlas = &self.res.atlas; - let red = rgba(255, 0, 0, 0x30); - if result && big_result { - batch.fill(atlas, x - 4.0, y - 4.0, 24.0, 24.0, red); - } else { - batch.fill(atlas, x, y, 16.0, 16.0, red); - } - self.draw_item(batch, &stack, x, y); - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 0x30)); - } + let calls = screen::ghost(self.swap_index(), ox as i32, oy as i32, big_result, &ghosts); + self.paint_book(batch, &calls); } + /// `RecipeBookComponent.extractRenderState` and `extractTooltip`, laid + /// out by `horizon_client::recipe_book_screen`. fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) { let (xo, yo) = self.book_origin(batch); let cursor = self.cursor; - let atlas_name = "gui/recipe_book"; - // Background: the 147x166 page at (1, 1) of the texture. - if let Some(r) = self.res.atlas.sprites.get(atlas_name).copied() { - batch.rect_uv( - xo, - yo, - WIDTH, - HEIGHT, - sub_rect(r, [1.0, 1.0, WIDTH, HEIGHT]), - u32::MAX, - ); - } - // Search box. - if let Some(search) = self.recipe_ui.search.as_mut() { - search.x = xo + 25.0; - search.y = yo + 13.0; - search.draw(batch, &self.res.atlas, None); - if search.value.is_empty() && !search.focused { - let hint = self - .res - .stations - .enchantments - .translate("gui.recipebook.search_hint") - .unwrap_or("Search...") - .to_owned(); - batch.text( - &self.res.atlas, - &hint, - search.text_x(), - search.text_y(), - rgba(170, 170, 170, 255), - true, - ); - } - } - // Tabs. - let tabs = self.recipe_ui.view.tabs.clone(); - let current = self - .recipe_ui - .tab - .filter(|t| tabs.contains(t)) - .unwrap_or(Tab::Search); - let frame = self.frame_ticks; - for (n, tab) in tabs.iter().enumerate() { - let (x, y) = self.tab_pos(xo, yo, n); - let selected = *tab == current; - let name = if selected { "tab_selected" } else { "tab" }; - let sx = if selected { x - 2.0 } else { x }; - let start = batch.vertices.len(); - batch.sprite(&self.res.atlas, &sprite(name), sx, y); - let (a, b) = tab.icons(); - let shift = if selected { -2.0 } else { 0.0 }; - match b { - Some(b) => { - self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0); - self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0); + let atlas = &self.res.atlas; + let search = match self.recipe_ui.search.as_mut() { + Some(edit) => { + // The box's place, for clicks and typing. + edit.x = xo + 25.0; + edit.y = yo + 13.0; + let (display, blink_ms) = edit.view_state(atlas); + Search { + value: edit.value.clone(), + cursor: edit.cursor, + highlight: edit.highlight, + display, + focused: edit.focused, + blink_ms, } - None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0), } - if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) { - let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin(); - batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze); - entry.1 -= frame; + None => Search::default(), + }; + let ui = &self.recipe_ui; + let current = ui + .tab + .filter(|t| ui.view.tabs.contains(t)) + .unwrap_or(Tab::Search); + let tabs: Vec = ui + .view + .tabs + .iter() + .map(|tab| { + let (a, b) = tab.icons(); + TabView { + icons: (a.to_owned(), b.map(str::to_owned)), + selected: *tab == current, + anim: ui + .tab_anim + .iter() + .find(|e| e.0 == *tab) + .map_or(0.0, |e| e.1), + } + }) + .collect(); + let pages = ui.view.buttons.len().div_ceil(20); + let first = ui.page * 20; + let (buttons, overlay) = match ui.book.as_ref() { + Some(book) => { + let buttons: Vec = ui + .view + .buttons + .iter() + .enumerate() + .skip(first) + .take(20) + .map(|(n, b)| ButtonView { + has_craftable: b.craftable(), + entries: b + .entries + .iter() + .map(|e| vec![book.entries[e.0].result.clone()]) + .collect(), + anim: ui + .button_anim + .iter() + .find(|e| e.0 == n) + .map_or(0.0, |e| e.1), + }) + .collect(); + let overlay = ui.overlay.as_ref().map(|o| OverlayView { + x: o.x as i32, + y: o.y as i32, + recipes: o + .entries + .iter() + .map(|&(i, craftable)| OverlayRecipe { + craftable, + cells: screen::overlay_cells(book, &book.entries[i]), + }) + .collect(), + }); + (buttons, overlay) } + None => (Vec::new(), None), + }; + let translate = |key: &str| self.translate(key, key); + let text_width = |s: &str| HudBatch::text_width(atlas, s) as i32; + let layout = Layout { + book: book_type, + width: batch.width as i32, + height: batch.height as i32, + narrow: batch.width < NARROW, + mouse: (cursor.0.floor() as i32, cursor.1.floor() as i32), + index: self.swap_index(), + filtering: self.book_filtering(book_type), + search: &search, + tabs: &tabs, + buttons: &buttons, + page: ui.page, + pages, + overlay: overlay.as_ref(), + ghost: None, + translate: &translate, + text_width: &text_width, + }; + let calls = screen::draw(&layout); + let tooltip = self.paint_book(batch, &calls); + // The squeeze animations run down with the frames. + let frame = self.frame_ticks; + for e in &mut self.recipe_ui.tab_anim { + e.1 -= frame; + } + for e in &mut self.recipe_ui.button_anim { + e.1 -= frame; } self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0); - // Craftable filter. - let filtering = self.book_filtering(book_type); - let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0); - let prefix = if book_type == BookType::Crafting { - "" - } else { - "furnace_" - }; - let state = if filtering { - "filter_enabled" - } else { - "filter_disabled" - }; - let name = format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" }); - batch.sprite(&self.res.atlas, &sprite(&name), xo + 110.0, yo + 12.0); - // Recipe buttons. - let buttons = self.recipe_ui.view.buttons.clone(); - let pages = buttons.len().div_ceil(20); - let step = self.swap_index(); - let first = self.recipe_ui.page * 20; - let mut tooltip: Option> = None; - let overlay_open = self.recipe_ui.overlay.is_some(); - for n in 0..20 { - let Some(button) = buttons.get(first + n) else { - break; - }; - let (x, y) = Self::button_pos(xo, yo, n); - let anim_start = batch.vertices.len(); - let many = button.entries.len() > 1; - let name = match (button.craftable(), many) { - (true, true) => "slot_many_craftable", - (true, false) => "slot_craftable", - (false, true) => "slot_many_uncraftable", - (false, false) => "slot_uncraftable", - }; - batch.sprite(&self.res.atlas, &sprite(name), x, y); - let shown = button.entries[step % button.entries.len()].0; - let Some(stack) = self - .recipe_ui - .book - .as_ref() - .map(|b| ItemStack::new(&b.entries[shown].result.item, 1)) - else { - continue; - }; - let same_result = button.entries.iter().all(|e| { - self.recipe_ui - .book - .as_ref() - .is_some_and(|b| b.entries[e.0].result.item == b.entries[shown].result.item) - }); - let mut offset = 4.0; - if many && same_result { - self.draw_item_plain(batch, &stack, x + offset + 1.0, y + offset + 1.0); - offset -= 1.0; - } - self.draw_item_plain(batch, &stack, x + offset, y + offset); - if let Some(entry) = self - .recipe_ui - .button_anim - .iter_mut() - .find(|e| e.0 == first + n) - { - let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin(); - batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze); - entry.1 -= self.frame_ticks; - } - if inside(cursor, x, y, 25.0, 25.0) && !overlay_open { - let mut lines = self.stack_tooltip(&stack); - if many { - lines.push(( - self.translate("gui.recipebook.moreRecipes", "Right Click for More"), - u32::MAX, - )); - } - tooltip = Some(lines); - } - } self.recipe_ui.button_anim.retain(|e| e.1 > 0.0); - // Page arrows and number. - if pages > 1 { - let page_text = self - .translate("gui.recipebook.page", "%s/%s") - .replacen("%s", &(self.recipe_ui.page + 1).to_string(), 1) - .replacen("%s", &pages.to_string(), 1); - let w = HudBatch::text_width(&self.res.atlas, &page_text); - batch.text( - &self.res.atlas, - &page_text, - xo - (w / 2.0).floor() + 73.0, - yo + 141.0, - u32::MAX, - true, - ); - if self.recipe_ui.page + 1 < pages { - let hover = inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0); - let name = if hover { - "page_forward_highlighted" - } else { - "page_forward" - }; - batch.sprite(&self.res.atlas, &sprite(name), xo + 93.0, yo + 137.0); - if hover { - tooltip = Some(vec![( - self.translate("gui.recipebook.next_page", "Next Page"), - u32::MAX, - )]); - } - } - if self.recipe_ui.page > 0 { - let hover = inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0); - let name = if hover { - "page_backward_highlighted" - } else { - "page_backward" - }; - batch.sprite(&self.res.atlas, &sprite(name), xo + 38.0, yo + 137.0); - if hover { - tooltip = Some(vec![( - self.translate("gui.recipebook.previous_page", "Previous Page"), - u32::MAX, - )]); - } - } - } - if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) { - let key = if !filtering { - "gui.recipebook.toggleRecipes.all" - } else { - match book_type { - BookType::Crafting => "gui.recipebook.toggleRecipes.craftable", - BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable", - BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable", - BookType::Smoker => "gui.recipebook.toggleRecipes.smokable", - } - }; - tooltip = Some(vec![(self.translate(key, key), u32::MAX)]); - } - self.draw_overlay(batch, book_type); if let Some(lines) = tooltip { self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1); } } - /// An item without count or bars (`GuiGraphics.fakeItem`). - fn draw_item_plain(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { - let one = ItemStack { - count: 1, - damage: 0, - ..stack.clone() - }; - self.draw_item(batch, &one, x, y); - } - fn draw_overlay(&mut self, batch: &mut HudBatch, book_type: BookType) { - let Some(overlay) = self.recipe_ui.overlay.as_ref() else { - return; - }; - let (ox, oy, entries) = (overlay.x, overlay.y, overlay.entries.clone()); - let maxrow = if entries.len() <= 16 { 4 } else { 5 }; - let width = entries.len().min(maxrow) as f32 * 25.0 + 8.0; - let height = entries.len().div_ceil(maxrow) as f32 * 25.0 + 8.0; - horizon_client::ui::nine_slice( - batch, - &self.res.atlas, - &sprite("overlay_recipe"), - ox, - oy, - width, - height, - u32::MAX, - ); - let cursor = self.cursor; - let step = self.swap_index(); - let (gw, gh) = if book_type == BookType::Crafting { - (3, 3) - } else { - (1, 1) - }; - for (n, (index, craftable)) in entries.into_iter().enumerate() { - let x = ox + 4.0 + 25.0 * (n % maxrow) as f32; - let y = oy + 5.0 + 25.0 * (n / maxrow) as f32; - let hover = inside(cursor, x, y, 24.0, 24.0); - let family = if book_type == BookType::Crafting { - "crafting" - } else { - "furnace" - }; - let state = if craftable { "" } else { "_disabled" }; - let name = format!( - "{family}_overlay{state}{}", - if hover { "_highlighted" } else { "" } - ); - batch.sprite(&self.res.atlas, &sprite(&name), x, y); - let Some(entry) = self - .recipe_ui - .book - .as_ref() - .map(|b| b.entries[index].clone()) - else { - continue; - }; - // The recipe's layout in miniature, ingredients at 3/8 scale. - let mut cells: Vec<(f32, f32, ItemStack)> = Vec::new(); - if let Some(book) = self.recipe_ui.book.as_ref() { - let requirements = entry.requirements(); - match &entry.display { - Display::Furnace(ingredient) => { - let items = book.items_of(ingredient); - if !items.is_empty() { - let item = &items[step % items.len()]; - cells.push((3.0 + 7.0, 3.0 + 7.0, ItemStack::new(item, 1))); - } - } - Display::Shaped { .. } => { - for (ingredient, grid_index) in entry.grid_cells(gw, gh) { - if let Some(i) = ingredient { - let items = book.items_of(requirements[i]); - if !items.is_empty() { - let item = &items[step % items.len()]; - cells.push(( - 3.0 + (grid_index % 3) as f32 * 7.0, - 3.0 + (grid_index / 3) as f32 * 7.0, - ItemStack::new(item, 1), - )); - } - } - } - } - Display::Shapeless(list) => { - for (i, ingredient) in list.iter().enumerate() { - let items = book.items_of(ingredient); - if !items.is_empty() { - let item = &items[step % items.len()]; - cells.push(( - 3.0 + (i % 3) as f32 * 7.0, - 3.0 + (i / 3) as f32 * 7.0, - ItemStack::new(item, 1), - )); - } - } + /// Paints recipe book calls; returns the first tooltip set (vanilla keeps + /// the first one a frame asks for). + fn paint_book(&mut self, batch: &mut HudBatch, calls: &[Drawn]) -> Option> { + let mut tooltip: Option> = None; + for d in calls { + let start = batch.vertices.len(); + let atlas = &self.res.atlas; + match &d.call { + Call::Blit { + x, y, w, h, u, v, .. + } => { + if let Some(r) = atlas.sprites.get("gui/recipe_book").copied() { + let (w, h) = (*w as f32, *h as f32); + batch.rect_uv( + *x as f32, + *y as f32, + w, + h, + sub_rect(r, [*u, *v, w, h]), + u32::MAX, + ); } } + Call::Sprite { id, x, y, w, h } => { + let name = format!("gui/sprites/{id}"); + let native = atlas + .sprites + .get(&name) + .is_some_and(|r| r.w as i32 == *w && r.h as i32 == *h); + if native { + batch.sprite(atlas, &name, *x as f32, *y as f32); + } else { + horizon_client::ui::nine_slice( + batch, + atlas, + &name, + *x as f32, + *y as f32, + *w as f32, + *h as f32, + u32::MAX, + ); + } + } + Call::Fill { + x0, + y0, + x1, + y1, + color, + } => batch.fill( + atlas, + *x0 as f32, + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + argb(*color), + ), + Call::Highlight { x0, y0, x1, y1 } => { + let (a, b) = (*x0.min(x1), *x0.max(x1)); + batch.fill( + atlas, + a as f32, + *y0 as f32, + (b - a) as f32, + (y1 - y0) as f32, + rgba(0, 0, 255, 128), + ); + } + Call::Text { + runs, + x, + y, + color, + shadow, + } => { + let mut x = *x as f32; + for r in runs { + let style = Style { + color: (r.color >= 0).then_some(r.color as u32), + italic: r.italic.then_some(true), + ..Style::default() + }; + let t = Text::styled(r.text.clone(), style); + batch.text_styled(atlas, &t, x, *y as f32, argb(*color), *shadow); + x += atlas.font.width_text(&t); + } + } + Call::Item { call, stack, x, y } => match call { + ItemCall::Item | ItemCall::Fake => { + self.draw_item_model(batch, stack, *x as f32, *y as f32) + } + ItemCall::Decorations => { + self.draw_item_decorations(batch, stack, *x as f32, *y as f32) + } + }, + Call::Tooltip(lines) => { + if tooltip.is_none() { + tooltip = Some( + lines + .iter() + .map(|l| (l.iter().map(|r| r.text.as_str()).collect(), u32::MAX)) + .collect(), + ); + } + } + Call::ItemTooltip { stack, more } => { + if tooltip.is_none() { + let mut lines = self.stack_tooltip(stack); + if *more { + lines.push(( + self.translate( + "gui.recipebook.moreRecipes", + "Right Click for More", + ), + u32::MAX, + )); + } + tooltip = Some(lines); + } + } + Call::Stratum => {} } - for (cx, cy, stack) in cells { - // Draw at the origin, then shrink around the cell centre. - let start = batch.vertices.len(); - self.draw_item_plain(batch, &stack, 0.0, 0.0); - let (px, py) = (x + 2.0 + cx, y + 2.0 + cy); + if d.pose != screen::IDENTITY { + let m = d.pose; for v in &mut batch.vertices[start..] { - v.pos = [px + (v.pos[0] - 8.0) * 0.375, py + (v.pos[1] - 8.0) * 0.375]; + let [x, y] = v.pos; + v.pos = [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]; } } } + tooltip } } +/// An ARGB colour as a HUD vertex colour. +fn argb(c: i32) -> u32 { + let c = c as u32; + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8) +} + /// A sub-rectangle of a sprite given in texels. fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect { let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8b7ef4c4a..33d30f6f5 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -166,6 +166,9 @@ pub struct Items { /// Block tag name (without '#') -> member block names. pub block_tags: HashMap>, pub item_tags: HashMap>, + /// Item tags in vanilla's order (`TagLoader`: file order, nested tags in + /// place, first occurrence kept), the order `TagSlotDisplay` resolves. + pub item_tag_order: HashMap>, loot: HashMap, /// The `jukebox_song` registry. pub songs: HashMap, @@ -216,6 +219,13 @@ fn load_songs(root: &Path) -> HashMap { songs } pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>> { + Ok(load_tag_lists(root, kind)? + .into_iter() + .map(|(k, v)| (k, v.into_iter().collect())) + .collect()) +} +/// Every tag's contents in `TagLoader.tryBuildTag` order (a `LinkedHashSet`). +pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result>> { let dir = root.join(format!("data/minecraft/tags/{kind}")); let mut raw: HashMap> = HashMap::new(); fn walk(dir: &Path, base: &Path, raw: &mut HashMap>) -> Result<()> { @@ -246,29 +256,24 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>, - out: &mut HashSet, - depth: u32, - ) { + fn resolve(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { if depth > 32 { return; } for v in raw.get(name).into_iter().flatten() { if let Some(tag) = v.strip_prefix('#') { resolve(tag, raw, out, depth + 1); - } else { - out.insert(v.clone()); + } else if !out.contains(v) { + out.push(v.clone()); } } } Ok(raw .keys() .map(|k| { - let mut set = HashSet::new(); - resolve(k, &raw, &mut set, 0); - (k.clone(), set) + let mut list = Vec::new(); + resolve(k, &raw, &mut list, 0); + (k.clone(), list) }) .collect()) } @@ -456,6 +461,7 @@ impl Items { order, block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, + item_tag_order: load_tag_lists(root, "item")?, loot, songs: load_songs(root), }) @@ -470,6 +476,7 @@ impl Items { order: Vec::new(), block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, + item_tag_order: load_tag_lists(root, "item")?, loot: HashMap::new(), songs: HashMap::new(), }) @@ -481,6 +488,10 @@ impl Items { items: HashMap::new(), order: Vec::new(), block_tags: HashMap::new(), + item_tag_order: item_tags + .iter() + .map(|(k, v)| (k.clone(), v.iter().cloned().collect())) + .collect(), item_tags, loot: HashMap::new(), songs: HashMap::new(), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1f8893cd4..4e6d6bf05 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -85,6 +85,7 @@ pub mod projectiles; pub mod raid; pub mod random_sequences; pub mod recipe_book; +pub mod recipe_book_screen; pub mod save; pub mod scoreboard; pub mod scoreboard_cmd; diff --git a/crates/horizon-client/src/menu/place.rs b/crates/horizon-client/src/menu/place.rs index 9bd08afe2..85f537146 100644 --- a/crates/horizon-client/src/menu/place.rs +++ b/crates/horizon-client/src/menu/place.rs @@ -639,7 +639,7 @@ mod tests { use super::*; fn ing(items: &[&str]) -> Ingredient { - Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect()) } fn have(items: &[(&str, i32)]) -> Stacked { let mut s = Stacked::default(); diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 331a215a4..407502f55 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -405,11 +405,10 @@ impl Book { pub fn entry(&self, id: &str) -> Option<&Entry> { self.entries.iter().find(|e| e.id == id) } - /// `ingredient`'s items in registry order (the cycling order of ghost slots). + /// `ingredient`'s items as its display resolves them (the cycling order + /// of ghost slots and the overlay). pub fn items_of(&self, ingredient: &Ingredient) -> Vec { - let mut items: Vec = ingredient.0.iter().cloned().collect(); - items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone())); - items + ingredient.1.clone() } /// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a /// `FullTextSearchTree`): without a colon the text must occur in a @@ -714,7 +713,7 @@ mod tests { use super::*; fn ing(items: &[&str]) -> Ingredient { - Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect()) } #[test] fn small_recipes_are_centred_in_the_grid() { diff --git a/crates/horizon-client/src/recipe_book_screen.rs b/crates/horizon-client/src/recipe_book_screen.rs new file mode 100644 index 000000000..6d20e8500 --- /dev/null +++ b/crates/horizon-client/src/recipe_book_screen.rs @@ -0,0 +1,734 @@ +//! The recipe book's drawing (`RecipeBookComponent.extractRenderState`, +//! `extractTooltip` and `GhostSlots.extractRenderState`) as the list of GUI +//! calls vanilla's widgets make: the background, the search `EditBox`, the +//! `RecipeBookTabButton`s, the craftable filter `CycleButton`, the +//! `RecipeBookPage` with its `RecipeButton`s, page number and arrows, the +//! `OverlayRecipeComponent` and the ghost slots, each with the pose it is +//! drawn under. The game paints them; the render parity harness compares them. +use crate::{ + items::ItemStack, + recipe_book::{Book, BookType, Display, Entry}, +}; + +/// A styled run of text: its characters, colour (`-1` for the call's own) and italics. +#[derive(Clone, Debug, PartialEq)] +pub struct Run { + pub text: String, + pub color: i32, + pub italic: bool, +} +impl Run { + pub fn plain(text: impl Into) -> Self { + Run { + text: text.into(), + color: -1, + italic: false, + } + } +} + +/// How an item is drawn: `GuiGraphicsExtractor.item`, `fakeItem` or `itemDecorations`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ItemCall { + Item, + Fake, + Decorations, +} + +/// One GUI call. +#[derive(Clone, Debug)] +pub enum Call { + /// `blit` of a texture region (the book's background). + Blit { + texture: &'static str, + x: i32, + y: i32, + w: i32, + h: i32, + u: f32, + v: f32, + tw: i32, + th: i32, + }, + /// `blitSprite`, the id without its namespace. + Sprite { + id: String, + x: i32, + y: i32, + w: i32, + h: i32, + }, + Fill { + x0: i32, + y0: i32, + x1: i32, + y1: i32, + color: i32, + }, + /// `textHighlight` (the search box's selection). + Highlight { x0: i32, y0: i32, x1: i32, y1: i32 }, + Text { + runs: Vec, + x: i32, + y: i32, + color: i32, + shadow: bool, + }, + Item { + call: ItemCall, + stack: ItemStack, + x: i32, + y: i32, + }, + /// A widget's tooltip lines. + Tooltip(Vec>), + /// The hovered recipe button's tooltip: its display stack's own tooltip, + /// then "Right Click for More" when it has several recipes. + ItemTooltip { stack: ItemStack, more: bool }, + /// `nextStratum`. + Stratum, +} + +/// A call and the pose (`Matrix3x2f` m00, m01, m10, m11, m20, m21) it is made under. +#[derive(Clone, Debug)] +pub struct Drawn { + pub call: Call, + pub pose: [f32; 6], +} + +pub const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// JOML `Matrix3x2f.translate`. +fn translate(m: [f32; 6], x: f32, y: f32) -> [f32; 6] { + [ + m[0], + m[1], + m[2], + m[3], + m[0] * x + m[2] * y + m[4], + m[1] * x + m[3] * y + m[5], + ] +} +/// JOML `Matrix3x2f.scale`. +fn scale(m: [f32; 6], x: f32, y: f32) -> [f32; 6] { + [m[0] * x, m[1] * x, m[2] * y, m[3] * y, m[4], m[5]] +} + +/// The search box (`EditBox` fields). +#[derive(Clone, Debug, Default)] +pub struct Search { + pub value: String, + /// Cursor, selection end and first shown character, in characters. + pub cursor: usize, + pub highlight: usize, + pub display: usize, + pub focused: bool, + /// Milliseconds since the box was focused (`TextCursorUtils.isCursorVisible`). + pub blink_ms: u64, +} + +/// A visible tab, in order: its icons, whether selected, its squeeze time left. +#[derive(Clone, Debug)] +pub struct TabView { + pub icons: (String, Option), + pub selected: bool, + pub anim: f32, +} + +/// A recipe button: its collection has a craftable recipe; the display +/// stacks of each selected recipe; the squeeze time left. +#[derive(Clone, Debug)] +pub struct ButtonView { + pub has_craftable: bool, + pub entries: Vec>, + pub anim: f32, +} + +/// A recipe of the overlay: craftable, and its ingredient cells (grid +/// x, y and the stacks the cell cycles through). +#[derive(Clone, Debug)] +pub struct OverlayRecipe { + pub craftable: bool, + pub cells: Vec<(i32, i32, Vec)>, +} + +/// The alternatives overlay of a button, at the corner [`overlay_origin`] gives. +#[derive(Clone, Debug)] +pub struct OverlayView { + pub x: i32, + pub y: i32, + /// Craftable recipes first. + pub recipes: Vec, +} + +/// A ghost slot: its position in the menu, the stacks it cycles through, +/// and whether it is the result slot. +#[derive(Clone, Debug)] +pub struct GhostView { + pub x: i32, + pub y: i32, + pub items: Vec, + pub result: bool, +} + +/// What the recipe book shows. +pub struct Screen<'a> { + pub book: BookType, + /// GUI size and `widthTooNarrow`. + pub width: i32, + pub height: i32, + pub narrow: bool, + pub mouse: (i32, i32), + /// `slotSelectTime.currentIndex()`. + pub index: usize, + pub filtering: bool, + pub search: &'a Search, + pub tabs: &'a [TabView], + /// The current page's buttons. + pub buttons: &'a [ButtonView], + pub page: usize, + pub pages: usize, + pub overlay: Option<&'a OverlayView>, + /// The container's corner, whether its result slot is big, and the ghost slots. + pub ghost: Option<(i32, i32, bool, &'a [GhostView])>, + /// Translations. + pub translate: &'a dyn Fn(&str) -> String, + /// `Font.width`. + pub text_width: &'a dyn Fn(&str) -> i32, +} + +impl Screen<'_> { + /// `RecipeBookComponent.getXOrigin` and `getYOrigin`. + pub fn origin(&self) -> (i32, i32) { + let offset = if self.narrow { 0 } else { 86 }; + ((self.width - 147) / 2 - offset, (self.height - 166) / 2) + } + fn hovered(&self, x: i32, y: i32, w: i32, h: i32) -> bool { + let (mx, my) = self.mouse; + mx >= x && my >= y && mx < x + w && my < y + h + } + /// `Font.plainSubstrByWidth`. + fn substr_by_width<'s>(&self, s: &'s str, max: i32) -> &'s str { + let mut end = 0; + for (i, c) in s.char_indices() { + if (self.text_width)(&s[..i + c.len_utf8()]) > max { + break; + } + end = i + c.len_utf8(); + } + &s[..end] + } +} + +/// The recipe book's calls, in vanilla's order. +pub fn draw(s: &Screen) -> Vec { + let mut out = Vec::new(); + let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose }); + let (xo, yo) = s.origin(); + put( + Call::Blit { + texture: "textures/gui/recipe_book.png", + x: xo, + y: yo, + w: 147, + h: 166, + u: 1.0, + v: 1.0, + tw: 256, + th: 256, + }, + IDENTITY, + ); + search_box(s, xo + 25, yo + 13, &mut put); + // updateTabs. + let offset = if s.narrow { 0 } else { 86 }; + let tab_x = (s.width - 147) / 2 - offset - 30; + let tab_y = (s.height - 166) / 2 + 3; + for (n, tab) in s.tabs.iter().enumerate() { + let (x, y) = (tab_x, tab_y + 27 * n as i32); + let mut pose = IDENTITY; + if tab.anim > 0.0 { + let squeeze = squeeze(tab.anim); + let (cx, cy) = ((x + 8) as f32, (y + 12) as f32); + pose = translate(scale(translate(pose, cx, cy), 1.0, squeeze), -cx, -cy); + } + let sprite = if tab.selected { + "recipe_book/tab_selected" + } else { + "recipe_book/tab" + }; + let left = if tab.selected { -2 } else { 0 }; + put(sprite_call(sprite, x + left, y, 35, 27), pose); + let fake = |id: &str, x: i32| Call::Item { + call: ItemCall::Fake, + stack: ItemStack::new(id, 1), + x, + y: y + 5, + }; + match &tab.icons.1 { + Some(second) => { + put(fake(&tab.icons.0, x + 3 + left), pose); + put(fake(second, x + 14 + left), pose); + } + None => put(fake(&tab.icons.0, x + 9 + left), pose), + } + } + // The craftable filter. + let (fx, fy) = (xo + 110, yo + 12); + let hover = s.hovered(fx, fy, 26, 16); + let prefix = if s.book == BookType::Crafting { + "recipe_book/" + } else { + "recipe_book/furnace_" + }; + let state = if s.filtering { + "filter_enabled" + } else { + "filter_disabled" + }; + put( + sprite_call( + &format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" }), + fx, + fy, + 26, + 16, + ), + IDENTITY, + ); + if hover { + let key = if !s.filtering { + "gui.recipebook.toggleRecipes.all" + } else { + match s.book { + BookType::Crafting => "gui.recipebook.toggleRecipes.craftable", + BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable", + BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable", + BookType::Smoker => "gui.recipebook.toggleRecipes.smokable", + } + }; + put( + Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]), + IDENTITY, + ); + } + // RecipeBookPage.extractRenderState. + if s.pages > 1 { + let text = (s.translate)("gui.recipebook.page") + .replacen("%s", &(s.page + 1).to_string(), 1) + .replacen("%s", &s.pages.to_string(), 1); + let w = (s.text_width)(&text); + put( + Call::Text { + runs: vec![Run::plain(text)], + x: xo - w / 2 + 73, + y: yo + 141, + color: -1, + shadow: true, + }, + IDENTITY, + ); + } + let mut hovered = None; + for (i, b) in s.buttons.iter().enumerate().take(20) { + let (x, y) = (xo + 11 + 25 * (i as i32 % 5), yo + 31 + 25 * (i as i32 / 5)); + let many = b.entries.len() > 1; + let sprite = match (b.has_craftable, many) { + (true, true) => "recipe_book/slot_many_craftable", + (true, false) => "recipe_book/slot_craftable", + (false, true) => "recipe_book/slot_many_uncraftable", + (false, false) => "recipe_book/slot_uncraftable", + }; + let mut pose = IDENTITY; + if b.anim > 0.0 { + let squeeze = squeeze(b.anim); + let (cx, cy) = ((x + 8) as f32, (y + 12) as f32); + pose = translate(scale(translate(pose, cx, cy), squeeze, squeeze), -cx, -cy); + } + put(sprite_call(sprite, x, y, 25, 25), pose); + let stack = display_stack(&b.entries, s.index); + let mut offset = 4; + if many && same_result_display(&b.entries) { + put( + Call::Item { + call: ItemCall::Item, + stack: stack.clone(), + x: x + offset + 1, + y: y + offset + 1, + }, + pose, + ); + offset -= 1; + } + put( + Call::Item { + call: ItemCall::Fake, + stack: stack.clone(), + x: x + offset, + y: y + offset, + }, + pose, + ); + if s.hovered(x, y, 25, 25) { + hovered = Some((stack, many)); + } + } + let arrows = [ + ( + s.pages > 1 && s.page + 1 < s.pages, + xo + 93, + "recipe_book/page_forward", + "gui.recipebook.next_page", + ), + ( + s.pages > 1 && s.page > 0, + xo + 38, + "recipe_book/page_backward", + "gui.recipebook.previous_page", + ), + ]; + for (visible, x, sprite, key) in arrows { + if !visible { + continue; + } + let hover = s.hovered(x, yo + 137, 12, 17); + let id = if hover { + format!("{sprite}_highlighted") + } else { + sprite.to_owned() + }; + put(sprite_call(&id, x, yo + 137, 12, 17), IDENTITY); + if hover { + put( + Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]), + IDENTITY, + ); + } + } + put(Call::Stratum, IDENTITY); + if let Some(o) = s.overlay { + overlay(s, o, &mut put); + } + // RecipeBookPage.extractTooltip. + if let Some((stack, more)) = hovered + && s.overlay.is_none() + { + put(Call::ItemTooltip { stack, more }, IDENTITY); + } + if let Some((left, top, big, ghosts)) = s.ghost { + out.extend(ghost(s.index, left, top, big, ghosts)); + } + out +} + +/// `GhostSlots.extractRenderState` for a container whose corner is `(left, top)`. +pub fn ghost(index: usize, left: i32, top: i32, big: bool, ghosts: &[GhostView]) -> Vec { + let mut out = Vec::new(); + let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose }); + let pose = translate(IDENTITY, left as f32, top as f32); + for g in ghosts.iter().filter(|g| !g.items.is_empty()) { + let (x, y) = (g.x, g.y); + if g.result && big { + put(fill(x - 4, y - 4, x + 20, y + 20, 822_018_048), pose); + } else { + put(fill(x, y, x + 16, y + 16, 822_018_048), pose); + } + let stack = g.items[index % g.items.len()].clone(); + put( + Call::Item { + call: ItemCall::Fake, + stack: stack.clone(), + x, + y, + }, + pose, + ); + put(fill(x, y, x + 16, y + 16, 822_083_583), pose); + if g.result { + put( + Call::Item { + call: ItemCall::Decorations, + stack, + x, + y, + }, + pose, + ); + } + } + out +} + +/// `1 + 0.1 sin(t / 15 * PI)`, the squeeze of new recipes' buttons and tabs. +fn squeeze(time: f32) -> f32 { + 1.0 + 0.1 * f64::from(time / 15.0 * std::f32::consts::PI).sin() as f32 +} + +fn sprite_call(id: &str, x: i32, y: i32, w: i32, h: i32) -> Call { + Call::Sprite { + id: id.to_owned(), + x, + y, + w, + h, + } +} +fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: i32) -> Call { + Call::Fill { + x0, + y0, + x1, + y1, + color, + } +} + +/// `RecipeButton.getDisplayStack`. +fn display_stack(entries: &[Vec], index: usize) -> ItemStack { + let n = entries.len().max(1); + let (offset, entry) = (index / n, index % n); + match entries.get(entry) { + Some(items) if !items.is_empty() => items[offset % items.len()].clone(), + _ => ItemStack::new("minecraft:air", 0), + } +} +/// `RecipeButton.allRecipesHaveSameResultDisplay`. +fn same_result_display(entries: &[Vec]) -> bool { + let mut items = entries.iter().flatten(); + let Some(first) = items.next() else { + return true; + }; + items.all(|s| first.same_item_same_components(s)) +} + +/// `EditBox.extractWidgetRenderState` for the recipe book's search box. +fn search_box(s: &Screen, x: i32, y: i32, put: &mut impl FnMut(Call, [f32; 6])) { + let b = s.search; + let (w, h) = (81, 9 + 5); + let sprite = if b.focused { + "widget/text_field_highlighted" + } else { + "widget/text_field" + }; + put(sprite_call(sprite, x, y, w, h), IDENTITY); + let (text_x, text_y) = (x + 4, y + (h - 8) / 2); + let color = -1; + let chars: Vec = b.value.chars().collect(); + let tail: String = chars[b.display.min(chars.len())..].iter().collect(); + let displayed = s.substr_by_width(&tail, w - 8).to_owned(); + let shown = displayed.chars().count(); + let rel_cursor = b.cursor as i64 - b.display as i64; + let on_screen = rel_cursor >= 0 && rel_cursor <= shown as i64; + let visible = b.focused && (b.blink_ms / 300).is_multiple_of(2) && on_screen; + let mut draw_x = text_x; + let rel_highlight = (b.highlight as i64 - b.display as i64).clamp(0, shown as i64) as usize; + let prefix = |n: usize| displayed.chars().take(n).collect::(); + if !displayed.is_empty() { + let half = if on_screen { + prefix(rel_cursor as usize) + } else { + displayed.clone() + }; + let width = (s.text_width)(&half); + put( + Call::Text { + runs: runs_of(half), + x: draw_x, + y: text_y, + color, + shadow: true, + }, + IDENTITY, + ); + draw_x += width + 1; + } + let insert = b.cursor < chars.len() || chars.len() >= 50; + let mut cursor_x = draw_x; + if !on_screen { + cursor_x = if rel_cursor > 0 { text_x + w } else { text_x }; + } else if insert { + cursor_x -= 1; + draw_x -= 1; + } + if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown { + let rest: String = displayed.chars().skip(rel_cursor as usize).collect(); + put( + Call::Text { + runs: runs_of(rest), + x: draw_x, + y: text_y, + color, + shadow: true, + }, + IDENTITY, + ); + } + if displayed.is_empty() && !b.focused { + // SEARCH_HINT: gray, italic. + put( + Call::Text { + runs: vec![Run { + text: (s.translate)("gui.recipebook.search_hint"), + color: 0xAAAAAA, + italic: true, + }], + x: draw_x, + y: text_y, + color, + shadow: true, + }, + IDENTITY, + ); + } + if rel_highlight as i64 != rel_cursor { + let highlight_x = text_x + (s.text_width)(&prefix(rel_highlight)); + put( + Call::Highlight { + x0: cursor_x.min(x + w), + y0: text_y - 1, + x1: (highlight_x - 1).min(x + w), + y1: text_y + 1 + 9, + }, + IDENTITY, + ); + } + if visible { + if insert { + put( + fill(cursor_x, text_y - 1, cursor_x + 1, text_y + 10, color), + IDENTITY, + ); + } else { + put( + Call::Text { + runs: vec![Run::plain("_")], + x: cursor_x, + y: text_y, + color, + shadow: true, + }, + IDENTITY, + ); + } + } +} +fn runs_of(text: String) -> Vec { + if text.is_empty() { + Vec::new() + } else { + vec![Run::plain(text)] + } +} + +/// `OverlayRecipeComponent.init`'s corner for `total` recipes opened from the +/// button at `(button_x, button_y)` of the book at `(xo, yo)`. +pub fn overlay_origin(button_x: i32, button_y: i32, total: usize, xo: i32, yo: i32) -> (i32, i32) { + let total = total as i32; + let max_row = if total <= 16 { 4 } else { 5 }; + let rows = (total as f32 / max_row as f32).ceil() as i32; + let (mut x, mut y) = (button_x, button_y); + let width = 25.0f32; + let (center_x, center_y) = (xo + 147 / 2, yo + 13 + 166 / 2); + let right = (x + total.min(max_row) * 25) as f32; + let max_left = (center_x + 50) as f32; + if right > max_left { + x = (x as f32 - width * ((right - max_left) / width) as i32 as f32) as i32; + } + let bottom = (y + rows * 25) as f32; + let max_bottom = (center_y + 50) as f32; + if bottom > max_bottom { + y = (y as f32 - width * ((bottom - max_bottom) / width).ceil()) as i32; + } + let top = y as f32; + let max_top = (center_y - 100) as f32; + if top < max_top { + y = (y as f32 - width * ((top - max_top) / width).ceil()) as i32; + } + (x, y) +} + +/// `OverlayRecipeComponent.extractRenderState`. +fn overlay(s: &Screen, o: &OverlayView, put: &mut impl FnMut(Call, [f32; 6])) { + let total = o.recipes.len() as i32; + let max_row = if total <= 16 { 4 } else { 5 }; + let (x, y) = (o.x, o.y); + let columns = total.min(max_row); + let height = (total as f32 / max_row as f32).ceil() as i32; + put( + sprite_call( + "recipe_book/overlay_recipe", + x, + y, + columns * 25 + 8, + height * 25 + 8, + ), + IDENTITY, + ); + let family = if s.book == BookType::Crafting { + "crafting" + } else { + "furnace" + }; + for (i, r) in o.recipes.iter().enumerate() { + let i = i as i32; + let (bx, by) = (x + 4 + 25 * (i % max_row), y + 5 + 25 * (i / max_row)); + let hover = s.hovered(bx, by, 24, 24); + let id = format!( + "recipe_book/{family}_overlay{}{}", + if r.craftable { "" } else { "_disabled" }, + if hover { "_highlighted" } else { "" } + ); + put(sprite_call(&id, bx, by, 24, 24), IDENTITY); + let (gx, gy) = ((bx + 2) as f32, (by + 2) as f32); + for (cx, cy, items) in &r.cells { + let pose = translate( + scale( + translate(IDENTITY, gx + (3 + cx * 7) as f32, gy + (3 + cy * 7) as f32), + 0.375, + 0.375, + ), + -8.0, + -8.0, + ); + put( + Call::Item { + call: ItemCall::Item, + stack: items[s.index % items.len()].clone(), + x: 0, + y: 0, + }, + pose, + ); + } + } +} + +/// The ingredient cells a recipe shows in the overlay +/// (`OverlayCraftingRecipeButton` / `OverlaySmeltingRecipeButton.calculateIngredientsPositions`). +pub fn overlay_cells(book: &Book, entry: &Entry) -> Vec<(i32, i32, Vec)> { + let stacks = |ingredient| -> Vec { + book.items_of(ingredient) + .iter() + .map(|i| ItemStack::new(i, 1)) + .collect() + }; + let mut out = Vec::new(); + match &entry.display { + Display::Furnace(i) => out.push((1, 1, stacks(i))), + Display::Shaped { .. } => { + let requirements = entry.requirements(); + for (ingredient, grid) in entry.grid_cells(3, 3) { + if let Some(i) = ingredient { + out.push((grid as i32 % 3, grid as i32 / 3, stacks(requirements[i]))); + } + } + } + Display::Shapeless(list) => { + for (i, ingredient) in list.iter().enumerate() { + out.push((i as i32 % 3, i as i32 / 3, stacks(ingredient))); + } + } + } + out.retain(|c| !c.2.is_empty()); + out +} diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 5fdf94ab4..dd67312db 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -10,7 +10,7 @@ use crate::{ }; use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; -use std::{collections::HashSet, fs, path::Path, sync::Arc}; +use std::{fs, path::Path, sync::Arc}; /// Everything the workstation menus read, loaded once with the resources. pub struct StationData { @@ -457,7 +457,7 @@ pub struct StationRecipes { pub trim_materials: Vec<(String, String)>, } fn ingredient(v: &Value, items: &Items) -> Ingredient { - let mut set = HashSet::new(); + let mut list: Vec = Vec::new(); for s in match v { Value::String(s) => vec![s.clone()], Value::Array(a) => a @@ -466,14 +466,17 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient { .collect(), _ => vec![], } { - match s.strip_prefix('#') { - Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()), - None => { - set.insert(s); + let more = match s.strip_prefix('#') { + Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(), + None => vec![s], + }; + for i in more { + if !list.contains(&i) { + list.push(i); } } } - Ingredient(set) + Ingredient::of(list) } impl StationRecipes { pub fn load(root: &Path, items: &Items) -> Self { diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index cc8ac6054..b1340eb8a 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -701,6 +701,12 @@ impl EditBox { } true } + /// The first shown character after scrolling to the cursor, and the + /// milliseconds since the field was focused (the cursor's blink). + pub fn view_state(&mut self, atlas: &HudAtlas) -> (usize, u64) { + self.layout(atlas); + (self.display, self.focused_at.elapsed().as_millis() as u64) + } /// Draw the field; `format` styles the visible text (command colouring). pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) { self.layout(atlas); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookScreenOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookScreenOracle.java new file mode 100644 index 000000000..adbf32b75 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookScreenOracle.java @@ -0,0 +1,366 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.renderpearl.api.pipeline.RenderPipeline; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.ClientRecipeBook; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.CycleButton; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.client.gui.components.WidgetSprites; +import net.minecraft.client.gui.components.WidgetTooltipHolder; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner; +import net.minecraft.client.gui.screens.recipebook.*; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Util; +import net.minecraft.util.context.ContextMap; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeManager; +import net.minecraft.world.item.crafting.display.RecipeDisplayEntry; +import net.minecraft.world.item.crafting.display.RecipeDisplayId; +import net.minecraft.world.item.crafting.display.SlotDisplay; +import net.minecraft.world.item.crafting.display.SlotDisplayContext; +import net.minecraft.world.level.Level; +import org.joml.Matrix3x2fStack; + +/** + * Original oracle for the recipe book's drawing (RecipeBookComponent.extractRenderState, + * its tooltips and GhostSlots.extractRenderState): the background, the real + * search EditBox, RecipeBookTabButtons, the craftable filter CycleButton, a + * RecipeBookPage of RecipeButtons over real RecipeCollections with its page + * arrows and number, the OverlayRecipeComponent of a button and ghost slots, + * each built as RecipeBookComponent.initVisuals and RecipeBookPage.init build + * them, with the state the case gives (tab and button animations, the cycling + * index, the search box, the mouse). Every GuiGraphicsExtractor call is recorded + * with its pose. The hovered button's tooltip is recorded as its display stack + * (RecipeButton.getTooltipText adds the item's own tooltip, compared elsewhere). + */ +public final class VanillaRecipeBookScreenOracle { + static Object unsafe; + static Method allocate; + + @SuppressWarnings("unchecked") + static T alloc(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static Field field(Class owner, String name) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static void put(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f); + Class t = f.getType(); + String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject"; + Class param = t.isPrimitive() ? t : Object.class; + unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value); + } + + static float round(float v) { return Math.round(v * 1e4f) / 1e4f; } + + /** A text's styled runs: [text, rgb or -1, italic]. */ + static JsonArray runs(FormattedCharSequence s) { + var out = new JsonArray(); + StringBuilder text = new StringBuilder(); + int[] style = {Integer.MIN_VALUE, 0}; + s.accept((i, st, cp) -> { + int color = st.getColor() == null ? -1 : st.getColor().getValue(); + int italic = st.isItalic() ? 1 : 0; + if (text.length() > 0 && (color != style[0] || italic != style[1])) { + var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r); + text.setLength(0); + } + style[0] = color; style[1] = italic; + text.appendCodePoint(cp); + return true; + }); + if (text.length() > 0) { + var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r); + } + return out; + } + + static String id(ItemStack s) { return s.isEmpty() ? "minecraft:air" : s.getItem().builtInRegistryHolder().key().identifier().toString(); } + + /** Records every GuiGraphicsExtractor call with the pose it was made under. */ + public static final class Capture extends GuiGraphicsExtractor { + JsonArray draws = new JsonArray(); + Matrix3x2fStack stack = new Matrix3x2fStack(16); + private Capture() { super(null, null, 0, 0); } + @Override public Matrix3x2fStack pose() { return stack; } + @Override public void nextStratum() { add("stratum"); } + @Override public void requestCursor(com.mojang.blaze3d.platform.cursor.CursorType type) { } + @Override public boolean containsPointInScissor(int x, int y) { return true; } + JsonObject add(String type) { + var o = new JsonObject(); + o.addProperty("t", type); + var m = new JsonArray(); + for (float v : new float[] {stack.m00(), stack.m01(), stack.m10(), stack.m11(), stack.m20(), stack.m21()}) m.add(round(v)); + o.add("m", m); + draws.add(o); + return o; + } + @Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) { + var o = add("fill"); + o.addProperty("x0", Math.min(x0, x1)); o.addProperty("y0", Math.min(y0, y1)); + o.addProperty("x1", Math.max(x0, x1)); o.addProperty("y1", Math.max(y0, y1)); + o.addProperty("color", color); + } + @Override public void textHighlight(int x0, int y0, int x1, int y1, boolean invert) { + var o = add("highlight"); + o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1); + } + @Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { + var o = add("sprite"); + o.addProperty("id", id.getPath()); + o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h); + } + @Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int srcW, int srcH, int texW, int texH, int color) { + var o = add("blit"); + o.addProperty("texture", texture.getPath()); + o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h); + o.addProperty("u", u); o.addProperty("v", v); o.addProperty("tw", texW); o.addProperty("th", texH); + } + @Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) { + var o = add("text"); + o.add("runs", runs(str)); + o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow); + } + @Override public void text(Font font, String str, int x, int y, int color, boolean shadow) { + if (str != null) text(font, FormattedCharSequence.forward(str, net.minecraft.network.chat.Style.EMPTY), x, y, color, shadow); + } + void item(String kind, ItemStack s, int x, int y) { + if (s.isEmpty()) return; + var o = add(kind); + o.addProperty("id", id(s)); o.addProperty("count", s.getCount()); + o.addProperty("x", x); o.addProperty("y", y); + } + @Override public void item(ItemStack s, int x, int y) { item("item", s, x, y); } + @Override public void item(ItemStack s, int x, int y, int seed) { item("item", s, x, y); } + @Override public void fakeItem(ItemStack s, int x, int y) { item("fake", s, x, y); } + @Override public void fakeItem(ItemStack s, int x, int y, int seed) { item("fake", s, x, y); } + @Override public void itemDecorations(Font font, ItemStack s, int x, int y, String count) { item("decorations", s, x, y); } + @Override public void setTooltipForNextFrame(Font font, List lines, Optional image, + ClientTooltipPositioner positioner, int x, int y, boolean replace, Identifier style) { + var o = add("tooltip"); + var a = new JsonArray(); + for (var l : lines) a.add(runs(l)); + o.add("lines", a); + } + } + + /** The window's text input area, which a focused EditBox moves: not tracked here. */ + static final class NoTextInput extends com.mojang.blaze3d.platform.TextInputManager { + NoTextInput() { super(null); } + @Override public void setTextInputArea(int x0, int y0, int x1, int y1) { } + } + + static List displays(RecipeManager recipes, String id) { + List out = new ArrayList<>(); + recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(id)), out::add); + return out; + } + + /** A collection of the given recipes' displays; `craftable` lists the recipes the inventory can craft. */ + @SuppressWarnings("unchecked") + static RecipeCollection collection(RecipeManager recipes, JsonObject b) throws Exception { + List entries = new ArrayList<>(); + Set craftable = (Set) new HashSet(); + for (var r : b.getAsJsonArray("recipes")) { + var a = r.getAsJsonArray(); + for (var e : displays(recipes, a.get(0).getAsString())) { + entries.add(e); + if (a.get(1).getAsBoolean()) craftable.add(e.id()); + } + } + var c = new RecipeCollection(entries); + ((Set) field(RecipeCollection.class, "selected").get(c)).addAll(entries.stream().map(RecipeDisplayEntry::id).toList()); + ((Set) field(RecipeCollection.class, "craftable").get(c)).addAll(craftable); + return c; + } + + /** The widget's tooltip shows on this frame when hovered (its delay has passed). */ + static void settled(Object widget) throws Exception { + var holder = (WidgetTooltipHolder) field(net.minecraft.client.gui.components.AbstractWidget.class, "tooltip").get(widget); + put(holder, WidgetTooltipHolder.class, "wasDisplayed", true); + put(holder, WidgetTooltipHolder.class, "displayStartTime", Util.getMillis() - 1000L); + } + + static JsonArray run(JsonObject c, Minecraft mc, RecipeManager recipes) throws Exception { + var g = alloc(Capture.class); + g.draws = new JsonArray(); + g.stack = new Matrix3x2fStack(16); + String type = c.get("type").getAsString(); + boolean furnace = !type.equals("crafting"); + int width = c.get("width").getAsInt(), height = c.get("height").getAsInt(); + int xOffset = c.get("narrow").getAsBoolean() ? 0 : 86; + int xo = (width - 147) / 2 - xOffset, yo = (height - 166) / 2; + int mx = c.getAsJsonArray("mouse").get(0).getAsInt(), my = c.getAsJsonArray("mouse").get(1).getAsInt(); + int index = c.get("index").getAsInt(); + SlotSelectTime time = () -> index; + boolean filtering = c.get("filtering").getAsBoolean(); + // RecipeBookComponent.extractRenderState. + g.blit(RenderPipelines.GUI_TEXTURED, (Identifier) field(RecipeBookComponent.class, "RECIPE_BOOK_LOCATION").get(null), xo, yo, 1.0F, 1.0F, 147, 166, 256, 256); + var s = c.getAsJsonObject("search"); + var search = new EditBox(mc.font, xo + 25, yo + 13, 81, 9 + 5, Component.translatable("itemGroup.search")); + search.setMaxLength(50); + search.setVisible(true); + search.setTextColor(-1); + search.setValue(s.get("value").getAsString()); + search.setHint((Component) field(RecipeBookComponent.class, "SEARCH_HINT").get(null)); + put(search, net.minecraft.client.gui.components.AbstractWidget.class, "focused", s.get("focused").getAsBoolean()); + put(search, EditBox.class, "displayPos", s.get("display").getAsInt()); + put(search, EditBox.class, "cursorPos", s.get("cursor").getAsInt()); + put(search, EditBox.class, "highlightPos", s.get("highlight").getAsInt()); + put(search, EditBox.class, "focusedTime", Util.getMillis() - s.get("blink").getAsLong()); + search.extractRenderState(g, mx, my, 1.0F); + Class tabOwner = switch (type) { + case "crafting" -> CraftingRecipeBookComponent.class; + case "furnace" -> net.minecraft.client.gui.screens.inventory.FurnaceScreen.class; + case "blast_furnace" -> net.minecraft.client.gui.screens.inventory.BlastFurnaceScreen.class; + default -> net.minecraft.client.gui.screens.inventory.SmokerScreen.class; + }; + @SuppressWarnings("unchecked") + var infos = (List) field(tabOwner, "TABS").get(null); + // updateTabs: the visible tabs in order. + int n = 0; + for (var t : c.getAsJsonArray("tabs")) { + var tab = t.getAsJsonObject(); + var button = new RecipeBookTabButton(0, 0, infos.get(tab.get("tab").getAsInt()), b -> {}); + button.setPosition((width - 147) / 2 - xOffset - 30, (height - 166) / 2 + 3 + 27 * n++); + if (tab.get("selected").getAsBoolean()) button.select(); + put(button, RecipeBookTabButton.class, "animationTime", tab.get("anim").getAsFloat()); + button.extractRenderState(g, mx, my, 1.0F); + } + RecipeBookComponent component = furnace ? alloc(FurnaceRecipeBookComponent.class) : alloc(CraftingRecipeBookComponent.class); + Method name = RecipeBookComponent.class.getDeclaredMethod("getRecipeFilterName"); + name.setAccessible(true); + Method sprites = RecipeBookComponent.class.getDeclaredMethod("getFilterButtonTextures"); + sprites.setAccessible(true); + if (furnace) put(component, FurnaceRecipeBookComponent.class, "recipeFilterName", Component.translatable(switch (type) { + case "furnace" -> "gui.recipebook.toggleRecipes.smeltable"; + case "blast_furnace" -> "gui.recipebook.toggleRecipes.blastable"; + default -> "gui.recipebook.toggleRecipes.smokable"; + })); + Component filterName = (Component) name.invoke(component); + WidgetSprites filterSprites = (WidgetSprites) sprites.invoke(component); + Component all = (Component) field(RecipeBookComponent.class, "ALL_RECIPES_TOOLTIP").get(null); + var filter = CycleButton.booleanBuilder(filterName, all, filtering) + .withTooltip(f -> f ? Tooltip.create(filterName) : Tooltip.create(all)) + .withSprite((b, f) -> filterSprites.get(f, b.isHoveredOrFocused())) + .displayState(CycleButton.DisplayState.HIDE) + .create(xo + 110, yo + 12, 26, 16, CommonComponents.EMPTY, (b, v) -> {}); + settled(filter); + filter.extractRenderState(g, mx, my, 1.0F); + // RecipeBookPage.init and updateCollections. + var page = new RecipeBookPage(null, time, furnace); + page.init(mc, xo, yo); + List collections = new ArrayList<>(); + for (var b : c.getAsJsonArray("collections")) collections.add(collection(recipes, b.getAsJsonObject())); + put(page, RecipeBookPage.class, "currentPage", c.get("page").getAsInt()); + page.updateCollections(collections, false, filtering); + @SuppressWarnings("unchecked") + var buttons = (List) field(RecipeBookPage.class, "buttons").get(page); + var anims = c.getAsJsonArray("buttonAnims"); + for (int i = 0; i < anims.size(); i++) put(buttons.get(i), RecipeButton.class, "animationTime", anims.get(i).getAsFloat()); + for (String arrow : new String[] {"forwardButton", "backButton"}) settled(field(RecipeBookPage.class, arrow).get(page)); + var overlay = (OverlayRecipeComponent) field(RecipeBookPage.class, "overlay").get(page); + if (c.has("overlay")) { + // RecipeBookPage.mouseClicked: right click on a button. + var button = buttons.get(c.get("overlay").getAsInt()); + ContextMap context = SlotDisplayContext.fromLevel(mc.level); + overlay.init(button.getCollection(), context, filtering, button.getX(), button.getY(), xo + 147 / 2, yo + 13 + 166 / 2, button.getWidth()); + } + page.extractRenderState(g, xo, yo, mx, my, 1.0F); + // RecipeBookPage.extractTooltip. + var hovered = (RecipeButton) field(RecipeBookPage.class, "hoveredButton").get(page); + if (hovered != null && !overlay.isVisible()) { + var o = g.add("item_tooltip"); + o.addProperty("id", id(hovered.getDisplayStack())); + o.addProperty("more", !hovered.isOnlyOption()); + } + // GhostSlots.extractRenderState. + if (c.has("ghost")) { + var ghost = new GhostSlots(time); + ContextMap context = SlotDisplayContext.fromLevel(mc.level); + var container = new SimpleContainer(16); + int i = 0; + for (var e : c.getAsJsonArray("ghost")) { + var gs = e.getAsJsonObject(); + var slot = new Slot(container, i++, gs.get("x").getAsInt(), gs.get("y").getAsInt()); + List items = new ArrayList<>(); + for (var it : gs.getAsJsonArray("items")) items.add(new SlotDisplay.ItemStackSlotDisplay(new net.minecraft.world.item.ItemStackTemplate(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue(Identifier.parse(it.getAsString()))))); + SlotDisplay display = new SlotDisplay.Composite(items); + Method set = GhostSlots.class.getDeclaredMethod(gs.get("result").getAsBoolean() ? "setResult" : "setInput", Slot.class, ContextMap.class, SlotDisplay.class); + set.setAccessible(true); + set.invoke(ghost, slot, context, display); + } + g.pose().pushMatrix(); + g.pose().translate(c.get("left").getAsInt(), c.get("top").getAsInt()); + ghost.extractRenderState(g, mc, c.get("big").getAsBoolean()); + g.pose().popMatrix(); + } + return g.draws; + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + RecipeManager recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + // A stand-in client: its font, a level for the slot display context, a player's book. + Minecraft mc = alloc(Minecraft.class); + put(mc, Minecraft.class, "font", ParityFont.create(ParityFont.resources())); + var level = alloc(ClientLevel.class); + put(level, Level.class, "registryAccess", ParityData.access); + put(mc, Minecraft.class, "level", level); + var player = alloc(LocalPlayer.class); + put(player, LocalPlayer.class, "recipeBook", new ClientRecipeBook()); + put(mc, Minecraft.class, "player", player); + put(mc, Minecraft.class, "lastInputType", net.minecraft.client.InputType.MOUSE); + put(mc, Minecraft.class, "textInputManager", new NoTextInput()); + field(Minecraft.class, "instance").set(null, mc); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + var c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + try { + result.add("draws", run(c, mc, recipes)); + } catch (Throwable error) { + var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error; + var sw = new java.io.StringWriter(); + cause.printStackTrace(new java.io.PrintWriter(sw)); + result.addProperty("error", sw.toString().lines().limit(8).reduce("", (a, b) -> a + b + " | ")); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_recipe_book_render_parity.py b/tools/test_recipe_book_render_parity.py new file mode 100644 index 000000000..78d911d72 --- /dev/null +++ b/tools/test_recipe_book_render_parity.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Compare the recipe book's drawing with the vanilla client's. + +Each case opens a book type (the inventory's or a crafting table's crafting +book, the furnace, blast furnace or smoker) at a GUI size, with its visible +tabs (one selected, some in their new-recipe squeeze), the search box (text, +cursor, selection, focus and cursor blink), the craftable filter, a page of +recipe collections (real recipes, some craftable, some buttons squeezing), +the alternatives overlay of one button, ghost slots, the cycling index and +the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's +widgets for that state as RecipeBookComponent.initVisuals and +RecipeBookPage.init do and records every GuiGraphicsExtractor call of their +extractRenderState, the tooltips and GhostSlots.extractRenderState, with its +pose; examples/recipe_book_render_fixture lays out the same state with +horizon_client::recipe_book_screen, which the game paints. The call lists +must agree. +""" +import argparse +import json +import os +import random +import subprocess +import sys +try: + from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base +except ImportError: + import interaction_lab as lib + import test_model_baking_parity as baking + import test_rust_parity as base + +TABS = {'crafting': 5, 'furnace': 4, 'blast_furnace': 3, 'smoker': 2} +TYPES = {'crafting': ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless'), 'furnace': ('minecraft:smelting',), + 'blast_furnace': ('minecraft:blasting',), 'smoker': ('minecraft:smoking',)} +WORDS = ['', '', 'a', 'stone', 'iron ingot', 'oak', 'zzz', 'red', 'a very long search text that overflows'] + + +def recipes_by_type(): + out = {k: [] for k in TYPES} + for path in sorted((lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')): + kind = json.loads(path.read_text()).get('type') + for k, types in TYPES.items(): + if kind in types: + out[k].append('minecraft:' + path.stem) + return out + + +def cases(count, seed): + rng = random.Random(seed) + by_type = recipes_by_type() + items = sorted(i for i in json.loads((lib.RESOURCES / 'items.json').read_text()) if i != 'minecraft:air') + out = [] + for n in range(count): + kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5] + width, height = rng.choice([(427, 240), (480, 270), (640, 360), (320, 240), (378, 260), (854, 480)]) + narrow = width < 379 + xo = (width - 147) // 2 - (0 if narrow else 86) + yo = (height - 166) // 2 + tabs = [0] + sorted(rng.sample(range(1, TABS[kind]), rng.randint(0, TABS[kind] - 1))) + selected = rng.choice(tabs) + tab_list = [{'tab': t, 'selected': t == selected, 'anim': rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)])} + for t in tabs] + total = rng.choice([0, 1, 5, 19, 20, 21, 47, 80]) + pages = (total + 19) // 20 + page = rng.randrange(pages) if pages else 0 + filtering = rng.random() < 0.4 + collections = [] + for _ in range(total): + group = rng.sample(by_type[kind], rng.choice([1, 1, 1, 2, 3, 6])) + recipes = [[r, rng.random() < 0.4] for r in group] + if filtering and not any(c for _, c in recipes): + recipes[0][1] = True + collections.append({'recipes': recipes}) + on_page = max(0, min(20, total - 20 * page)) + value = rng.choice(WORDS) + cursor = rng.randint(0, len(value)) + highlight = rng.choice([cursor, rng.randint(0, len(value))]) + search = {'value': value, 'cursor': cursor, 'highlight': highlight, + 'display': rng.choice([0, 0, min(cursor, rng.randint(0, len(value)))]), 'focused': rng.random() < 0.5, + 'blink': rng.choice([0, 150, 450, 700])} + targets = [(xo + 11 + 25 * (i % 5) + rng.randint(0, 24), yo + 31 + 25 * (i // 5) + rng.randint(0, 24)) for i in range(on_page)] + targets += [(xo + 115, yo + 20), (xo + 95, yo + 140), (xo + 40, yo + 140), (xo + 30, yo + 18), (xo - 20, yo + 40), + (rng.randint(0, width), rng.randint(0, height))] + case = {'type': kind, 'grid': 2 if rng.random() < 0.5 else 3, 'width': width, 'height': height, 'narrow': narrow, + 'mouse': list(rng.choice(targets)), 'index': rng.choice([0, 0, 1, 2, 5, 13, 60]), 'filtering': filtering, + 'tabs': tab_list, 'search': search, 'collections': collections, 'page': page, + 'buttonAnims': [rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)]) for _ in range(on_page)]} + multi = [i for i in range(on_page) if sum(1 for _, c in collections[20 * page + i]['recipes'] if c or not filtering) > 1] + if multi and rng.random() < 0.4: + case['overlay'] = rng.choice(multi) + if rng.random() < 0.4: + left, top = (width - 176) // 2, (height - 166) // 2 + slots = [(124, 35, True)] + [(30 + 18 * (i % 3), 17 + 18 * (i // 3), False) for i in range(9)] + if kind != 'crafting': + slots = [(116, 35, True), (56, 17, False)] + case.update({'left': left, 'top': top, 'big': rng.random() < 0.7, + 'ghost': [{'x': x, 'y': y, 'result': r, 'items': rng.sample(items, rng.choice([1, 1, 2, 4]))} + for x, y, r in rng.sample(slots, rng.randint(1, len(slots)))]}) + out.append(case) + return out + + +def same(a, b): + """Calls agree: every field exactly, poses within float printing.""" + if a is None or b is None or set(a) != set(b): + return False + return all(all(abs(x - y) <= 1e-3 for x, y in zip(a[k], b[k])) if k == 'm' else a[k] == b[k] for k in a) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=29) + parser.add_argument('--cases', type=int, default=600) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + work = lib.work_dir('recipe-book-render-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps, + '-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'ParityFont', 'VanillaRecipeBookScreenOracle'))], + capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + chosen = cases(args.cases, args.seed) + inputs = work / 'cases.jsonl' + inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaRecipeBookScreenOracle', + str(inputs), str(work / 'vanilla.jsonl')], capture_output=True, text=True) + if run.returncode: + print(run.stderr[-4000:]) + sys.exit('oracle failed') + lib.cargo_example('horizon-client', 'recipe_book_render_fixture', lib.RESOURCES, inputs, work / 'rust.jsonl') + vanilla = [json.loads(l) for l in (work / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen)) + errors, failures, passed = {}, {}, 0 + for case, v, r in zip(chosen, vanilla, rust): + if 'error' in v: + errors.setdefault(case['type'], v['error']) + continue + a, b = v['draws'], r['draws'] + bad = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or not same(a[i], b[i])), None) + if bad is None: + passed += 1 + else: + failures.setdefault(case['type'], []).append((case, bad, a[bad] if bad < len(a) else None, b[bad] if bad < len(b) else None)) + for kind, error in sorted(errors.items()): + print(f'ORACLE ERROR {kind}: {error[:1500]}') + for kind, items in sorted(failures.items()): + print(f'MISMATCH {kind}: {len(items)} cases') + for case, i, x, y in items[:args.limit]: + brief = {k: v for k, v in case.items() if k not in ('collections',)} + print(f' {json.dumps(brief)[:700]}') + print(f' call {i}: vanilla {json.dumps(x)}') + print(f' call {i}: horizon {json.dumps(y)}') + print(f'{passed}/{len(chosen)} cases match') + if errors or failures: + sys.exit(1) + print('recipe book render parity ok') + + +if __name__ == '__main__': + main() From 5e48972bff338eafe9cc5a0339c882573a8aa181 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 02:26:40 +0200 Subject: [PATCH 14/14] README and docs: the recipe book's drawing, the loom's banner preview and End gateway beams match vanilla Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++---- docs/rust-parity.md | 19 +++++++++++++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 32ecb88c4..43f1c21b7 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ CI Minecraft Java 26.3 Rust - Vanilla parity 88% + Vanilla parity 89% Linux, macOS and Windows MIT license

@@ -22,7 +22,7 @@ A Rust rewrite of Minecraft: Java Edition 26.3 that aims for one-to-one vanilla parity, checked against the game itself with differential tests. -**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 88% (see [Project status](#project-status)). +**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 89% (see [Project status](#project-status)). > Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. Horizon contains no Minecraft code, assets or data: you need your own legally obtained copy of Minecraft: Java Edition 26.3. @@ -113,7 +113,7 @@ The client starts on the title screen. Command-line options (`--world`, `--seed` Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, spawned mob gear enchantments, the resource pack screen, a dedicated server mode, and worlds older than 1.17. -### Java parity: 88% +### Java parity: 89% Each subsystem scores 0 (absent), 0.25 (started, not playable), 0.5 (playable, major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete @@ -130,7 +130,7 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and | Network protocol and multiplayer | 0.75 | Joins vanilla servers and opens worlds to LAN; server.properties, eula.txt and the user lists match vanilla, but there is no dedicated server mode and LAN hosting is not tested against a vanilla client | | Chunk storage and palettes | 1 | None: client and saves share paletted containers, identical to vanilla over 266 scenarios | | Section meshing | 1 | None: 112 scenes and over a million quads identical to vanilla | -| Rendering | 0.75 | Entity models, block entity renderers (400 cases, End portals and gateways included) and their animations (256 cases), the HUD overlays (2,200 states), the player list, subtitles and the world border match vanilla; the recipe book's drawing and the banner preview are not compared, and End gateways show no beam in game | +| Rendering | 1 | None: entity models, block entity renderers (407 cases, End portals, gateways and the loom's banner preview included) and their animations (296 cases, End gateway beams included), the HUD overlays (2,200 states), the recipe book (600 states), the player list, subtitles and the world border match vanilla | | 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 | diff --git a/docs/rust-parity.md b/docs/rust-parity.md index 614e5a96d..977076575 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1418,11 +1418,22 @@ vanilla's own classes, and the game uses that code: `CrafterScreen`'s decorations as draw calls the game paints; `tools/test_screen_layout_parity.py` runs vanilla's screens on stand-in menus and compares 1,600 call lists. +- **The book's drawing.** `recipe_book_screen` lays out + `RecipeBookComponent`'s background, search `EditBox`, tab buttons, filter + `CycleButton`, the page of `RecipeButton`s with its number and arrows, the + `OverlayRecipeComponent`, the tooltips and `GhostSlots` as GUI calls with + their poses (squeeze animations, the overlay's 3/8 scale items); the game + paints them. `tools/test_recipe_book_render_parity.py` builds vanilla's + widgets for 600 states (`VanillaRecipeBookScreenOracle`) and compares every + call. Ingredients cycle in their `HolderSet` order (tags in `TagLoader` order). +- **The loom's banner preview.** `item_render::gui::draw_banner_result` draws + `GuiBannerResultRenderer`'s flag model and layers in the 20x40 picture in + picture, lit with `ITEMS_FLAT`; the block entity render harness compares its + quads under the picture-in-picture pose. -Not compared yet: the recipe book's own drawing (tabs, buttons, the overlay -and ghost slots) and its text search, the banner preview's 3D flag (drawn as -the flat front face), furnaces awarding their recipes and experience when -their output is taken, and the limited crafting game rule. +Not compared yet: the recipe book's text search, furnaces awarding their +recipes and experience when their output is taken, and the limited crafting +game rule. ## Player list and world border rendering