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 1/4] 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 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 2/4] 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 3/4] 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 4/4] 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) }