From 79e04e22d6b5f52270740bab857335f37838d0f1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:55:35 +0200 Subject: [PATCH] Monster spawners spawn, spin their mob and take spawn eggs Spawners were never ticked: Horizon kept their block entity as loaded NBT, and a freshly generated dungeon or mineshaft spawner lost even that, so no mob ever came out, nothing turned inside and a spawn egg used on one spawned a mob next to it instead of setting the spawner's. The spawner is now a modelled block entity (mobs::spawner): BaseSpawner's load and save with SpawnData's codec (normalised ids, custom spawn rules, weighted potentials, the next data shared with the one potential when the potentials are missing), serverTick (the player range, spawner_blocks_work, the delay, getOrCreateNextSpawnData, Pos, the spawn box against blocks and solid shulkers, custom light rules and peaceful, SpawnPlacements, the nearby cap, the yaw, checkSpawnRules and checkSpawnObstruction, finalizeSpawn for an id alone, the 2004 burst, entity_place and the spawn poof) and delay with its block event, in the level random's order. The client copy keeps its own delay for the spin and puffs smoke and flames; SpawnerRenderer draws the next mob small and turning. SpawnEggItem.useOn on a spawner sets its mob (setEntityId), tells the player when spawner_blocks_work is off and fails in peaceful for monsters. Breaking one pops 15 + nextInt(15) + nextInt(15) experience whatever the tool. LAN guests get the update tag, the block event and the entity event. tools/test_spawner_parity.py ticks vanilla's SpawnerBlockEntity on the natural spawn oracle's level against mobs::spawner on the same worlds (6,000 cases); tools/test_use_item_on_parity.py now covers spawn eggs on spawners. Co-Authored-By: Claude Opus 5.5 --- .../examples/natural_spawn_fixture.rs | 161 +++- crates/horizon-client/src/containers.rs | 12 +- crates/horizon-client/src/game.rs | 30 +- crates/horizon-client/src/game/creatures.rs | 18 + .../src/game/dispense_fixture.rs | 36 + crates/horizon-client/src/game/lan.rs | 19 + .../src/game/natural_spawning.rs | 54 +- crates/horizon-client/src/game/persist.rs | 2 +- crates/horizon-client/src/game/spawner.rs | 414 ++++++++++ crates/horizon-client/src/lan/chunks.rs | 35 +- crates/horizon-client/src/lan/containers.rs | 22 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/render.rs | 38 +- .../src/mobs/spawn_selection.rs | 4 +- crates/horizon-client/src/mobs/spawner.rs | 740 ++++++++++++++++++ crates/horizon-client/src/save.rs | 2 + crates/horizon-client/src/structure_blocks.rs | 4 + .../parity/VanillaBlockUpdateOracle.java | 3 + .../parity/VanillaDispenserOracle.java | 30 + .../parity/VanillaNaturalSpawnOracle.java | 75 +- tools/test_spawner_parity.py | 281 +++++++ tools/test_use_item_on_parity.py | 25 +- 22 files changed, 1939 insertions(+), 67 deletions(-) create mode 100644 crates/horizon-client/src/game/spawner.rs create mode 100644 crates/horizon-client/src/mobs/spawner.rs create mode 100644 tools/test_spawner_parity.py diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index b2f0a8900..af15b9fde 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -9,6 +9,10 @@ //! 1.0), foxes and axolotls from the third, sulfur cubes have size 2, salmon //! are small, slimes and magma cubes keep size 1, tropical fish school. //! +//! Spawner cases (`mode=spawner`, tools/test_spawner_parity.py) tick a +//! `mobs::spawner::Spawner` loaded from the case's SNBT on the same world and +//! print its events tick by tick. +//! //! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT use horizon_client::{ assets::Assets, @@ -25,6 +29,7 @@ use horizon_client::{ SpawnPlayer, SpawnRequest, SpawnState, Spawned, StructureAt, StructureSpawns, spawn_box, }, + spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn}, species::{self, Baby}, }, }; @@ -73,6 +78,8 @@ struct Shared<'a> { structures: &'a StructureSpawns, collision: &'a BlockCollisionRegistry<'a>, air: BlockStateId, + /// Every entity type id (`entity-types.json`). + entity_types: &'a HashSet, } struct World<'a> { s: &'a Shared<'a>, @@ -95,8 +102,10 @@ struct World<'a> { respawn: Option<[i32; 3]>, unloaded: HashSet<(i32, i32)>, spawn_mobs: bool, - /// Boxes of living entities (case entities, then spawned mobs). - entities: RefCell>, + /// The `spawner_blocks_work` game rule. + spawners_work: bool, + /// Types and boxes of living entities (case entities, then spawned mobs). + entities: RefCell>, } impl World<'_> { fn biome_at(&self, x: i32, y: i32, z: i32) -> &str { @@ -280,10 +289,21 @@ impl NaturalLevel for World<'_> { block: &lookup, binding: self.s.collision, }; + // getEntityCollisions(null, box): living shulkers are solid. + let grown = bounds.inflate(horizon_core::geometry::Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut world, bounds) + && !self + .entities + .borrow() + .iter() + .any(|(id, b)| id == "minecraft:shulker" && b.intersects(grown)) } fn unobstructed(&self, bounds: Aabb) -> bool { - !self.entities.borrow().iter().any(|b| b.intersects(bounds)) + !self + .entities + .borrow() + .iter() + .any(|(_, b)| b.intersects(bounds)) } fn spawn_mobs(&self) -> bool { self.spawn_mobs @@ -299,6 +319,28 @@ impl NaturalLevel for World<'_> { } } +impl SpawnerLevel for World<'_> { + fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool { + self.players.iter().any(|(p, mode)| { + let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2); + mode != "spectator" && (range < 0.0 || d < range * range) + }) + } + fn spawner_blocks_work(&self) -> bool { + self.spawners_work + } + fn entity_exists(&self, id: &str) -> bool { + self.s.types.types.contains_key(id) || self.s.entity_types.contains(id) + } + fn count_entities(&self, id: &str, bounds: Aabb) -> usize { + self.entities + .borrow() + .iter() + .filter(|(k, b)| k == id && b.intersects(bounds)) + .count() + } +} + /// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random. fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb { let t = &l.s.types.types[r.entity]; @@ -369,6 +411,17 @@ fn main() -> horizon_client::Result<()> { let biomes = Biomes::load(root)?; let structures = StructureSpawns::load(root); let collision = collisions::load(root, registry)?; + let entity_types: HashSet = fs::read(root.join("entity-types.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v.as_object().map(|o| { + o.keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect() + }) + }) + .unwrap_or_default(); let shared = Shared { facts: &facts, data: &data, @@ -378,6 +431,7 @@ fn main() -> horizon_client::Result<()> { structures: &structures, collision: &collision, air: facts.air, + entity_types: &entity_types, }; let mut adaptation: HashMap = HashMap::new(); let mut out = String::new(); @@ -538,12 +592,18 @@ fn main() -> horizon_client::Result<()> { respawn, unloaded, spawn_mobs: get("rules", "1") != "0", + spawners_work: get("spawners", "1") != "0", entities: RefCell::new( case_entities .iter() - .filter_map(|(t, p, _)| { - let t = types.types.get(t)?; - Some(spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32)) + .filter_map(|(id, p, _)| { + let t = types.types.get(id)?; + // Entity.setPos (a shulker sits at its block's centre). + let p = horizon_client::mobs::spawner::entity_position(t.species, *p); + Some(( + id.clone(), + spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32), + )) }) .collect(), ), @@ -560,14 +620,16 @@ fn main() -> horizon_client::Result<()> { let mut log: Vec = Vec::new(); let mut spawn = |l: &World, r: &SpawnRequest| -> Option { let bounds = neutral_box(l, r); - l.entities.borrow_mut().push(bounds); + l.entities.borrow_mut().push((r.entity.to_owned(), bounds)); Some(Spawned { bounds, school: true, }) }; let mode = get("mode", "chunk"); - if mode == "gen" { + if mode == "spawner" { + spawner_case(&world, &get, &mut random, &mut log)?; + } else if mode == "gen" { let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?); // The level random of the spawn predicates: no creature's predicate // draws from it (the oracle's answers fixed values). @@ -686,3 +748,86 @@ fn main() -> horizon_client::Result<()> { fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; Ok(()) } + +/// `SpawnerBlockEntity.serverTick` `ticks` times at `spos` for the spawner in +/// `snbt` (base64 SNBT), as the oracle logs it. +fn spawner_case( + world: &World, + get: &dyn Fn(&str, &'static str) -> String, + random: &mut LegacyRandom, + log: &mut Vec, +) -> horizon_client::Result<()> { + let v: Vec = get("spos", "0,0,0") + .split(',') + .map(|n| n.parse().unwrap_or(0)) + .collect(); + let pos = [v[0], v[1], v[2]]; + let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?; + let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0; + let mut spawner = Spawner::load(&tag); + let ticks: i32 = get("ticks", "1").parse()?; + for tick in 0..ticks { + let mut events = Vec::new(); + let mut spawned = std::collections::VecDeque::new(); + let mut spawn = |l: &World, r: &SpawnerSpawn| -> Option { + let t = l.s.types.types.get(r.id)?; + let [x, y, z] = r.position; + let bounds = spawn_box(x, y, z, t.width as f32, t.height as f32); + l.entities.borrow_mut().push((r.id.to_owned(), bounds)); + spawned.push_back(format!( + "{tick} spawn {} {} {} {} {}", + r.id, + bits(x), + bits(y), + bits(z), + // Shulker.finalizeSpawn faces it south. + yaw_text( + r.id, + if r.finalize && r.id == "minecraft:shulker" { + 0.0 + } else { + r.yaw + } + ) + )); + Some(SpawnerAdded { + id: spawned.len() as u32, + bounds, + mob: true, + }) + }; + spawner.server_tick(world, random, pos, &mut spawn, &mut events); + for e in events { + match e { + SpawnerEvent::BlockUpdated => log.push(format!("{tick} update")), + SpawnerEvent::BlockEvent(id) => log.push(format!("{tick} bevent {id} 0")), + // Each spawn's level event follows its tryAddFreshEntityWithPassengers. + SpawnerEvent::LevelEvent(id) => { + log.extend(spawned.pop_front()); + log.push(format!("{tick} levent {id} 0")); + } + SpawnerEvent::EntityPlace(_, p) => log.push(format!( + "{tick} gevent minecraft:entity_place {} {} {}", + p[0], p[1], p[2] + )), + SpawnerEvent::SpawnAnim(_) => log.push(format!("{tick} eevent 20")), + } + } + } + let next = spawner + .next_data() + .and_then(|d| d.id()) + .unwrap_or_else(|| "-".into()); + let pots: Vec = spawner + .potentials + .iter() + .map(|(d, w)| format!("{}*{w}", d.id().unwrap_or_else(|| "-".into()))) + .collect(); + log.push(format!( + "end delay={} next={next} pots={}", + spawner.spawn_delay as i16, + pots.join(",") + )); + log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); + Ok(()) +} diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 9688af5eb..70c71d7fc 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -66,6 +66,8 @@ pub enum BlockEntity { Banner(Banner), /// `CrafterBlockEntity`. Crafter(Crafter), + /// `SpawnerBlockEntity` (`crate::mobs::spawner`). + Spawner(Box), } /// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag /// and the ticks left in the crafting animation. @@ -180,6 +182,9 @@ impl BlockEntity { if name == "minecraft:creaking_heart" { return Some(Self::CreakingHeart(Box::default())); } + if name == "minecraft:spawner" { + return Some(Self::Spawner(Box::default())); + } if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } @@ -255,6 +260,7 @@ impl BlockEntity { Self::Banner(_) => "minecraft:banner", Self::Crafter(_) => "minecraft:crafter", Self::CreakingHeart(_) => "minecraft:creaking_heart", + Self::Spawner(_) => "minecraft:mob_spawner", } } pub fn contents(&self) -> Vec { @@ -264,7 +270,7 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(), + Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -283,7 +289,7 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &[], Self::Crafter(c) => &c.items, - Self::CreakingHeart(_) => &[], + Self::CreakingHeart(_) | Self::Spawner(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -298,7 +304,7 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &mut [], Self::Crafter(c) => &mut c.items, - Self::CreakingHeart(_) => &mut [], + Self::CreakingHeart(_) | Self::Spawner(_) => &mut [], } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 823f76cd6..15cecfec7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -95,6 +95,7 @@ mod sculk_fixture; mod shield; mod sign_edit; mod sniffers; +mod spawner; mod spill; mod station_control; mod stations; @@ -833,6 +834,8 @@ struct Game<'a> { tridents: Vec, rockets: Vec, creaking: creaking::CreakingState, + /// Monster spawners' display mobs (`game/spawner.rs`). + spawners: spawner::SpawnerState, trident_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, @@ -879,6 +882,10 @@ struct Game<'a> { forced_hit: Option, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, + /// Block events (position, b0, b1, state) and entity events (id, event, + /// position) for the guests. + lan_block_events: Vec<([i32; 3], i32, i32, u16)>, + lan_entity_events: Vec<(i32, i8, [f64; 3])>, lan_acting: Option, /// Command feedback to forward to a guest. chat_capture: Option>, @@ -1608,6 +1615,9 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + LevelEvent::LevelEvent { id: 2004, pos, .. } => { + self.spawner_burst([pos.x, pos.y, pos.z]) + } LevelEvent::LevelEvent { id: id @ 3002..=3005, pos, @@ -2045,7 +2055,8 @@ impl Game<'_> { self.pop_resource(pos, d); } } - let xp = if silk { + // SpawnerBlock.spawnAfterBreak pops its experience whatever the tool. + let xp = if silk && &*facts.name != "minecraft:spawner" { 0 } else { self.block_experience(&facts.name) @@ -3470,7 +3481,8 @@ impl Game<'_> { | BlockEntity::Lectern(_) | BlockEntity::Sculk(_) | BlockEntity::Banner(_) - | BlockEntity::CreakingHeart(_), + | BlockEntity::CreakingHeart(_) + | BlockEntity::Spawner(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3687,7 +3699,8 @@ impl Game<'_> { | BlockEntity::Lectern(_) | BlockEntity::Sculk(_) | BlockEntity::Banner(_) - | BlockEntity::CreakingHeart(_), + | BlockEntity::CreakingHeart(_) + | BlockEntity::Spawner(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -5202,6 +5215,7 @@ impl Game<'_> { self.tick_jukeboxes(); self.tick_beacons(); self.tick_creaking_hearts()?; + self.tick_spawners()?; let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Furnace(f) = entity @@ -6552,7 +6566,12 @@ impl Game<'_> { "sculk_catalyst" | "sculk_sensor" | "calibrated_sculk_sensor" | "sculk_shrieker" => { (5, 5) } - "spawner" => (15, 43), + // SpawnerBlock.spawnAfterBreak: 15 + nextInt(15) + nextInt(15). + "spawner" => { + let r = &mut self.world.random; + let a = r.next_int_bound(15).unwrap_or(0); + return (15 + a + r.next_int_bound(15).unwrap_or(0)) as u32; + } _ => (0, 0), }; if max == 0 { @@ -8953,6 +8972,7 @@ pub fn run() -> Result<()> { tridents: Vec::new(), rockets: Vec::new(), creaking: Default::default(), + spawners: Default::default(), trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), tnts: Vec::new(), hoppers: HashMap::new(), @@ -8981,6 +9001,8 @@ pub fn run() -> Result<()> { saved_for_exit: false, forced_hit: None, lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), lan_acting: None, chat_capture: None, cmds: Default::default(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index b6029a202..bbe07cae0 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2276,6 +2276,23 @@ impl Game<'_> { return Ok(false); }; let kind = stack.item.trim_end_matches("_spawn_egg").to_owned(); + // EntityType.canSpawn: no monsters in peaceful (FAIL ends the click). + let id = format!("minecraft:{}", kind.trim_start_matches("minecraft:")); + if self.ui.difficulty == 0 + && let Some(t) = self.res.mob_types.get(&id) + && !horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species) + { + return Ok(true); + } + // SpawnEggItem.useOn on a spawner sets its mob. + if let Some(done) = self.use_spawn_egg_on_spawner(hit.pos, &id) { + if done { + self.swing_arm(); + self.stats.add("used", &stack.item, 1); + self.consume_held(); + } + return Ok(true); + } let p = [ hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], @@ -2392,6 +2409,7 @@ impl Game<'_> { } } self.elder_apparition_geometry(alpha, out); + self.spawner_geometry(camera, alpha, out); // Projectiles: arrows as crossed quads, the rest as item billboards. let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); let forward = glam::Vec3::new( diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index e3fd0e896..ab6a79961 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -340,6 +340,34 @@ impl Game<'_> { disabled.join(",") )); } + // A spawner's next spawn data (its id and number of keys), potentials and delay. + let mut spawners: Vec<_> = self + .world + .block_entities + .iter() + .filter_map(|(p, e)| match e { + BlockEntity::Spawner(s) => Some((*p, s)), + _ => None, + }) + .collect(); + spawners.sort_unstable_by_key(|s| s.0); + for (p, s) in spawners { + let next = s.next_data().map_or("-".to_owned(), |d| { + format!( + "{}/{}", + d.id().unwrap_or_else(|| "?".into()), + d.entity.len() + ) + }); + out.push(format!( + "spawner {},{},{} next={next} potentials={} delay={}", + p.0, + p.1, + p.2, + s.potentials.len(), + s.spawn_delay as i16 + )); + } self.fixture_entities(&old_mobs, &old_stands, &mut out); for (i, t) in targets.iter().enumerate() { out.push(self.fixture_describe(i, t)); @@ -449,11 +477,19 @@ impl Game<'_> { f64::from(pos.z) + 0.5, ], }); + self.chat_capture = Some(Vec::new()); let used = self.use_item_as_player(); self.forced_hit = None; + let messages = self.chat_capture.take().unwrap_or_default(); used?; self.process_level_events()?; let mut out = Vec::new(); + for m in messages { + let key = m.component()["translate"] + .as_str() + .map_or_else(|| m.plain(), str::to_owned); + out.push(format!("msg {key}")); + } if let Some(s) = &stack { let used = self.stats.get("used", &s.item) - used_before; if used != 0 { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index a29ca085c..6fd7e4dd8 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -707,6 +707,19 @@ impl Game<'_> { } } + /// `Level.blockEvent` for the guests (`ClientboundBlockEventPacket`). + pub(super) fn lan_block_event(&mut self, pos: [i32; 3], b0: i32, b1: i32) { + if self.audio.capture.is_some() { + let state = self.world.block(pos[0], pos[1], pos[2]).0 as u16; + self.lan_block_events.push((pos, b0, b1, state)); + } + } + /// `Level.broadcastEntityEvent` for the guests. + pub(super) fn lan_entity_event(&mut self, id: i32, event: i8, at: [f64; 3]) { + if self.audio.capture.is_some() { + self.lan_entity_events.push((id, event, at)); + } + } /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { @@ -716,6 +729,12 @@ impl Game<'_> { } host.hub.level_event(kind, pos, data, acting); } + for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) { + host.hub.block_event(pos, b0, b1, state); + } + for (id, event, at) in std::mem::take(&mut self.lan_entity_events) { + host.hub.entity_event(id, event, at); + } self.lan_broadcast_effects(host); if host.hub.guests.is_empty() { host.mob_state.clear(); diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index fc37143b7..83d7ddfb3 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -28,7 +28,9 @@ pub(super) struct GameLevel<'g, 'a> { pub(super) game: &'g Game<'a>, w: MobWorld<'g>, /// Boxes of the mobs this pass created, not yet in the game's list. - pending: std::cell::RefCell>, + pub(super) pending: std::cell::RefCell>, + /// The types and boxes of what a spawner created this tick. + pub(super) pending_ids: std::cell::RefCell>, } impl GameLevel<'_, '_> { fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { @@ -165,7 +167,20 @@ impl NaturalLevel for GameLevel<'_, '_> { binding: self.w.collision, subject: None, }; + // getEntityCollisions(null, box): living shulkers are solid. + let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut scene, bounds) + && !self.game.mobs.iter().any(|m| { + m.species() == Species::Shulker + && m.alive() + && !m.removed + && m.bounds().intersects(grown) + }) + && !self + .pending_ids + .borrow() + .iter() + .any(|(id, b)| id == "minecraft:shulker" && b.intersects(grown)) } fn unobstructed(&self, bounds: Aabb) -> bool { let player = self @@ -194,12 +209,49 @@ impl NaturalLevel for GameLevel<'_, '_> { self.w.data.state(self.state(x, y, z)).flags & data::LAND != 0 } } +impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { + fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool { + let Some(p) = self.game.player_view() else { + return false; + }; + if !p.alive || p.spectator { + return false; + } + let at = self.game.player.as_ref().map(|p| p.position); + at.is_some_and(|a| { + let d = (a.x - x).powi(2) + (a.y - y).powi(2) + (a.z - z).powi(2); + range < 0.0 || d < range * range + }) + } + fn spawner_blocks_work(&self) -> bool { + self.game.ui.rules.bool("spawner_blocks_work") + } + fn entity_exists(&self, id: &str) -> bool { + self.game.res.mob_types.contains_key(id) || self.game.entity_type_exists(id) + } + fn count_entities(&self, id: &str, bounds: Aabb) -> usize { + let mobs = self + .game + .mobs + .iter() + .filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds)) + .count(); + let pending = self + .pending_ids + .borrow() + .iter() + .filter(|(k, b)| k == id && b.intersects(bounds)) + .count(); + mobs + pending + } +} impl<'a> Game<'a> { pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> { GameLevel { game: self, w: self.mob_world_base(&[]), pending: Default::default(), + pending_ids: Default::default(), } } /// Creates a mob the spawner accepted, finalized the game's way; the diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 6e4b39866..8eeb4e7c4 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -304,7 +304,7 @@ impl Game<'_> { } } /// A saved mob and, under `Passengers`, the mobs riding it. - fn load_mob(&mut self, tag: Tag, mount: Option) -> Option { + pub(super) fn load_mob(&mut self, tag: Tag, mount: Option) -> Option { self.next_entity += 1; let uuid = entity_nbt::uuid(&tag); // Structure entities placed with finalizeEntities. diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs new file mode 100644 index 000000000..ef61d58ee --- /dev/null +++ b/crates/horizon-client/src/game/spawner.rs @@ -0,0 +1,414 @@ +//! Monster spawners in the game: `SpawnerBlockEntity.serverTick` and +//! `clientTick` for every spawner (`mobs::spawner`), the mobs they add, a +//! spawn egg used on one (`SpawnEggItem.useOn`), their events and the mob +//! spinning inside (`SpawnerRenderer`). +use super::Game; +use horizon_client::{ + Result, + containers::BlockEntity, + mobs::{ + Mob, Who, + spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerSpawn}, + spawning, + }, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_world::nbt::Tag; +use std::collections::{HashMap, HashSet}; + +type Pos = (i32, i32, i32); + +/// What a spawner tick decided to add, created once the level is free. +enum Planned { + /// `finalizeSpawn` ran on a fresh mob. + Finalized(Mob), + /// A mob loaded from the spawn data (with its passengers). + Loaded(Tag), +} + +/// What the spawner code keeps between ticks. +#[derive(Default)] +pub(super) struct SpawnerState { + /// Every entity type id (`EntityType.byString`), read once. + entity_types: Option>, + /// The mob shown in each spawner and the id it was made for + /// (`getOrCreateDisplayEntity`). + displays: HashMap, +} + +impl Game<'_> { + /// `EntityType.byString`: the type is in the registry. + pub(super) fn entity_type_exists(&self, id: &str) -> bool { + self.spawners + .entity_types + .as_ref() + .is_some_and(|t| t.contains(id)) + } + fn load_entity_types(&mut self) { + if self.spawners.entity_types.is_some() { + return; + } + let path = self.options.resources.join("entity-types.json"); + let types = std::fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v.as_object().map(|o| { + o.keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect() + }) + }) + .unwrap_or_default(); + self.spawners.entity_types = Some(types); + } + /// Every spawner's server tick, then its client tick. + pub(super) fn tick_spawners(&mut self) -> Result<()> { + self.load_entity_types(); + let keys: Vec = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Spawner(_))) + .map(|(k, _)| *k) + .collect(); + for key in &keys { + let state = self.world.block(key.0, key.1, key.2); + if &*self.res.facts.get(state).name != "minecraft:spawner" { + continue; + } + let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.remove(key) + else { + continue; + }; + let result = self.server_tick_spawner(*key, &mut spawner); + self.world + .block_entities + .insert(*key, BlockEntity::Spawner(spawner)); + result?; + } + for key in keys { + self.client_tick_spawner(key); + } + let entities = &self.world.block_entities; + self.spawners + .displays + .retain(|k, _| matches!(entities.get(k), Some(BlockEntity::Spawner(_)))); + Ok(()) + } + fn server_tick_spawner(&mut self, key: Pos, spawner: &mut Spawner) -> Result<()> { + let pos = [key.0, key.1, key.2]; + let mut random = std::mem::replace( + &mut self.world.random, + horizon_core::random::LegacyRandom::new(0), + ); + let mut events = Vec::new(); + let mut planned: Vec = Vec::new(); + { + let level = self.natural_level(); + let mut spawn = |l: &super::natural_spawning::GameLevel, r: &SpawnerSpawn| { + l.game.plan_spawner_mob(l, r, &mut planned) + }; + spawner.server_tick(&level, &mut random, pos, &mut spawn, &mut events); + } + self.world.random = random; + // Provisional ids (counting down from u32::MAX) become the mobs' ids. + let mut ids = HashMap::new(); + for (i, plan) in planned.into_iter().enumerate() { + let provisional = u32::MAX - i as u32; + let id = match plan { + Planned::Finalized(mut mob) => { + self.next_entity += 1; + mob.id = self.next_entity; + let id = mob.id; + self.mobs.push(mob); + self.enchant_spawn_equipment(id); + self.spawn_jockeys(id, true); + Some(id) + } + Planned::Loaded(tag) => self.load_mob(tag, None), + }; + if let Some(id) = id { + ids.insert(provisional, id); + } + } + self.apply_spawner_events(key, events, &ids) + } + /// The spawner's `loadEntityRecursive` and `tryAddFreshEntityWithPassengers`: + /// the mob it will add (created after the tick) and its box. + fn plan_spawner_mob( + &self, + l: &super::natural_spawning::GameLevel, + r: &SpawnerSpawn, + planned: &mut Vec, + ) -> Option { + let kind = self.res.mob_types.get(r.id)?.clone(); + let [x, y, z] = r.position; + let at = Vec3::new(x, y, z); + let bounds = if r.finalize { + let mut mob = Mob::new(0, kind, at, r.yaw); + let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32); + let difficulty = self.local_difficulty(r.position); + spawning::finalize(&mut mob, &facts, &difficulty); + horizon_client::mobs::raider::finalize( + &mut mob, + horizon_client::mobs::raider::Reason::Other, + ); + // Shulker.finalizeSpawn faces it south. + if mob.species() == horizon_client::mobs::Species::Shulker { + mob.yaw = 0.0; + mob.previous_yaw = 0.0; + mob.body_yaw = 0.0; + mob.previous_body_yaw = 0.0; + mob.head_yaw = 0.0; + mob.previous_head_yaw = 0.0; + } + let bounds = mob.bounds(); + planned.push(Planned::Finalized(mob)); + bounds + } else { + // A UUID already in the level is refused. + let mut tag = r.entity.clone(); + if let Some(uuid) = horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone())) + && self.persist.uuids.values().any(|u| *u == uuid) + { + return None; + } + let double = |v: f64| Tag::Double(v.to_bits()); + tag.insert( + "Pos".into(), + Tag::List(vec![double(x), double(y), double(z)]), + ); + tag.insert( + "Rotation".into(), + Tag::List(vec![ + Tag::Float(r.yaw.to_bits()), + Tag::Float(0f32.to_bits()), + ]), + ); + let tag = Tag::Compound(tag); + let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?; + let bounds = mob.bounds(); + planned.push(Planned::Loaded(tag)); + bounds + }; + l.pending.borrow_mut().push(bounds); + l.pending_ids.borrow_mut().push((r.id.to_owned(), bounds)); + Some(SpawnerAdded { + id: u32::MAX - (planned.len() as u32 - 1), + bounds, + mob: true, + }) + } + /// What a spawner's tick or a spawn egg did, shown and sent. + fn apply_spawner_events( + &mut self, + key: Pos, + events: Vec, + ids: &HashMap, + ) -> Result<()> { + let pos = [key.0, key.1, key.2]; + for event in events { + match event { + SpawnerEvent::BlockUpdated => self.spawner_block_updated(key), + SpawnerEvent::BlockEvent(id) => { + self.lan_block_event(pos, id, 0); + // The client copy's onEventTriggered. + if let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) { + s.client_event(id); + } + } + SpawnerEvent::LevelEvent(id) => self.level_event_at(id, pos, 0), + SpawnerEvent::EntityPlace(mob, at) => { + let who = ids.get(&mob).map(|id| Who::Mob(*id)); + self.post_block_game_event("minecraft:entity_place", at, who, None); + } + SpawnerEvent::SpawnAnim(mob) => { + if let Some(id) = ids.get(&mob) { + self.mob_poof(*id); + } + } + } + } + Ok(()) + } + /// `sendBlockUpdated`: the clients load the new update tag (the client + /// copy's delay follows it, its display mob is made again). + fn spawner_block_updated(&mut self, key: Pos) { + if let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) { + s.client_loaded(); + } + self.spawners.displays.remove(&key); + if let Some(log) = self.world.block_log.as_mut() { + log.push(key); + } + self.world.modified.insert((key.0 >> 4, key.2 >> 4)); + } + /// `LivingEntity.makePoofParticles` (entity event 20) for a mob. + fn mob_poof(&mut self, id: u32) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); + self.lan_entity_event(id as i32, 20, [at.x, at.y, at.z]); + let options = ParticleOptions::simple(ParticleType::Poof); + for _ in 0..20 { + let r = self.particles.level_random(); + let xa = r.next_gaussian() * 0.02; + let ya = r.next_gaussian() * 0.02; + let za = r.next_gaussian() * 0.02; + let x = at.x + w * (2.0 * r.next_double() - 1.0) - xa * 10.0; + let y = at.y + h * r.next_double() - ya * 10.0; + let z = at.z + w * (2.0 * r.next_double() - 1.0) - za * 10.0; + self.particles.add(&options, [x, y, z], [xa, ya, za]); + } + } + /// `LevelEventHandler` 2004: twenty smoke and flame pairs around the spawner. + pub(super) fn spawner_burst(&mut self, pos: [i32; 3]) { + let (smoke, flame) = ( + ParticleOptions::simple(ParticleType::Smoke), + ParticleOptions::simple(ParticleType::Flame), + ); + for _ in 0..20 { + let r = self.particles.level_random(); + let x = f64::from(pos[0]) + 0.5 + (r.next_double() - 0.5) * 2.0; + let y = f64::from(pos[1]) + 0.5 + (r.next_double() - 0.5) * 2.0; + let z = f64::from(pos[2]) + 0.5 + (r.next_double() - 0.5) * 2.0; + self.particles.add(&smoke, [x, y, z], [0.0; 3]); + self.particles.add(&flame, [x, y, z], [0.0; 3]); + } + } + /// The client copy's tick: particles and the spin while a player is near. + fn client_tick_spawner(&mut self, key: Pos) { + let near = { + let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get(&key) else { + return; + }; + let range = f64::from(s.required_player_range); + let center = [ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]; + self.player.as_ref().is_some_and(|p| { + let d = (p.position.x - center[0]).powi(2) + + (p.position.y - center[1]).powi(2) + + (p.position.z - center[2]).powi(2); + !p.health.dead_or_dying() && !self.spectator() && (range < 0.0 || d < range * range) + }) + }; + let display = self.update_spawner_display(key); + let pos = [key.0, key.1, key.2]; + let random = self.particles.level_random(); + let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) else { + return; + }; + if let Some(p) = s.client_tick(near, display, random, pos) { + self.particles + .add(&ParticleOptions::simple(ParticleType::Smoke), p, [0.0; 3]); + self.particles + .add(&ParticleOptions::simple(ParticleType::Flame), p, [0.0; 3]); + } + } + /// `getOrCreateDisplayEntity`: the mob shown in the spawner, made again + /// when its type changes. False when there is none. + fn update_spawner_display(&mut self, key: Pos) -> bool { + let Some(kind) = self.spawner_display_kind(key) else { + self.spawners.displays.remove(&key); + return false; + }; + if self + .spawners + .displays + .get(&key) + .is_none_or(|(k, _)| *k != kind) + { + let Some(t) = self.res.mob_types.get(&kind).cloned() else { + return false; + }; + let mob = Mob::new(u32::MAX, t, Vec3::ZERO, 0.0); + self.spawners.displays.insert(key, (kind, mob)); + } + true + } + /// The type of the mob a spawner shows: its next data's id, when the game + /// knows the mob. + fn spawner_display_kind(&self, key: Pos) -> Option { + let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get(&key) else { + return None; + }; + let id = s.next_data()?.id()?; + self.res.mob_types.contains_key(&id).then_some(id) + } + /// `SpawnEggItem.useOn` on a spawner: the egg sets its mob. None when the + /// clicked block has no spawner. + pub(super) fn use_spawn_egg_on_spawner(&mut self, pos: [i32; 3], kind: &str) -> Option { + let key = (pos[0], pos[1], pos[2]); + if !matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Spawner(_)) + ) { + return None; + } + if !self.ui.rules.bool("spawner_blocks_work") { + self.system_message(horizon_client::text::Text::translate( + "advMode.notEnabled.spawner", + &[], + )); + return Some(false); + } + let mut events = Vec::new(); + let mut random = std::mem::replace( + &mut self.world.random, + horizon_core::random::LegacyRandom::new(0), + ); + if let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) { + s.set_entity_id(kind, &mut random, &mut events); + } + self.world.random = random; + let _ = self.apply_spawner_events(key, events, &HashMap::new()); + // sendBlockUpdated(3) and the player's block_change game event. + self.spawner_block_updated(key); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + Some(true) + } + /// `SpawnerRenderer`: the next mob of every spawner near the camera, + /// small and turning. + pub(super) fn spawner_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let atlas = &self.res.atlas; + let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + for (key, (_, mob)) in &self.spawners.displays { + let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); + if at.distance_squared(camera) >= 64.0 * 64.0 { + continue; + } + let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get(key) else { + continue; + }; + let (spin, scale) = s.display_pose(alpha as f32, mob.width(), mob.height()); + let origin = glam::Mat4::from_translation( + (at - camera).as_vec3() + glam::Vec3::new(0.5, 0.4, 0.5), + ) * glam::Mat4::from_rotation_y(spin.to_radians()) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.2, 0.0)) + * glam::Mat4::from_rotation_x((-30.0_f32).to_radians()) + * glam::Mat4::from_scale(glam::Vec3::splat(scale)); + let light = self.world.light(key.0, key.1, key.2); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + horizon_client::mobs::render::render_posed( + mob, + alpha as f32, + origin, + &lookup, + packed, + &self.res.mob_data, + out, + ); + } + } +} diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 2451d373f..54e385383 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -254,7 +254,6 @@ impl ChunkEncoder { tag: block_entities .get(&pos) .and_then(entity_tag) - .or_else(|| saved_update_tag(chunk, pos)) .unwrap_or(Tag::End), }); } @@ -343,43 +342,11 @@ fn java_hash_order(items: &mut Vec, pos: impl Fn(&T) -> (i32, i32, i32)) { items.extend(iteration.into_iter().filter_map(|i| slots[i].take())); } -/// The update tag of a block entity Horizon keeps only as loaded NBT: -/// SpawnerBlockEntity.getUpdateTag is its saved fields without -/// SpawnPotentials (saveCustomOnly, so no id or position). -fn saved_update_tag(chunk: &Chunk, pos: (i32, i32, i32)) -> Option { - let saved = chunk.saved.as_ref()?; - let tag = saved.block_entities.iter().find(|t| { - let Tag::Compound(c) = t else { return false }; - let at = |k: &str| match c.get(&k.into()) { - Some(Tag::Int(v)) => Some(*v), - _ => None, - }; - (at("x"), at("y"), at("z")) == (Some(pos.0), Some(pos.1), Some(pos.2)) - })?; - if crate::block_entity_nbt::id(tag).as_deref() != Some("minecraft:mob_spawner") { - return None; - } - let Tag::Compound(mut c) = crate::block_entity_nbt::canonical(tag)? else { - return None; - }; - for key in [ - "id", - "x", - "y", - "z", - "keepPacked", - "SpawnPotentials", - "components", - ] { - c.remove(&key.into()); - } - Some(Tag::Compound(c)) -} - /// The update tag of a block entity (getUpdateTag) for what the client shows. pub fn entity_tag(entity: &BlockEntity) -> Option { match entity { BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())), + BlockEntity::Spawner(s) => Some(s.update_tag()), BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None, _ => None, } diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index a323b914d..1ed11ef54 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -78,6 +78,28 @@ impl Hub { ); } + /// ClientboundBlockEventPacket (`PlayerList.broadcast` within 64 blocks). + pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u16) { + let block = self + .encoder + .block_ids + .get(usize::from(state)) + .copied() + .unwrap_or(0); + let at = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]; + self.broadcast_near( + at, + 64.0, + &C::BlockEvent(play::BlockEvent { + pos, + b0: b0 as u8, + b1: b1 as u8, + block, + }), + None, + ); + } + pub fn entity_event(&self, id: i32, event: i8, at: [f64; 3]) { self.broadcast_near( at, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4c2ff6bba..328265585 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -53,6 +53,7 @@ pub mod shulker; pub mod sniffer; pub mod spawn_rules; pub mod spawn_selection; +pub mod spawner; pub mod spawning; pub mod species; pub mod sulfur_cube; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 638d1d5c1..709de4d77 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -716,6 +716,11 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { m.previous.y + (m.position.y - m.previous.y) * a, m.previous.z + (m.position.z - m.previous.z) * a, ) - camera; + base_transform_at(m, alpha, glam::Mat4::from_translation(p.as_vec3())) +} +/// `base_transform` from a pose of the entity's origin (`EntityRenderDispatcher.submit` +/// under a pose stack, as `SpawnerRenderer` draws the mob inside a spawner). +pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 { let mut body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha; if shaking(m) { // LivingEntityRenderer.setupRotations: a rapid wobble. @@ -737,7 +742,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { None => super::aquatic::rotations(m, alpha, body) .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())), }; - let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation; + let mut base = origin * rotation; if m.death_time > 0 && !super::creaking::tearing_down(m) { let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) .sqrt() @@ -922,25 +927,48 @@ pub fn render_with( let w = super::illusioner::wobble(i, age); let shifted = camera - glam::DVec3::new(off[0] + w[0], off[1] + w[1], off[2] + w[2]); - render_visible(m, alpha, shifted, atlas, light, data, extra, out); + let base = base_transform(m, alpha, shifted); + render_visible(m, alpha, base, atlas, light, data, extra, out); } } return; } - render_visible(m, alpha, camera, atlas, light, data, extra, out); + render_visible( + m, + alpha, + base_transform(m, alpha, camera), + atlas, + light, + data, + extra, + out, + ); +} +/// A mob drawn under `origin` instead of at its position (the spinning mob +/// of `SpawnerRenderer.submitEntityInSpawner`). +pub fn render_posed( + m: &Mob, + alpha: f32, + origin: glam::Mat4, + atlas: Atlas, + light: u32, + data: &MobData, + out: &mut Vec, +) { + let base = base_transform_at(m, alpha, origin); + render_visible(m, alpha, base, atlas, light, data, &[], out); } #[allow(clippy::too_many_arguments)] fn render_visible( m: &Mob, alpha: f32, - camera: glam::DVec3, + base: glam::Mat4, atlas: Atlas, light: u32, data: &MobData, extra: &[(&Part, [f32; 4], u32)], out: &mut Vec, ) { - let base = base_transform(m, alpha, camera); let overlay = u32::from(red_overlay(m)); let s = anim::state(m, alpha); let (model_key, texture) = body(m); diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index 74b371230..fa1ec736a 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -445,7 +445,7 @@ fn fluid_at(l: &L, x: i32, y: i32, z: i32) -> crate::blocks::Fl l.facts().get(l.state(x, y, z)).fluid } /// `checkSpawnRules(level, NATURAL)` of a freshly created mob at a block. -fn mob_spawn_rules(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { +pub(crate) fn mob_spawn_rules(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { use crate::blocks::Fluid; let value = match walk_target(s) { WalkTarget::NotPathfinder | WalkTarget::Zero => 0.0, @@ -584,7 +584,7 @@ pub fn spawn_aabb(s: Species, x: f64, y: f64, z: f64, width: f32, height: f32) - ) } /// `checkSpawnObstruction` of a freshly created mob with the given box. -fn spawn_obstruction( +pub(crate) fn spawn_obstruction( s: Species, l: &L, bounds: Aabb, diff --git a/crates/horizon-client/src/mobs/spawner.rs b/crates/horizon-client/src/mobs/spawner.rs new file mode 100644 index 000000000..726164a89 --- /dev/null +++ b/crates/horizon-client/src/mobs/spawner.rs @@ -0,0 +1,740 @@ +//! The monster spawner (`BaseSpawner` as `SpawnerBlockEntity` runs it): its +//! saved state and `SpawnData`, the server tick that spawns its mobs and the +//! client tick that spins the mob inside and puffs flames. +//! +//! Vanilla keeps a server and a client copy of the block entity; Horizon keeps +//! one [`Spawner`] with the client's own delay and spin beside the server's +//! state. The level's random drives the server tick in vanilla's draw order; +//! what the spawner asks of the level goes through [`SpawnerLevel`], so the +//! game and a differential test world answer the same questions. +use super::{ + Species, + spawn_rules::{self, Reason}, + spawn_selection::{self, Category, NaturalLevel}, +}; +use horizon_core::{geometry::Aabb, geometry::Vec3, random::RandomSource}; +use horizon_world::nbt::{Compound, JavaString, Tag}; + +/// `SpawnData.CustomSpawnRules`: the block and sky light the spawn block +/// must have (inclusive ranges within 0..=15). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CustomSpawnRules { + pub block: (i32, i32), + pub sky: (i32, i32), +} +/// `SpawnData`: the entity to spawn, optional light rules and an equipment +/// table (kept as loaded). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SpawnData { + pub entity: Compound, + pub custom_spawn_rules: Option, + pub equipment: Option, +} +impl SpawnData { + /// The `SpawnData` constructor: an `id` that is a valid identifier is + /// stored normalised (`zombie` becomes `minecraft:zombie`), any other is + /// removed. + pub fn new( + mut entity: Compound, + rules: Option, + equipment: Option, + ) -> Self { + let key = JavaString::from("id"); + let id = match entity.get(&key) { + Some(Tag::String(s)) => normalize_id(&s.to_string_lossy()), + _ => None, + }; + match id { + Some(id) => { + entity.insert(key, Tag::String(id.as_str().into())); + } + None => { + entity.remove(&key); + } + } + Self { + entity, + custom_spawn_rules: rules, + equipment, + } + } + /// The entity's `id`, if any. + pub fn id(&self) -> Option { + match self.entity.get(&JavaString::from("id")) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } + } + /// `SpawnData.CODEC`: `entity` (required), `custom_spawn_rules` and + /// `equipment`. + pub fn decode(tag: &Tag) -> Option { + let Some(Tag::Compound(entity)) = tag.get("entity") else { + return None; + }; + let rules = match tag.get("custom_spawn_rules") { + Some(Tag::Compound(_)) => { + let rules = tag.get("custom_spawn_rules")?; + Some(CustomSpawnRules { + block: light_limit(rules.get("block_light_limit"))?, + sky: light_limit(rules.get("sky_light_limit"))?, + }) + } + Some(_) => return None, + None => None, + }; + Some(Self::new( + entity.clone(), + rules, + tag.get("equipment").cloned(), + )) + } + pub fn encode(&self) -> Tag { + let mut out = vec![("entity", Tag::Compound(self.entity.clone()))]; + if let Some(r) = self.custom_spawn_rules { + let mut rules = Vec::new(); + for (name, range) in [("block_light_limit", r.block), ("sky_light_limit", r.sky)] { + // lenientOptionalFieldOf: the full range is left out. + if range != (0, 15) { + rules.push((name, encode_range(range))); + } + } + out.push(("custom_spawn_rules", Tag::compound(rules))); + } + if let Some(e) = &self.equipment { + out.push(("equipment", e.clone())); + } + Tag::compound(out) + } + /// The entity compound is only its `id` (`hasNoConfiguration`): the + /// spawned mob is finalized. + fn unconfigured(&self) -> bool { + self.entity.len() == 1 && self.id().is_some() + } + /// `CustomSpawnRules.isValidPosition`. + fn valid_position(r: CustomSpawnRules, l: &L, x: i32, y: i32, z: i32) -> bool { + let block = l.block_light(x, y, z); + let sky = (l.sky_light(x, y, z) - l.sky_darken()).max(0); + (r.block.0..=r.block.1).contains(&block) && (r.sky.0..=r.sky.1).contains(&sky) + } +} + +/// `Identifier.CODEC` parsing an entity id: lowercase namespace and path +/// characters, `minecraft` when the namespace is left out. +pub fn normalize_id(s: &str) -> Option { + let (ns, path) = match s.split_once(':') { + Some((ns, path)) => (if ns.is_empty() { "minecraft" } else { ns }, path), + None => ("minecraft", s), + }; + let ok = |c: char, slash: bool| { + c.is_ascii_lowercase() + || c.is_ascii_digit() + || matches!(c, '_' | '-' | '.') + || slash && c == '/' + }; + (ns.chars().all(|c| ok(c, false)) && path.chars().all(|c| ok(c, true))) + .then(|| format!("{ns}:{path}")) +} + +/// A whole number from any numeric tag (`NumericTag.intValue`: floats floor). +fn number(tag: Option<&Tag>) -> Option { + Some(match tag? { + Tag::Byte(v) => i64::from(*v), + Tag::Short(v) => i64::from(*v), + Tag::Int(v) => i64::from(*v), + Tag::Long(v) => *v, + Tag::Float(b) => f32::from_bits(*b).floor() as i64, + Tag::Double(b) => f64::from_bits(*b).floor() as i64, + _ => return None, + }) +} +/// `InclusiveRange.INT` within 0..=15 (`lenientOptionalFieldOf` with the +/// full range as default): a number, a two-element list or +/// `{min_inclusive, max_inclusive}`. None is a decoding error. +fn light_limit(tag: Option<&Tag>) -> Option<(i32, i32)> { + let int = |t: &Tag| match t { + Tag::Int(v) => Some(*v), + Tag::Byte(v) => Some(i32::from(*v)), + Tag::Short(v) => Some(i32::from(*v)), + _ => None, + }; + let range = match tag { + None => return Some((0, 15)), + Some(Tag::IntArray(v)) if v.len() == 2 => Some((v[0], v[1])), + Some(Tag::List(v)) if v.len() == 2 => int(&v[0]).zip(int(&v[1])), + Some(t @ Tag::Compound(_)) => t + .get("min_inclusive") + .and_then(int) + .zip(t.get("max_inclusive").and_then(int)), + Some(t) => int(t).map(|v| (v, v)), + }; + match range { + // A malformed value falls back to the default (lenient); an + // inverted range or one outside 0..=15 fails validation. + None => Some((0, 15)), + Some((lo, hi)) if lo <= hi && lo >= 0 && hi <= 15 => Some((lo, hi)), + Some(_) => None, + } +} +fn encode_range((lo, hi): (i32, i32)) -> Tag { + if lo == hi { + Tag::Int(lo) + } else { + Tag::IntArray(vec![lo, hi]) + } +} + +/// Which `SpawnData` is next: one of the potentials (the same object in +/// vanilla, so changing it changes the potential) or its own. +#[derive(Clone, Debug, PartialEq)] +enum Next { + Potential(usize), + Own(SpawnData), +} + +/// `BaseSpawner`. +#[derive(Clone, Debug, PartialEq)] +pub struct Spawner { + pub spawn_delay: i32, + /// `SpawnPotentials`: data and weight. + pub potentials: Vec<(SpawnData, i32)>, + next: Option, + pub min_spawn_delay: i32, + pub max_spawn_delay: i32, + pub spawn_count: i32, + pub max_nearby_entities: i32, + pub required_player_range: i32, + pub spawn_range: i32, + /// The client copy's delay (`spawnDelay` on the client level), which + /// speeds the spin up as the next spawn nears. + pub client_delay: i32, + pub spin: f64, + pub o_spin: f64, +} +impl Default for Spawner { + fn default() -> Self { + Self { + spawn_delay: 20, + potentials: Vec::new(), + next: None, + min_spawn_delay: 200, + max_spawn_delay: 800, + spawn_count: 4, + max_nearby_entities: 6, + required_player_range: 16, + spawn_range: 4, + client_delay: 20, + spin: 0.0, + o_spin: 0.0, + } + } +} + +/// What a spawner did that the level shows or sends. +#[derive(Clone, Debug, PartialEq)] +pub enum SpawnerEvent { + /// `setNextSpawnData`: `sendBlockUpdated` with the new update tag. + BlockUpdated, + /// `broadcastEvent(1)`: the block event that resets the clients' delay. + BlockEvent(i32), + /// `levelEvent(2004)`: the flame and smoke burst at the spawner. + LevelEvent(i32), + /// `gameEvent(entity, ENTITY_PLACE, block)`. + EntityPlace(u32, [i32; 3]), + /// `mob.spawnAnim()`: entity event 20 (the poof). + SpawnAnim(u32), +} + +/// A mob or entity the spawner wants to add (`EntityType.loadEntityRecursive` +/// then `tryAddFreshEntityWithPassengers`). +#[derive(Clone, Debug)] +pub struct SpawnerSpawn<'a> { + pub entity: &'a Compound, + pub id: &'a str, + pub position: [f64; 3], + pub yaw: f32, + /// `finalizeSpawn(SPAWNER)` runs (the data is just an id). + pub finalize: bool, + pub equipment: Option<&'a Tag>, +} +/// An entity the level added: its id, box and whether it is a mob. +#[derive(Clone, Copy, Debug)] +pub struct SpawnerAdded { + pub id: u32, + pub bounds: Aabb, + pub mob: bool, +} + +/// What a spawner reads from the level besides the spawn rules. +pub trait SpawnerLevel: NaturalLevel { + /// `hasNearbyAlivePlayer`: a living non-spectator closer than `range` + /// (any distance when negative). + fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool; + /// The `spawner_blocks_work` game rule. + fn spawner_blocks_work(&self) -> bool; + /// `EntityType.byString`: the entity type exists. + fn entity_exists(&self, id: &str) -> bool; + /// Entities of the exact class of `id` whose box meets `bounds`. + fn count_entities(&self, id: &str, bounds: Aabb) -> usize; +} + +impl Spawner { + /// `BaseSpawner.load` (`SpawnerBlockEntity.loadAdditional`). + pub fn load(tag: &Tag) -> Self { + let mut s = Self { + spawn_delay: number(tag.get("Delay")).map_or(20, |v| i32::from(v as i16)), + ..Self::default() + }; + s.next = tag + .get("SpawnData") + .and_then(SpawnData::decode) + .map(Next::Own); + s.potentials = match tag.get("SpawnPotentials") { + Some(Tag::List(list)) => list + .iter() + .filter_map(|e| { + let weight = match e.get("weight") { + Some(Tag::Int(w)) if *w >= 0 => *w, + _ => return None, + }; + Some((SpawnData::decode(e.get("data")?)?, weight)) + }) + .collect(), + // WeightedList.of(nextSpawnData), the same object, when the + // potentials are missing or not a list. + _ => { + let data = match s.next.take() { + Some(Next::Own(d)) => d, + _ => SpawnData::default(), + }; + let had = tag.get("SpawnData").and_then(SpawnData::decode).is_some(); + if had { + s.next = Some(Next::Potential(0)); + } + vec![(data, 1)] + } + }; + let int = |k: &str, d: i32| number(tag.get(k)).map_or(d, |v| v as i32); + s.min_spawn_delay = int("MinSpawnDelay", 200); + s.max_spawn_delay = int("MaxSpawnDelay", 800); + s.spawn_count = int("SpawnCount", 4); + s.max_nearby_entities = int("MaxNearbyEntities", 6); + s.required_player_range = int("RequiredPlayerRange", 16); + s.spawn_range = int("SpawnRange", 4); + s.client_delay = s.spawn_delay; + s + } + /// `BaseSpawner.save`: the fields as shorts, the next data when set and + /// the potentials. + pub fn save(&self) -> Vec<(&'static str, Tag)> { + let short = |v: i32| Tag::Short(v as i16); + let mut out = vec![ + ("Delay", short(self.spawn_delay)), + ("MinSpawnDelay", short(self.min_spawn_delay)), + ("MaxSpawnDelay", short(self.max_spawn_delay)), + ("SpawnCount", short(self.spawn_count)), + ("MaxNearbyEntities", short(self.max_nearby_entities)), + ("RequiredPlayerRange", short(self.required_player_range)), + ("SpawnRange", short(self.spawn_range)), + ]; + if let Some(next) = self.next_data() { + out.push(("SpawnData", next.encode())); + } + out.push(( + "SpawnPotentials", + Tag::List( + self.potentials + .iter() + .map(|(d, w)| Tag::compound([("data", d.encode()), ("weight", Tag::Int(*w))])) + .collect(), + ), + )); + out + } + /// `SpawnerBlockEntity.getUpdateTag`: the saved fields without the potentials. + pub fn update_tag(&self) -> Tag { + Tag::compound( + self.save() + .into_iter() + .filter(|(k, _)| *k != "SpawnPotentials"), + ) + } + pub fn next_data(&self) -> Option<&SpawnData> { + match self.next.as_ref()? { + Next::Own(d) => Some(d), + Next::Potential(i) => self.potentials.get(*i).map(|(d, _)| d), + } + } + fn next_data_mut(&mut self) -> Option<&mut SpawnData> { + match self.next.as_mut()? { + Next::Own(d) => Some(d), + Next::Potential(i) => self.potentials.get_mut(*i).map(|(d, _)| d), + } + } + /// `WeightedList.getRandom`: one draw over the total weight, none when + /// the list weighs nothing. + fn random_potential(&self, random: &mut impl RandomSource) -> Option { + let total: i64 = self.potentials.iter().map(|(_, w)| i64::from(*w)).sum(); + if total == 0 { + return None; + } + let mut pick = i64::from( + random + .next_int_bound(total.min(i64::from(i32::MAX)) as i32) + .unwrap_or(0), + ); + for (i, (_, w)) in self.potentials.iter().enumerate() { + pick -= i64::from(*w); + if pick < 0 { + return Some(i); + } + } + None + } + /// `getOrCreateNextSpawnData`: a potential at random, or empty data. + fn next_or_create(&mut self, random: &mut impl RandomSource, events: &mut Vec) { + if self.next.is_some() { + return; + } + self.next = Some(match self.random_potential(random) { + Some(i) => Next::Potential(i), + None => Next::Own(SpawnData::default()), + }); + events.push(SpawnerEvent::BlockUpdated); + } + /// `setEntityId`: the next data's `id` (a spawn egg used on the spawner). + pub fn set_entity_id( + &mut self, + id: &str, + random: &mut impl RandomSource, + events: &mut Vec, + ) { + self.next_or_create(random, events); + if let Some(d) = self.next_data_mut() { + d.entity.insert("id".into(), Tag::String(id.into())); + } + } + /// `isNearPlayer`. + fn near_player(&self, l: &L, pos: [i32; 3]) -> bool { + l.alive_player_near( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + f64::from(self.required_player_range), + ) + } + /// `delay`: the next delay, a new potential (when there are any) and the + /// block event. + fn delay(&mut self, random: &mut impl RandomSource, events: &mut Vec) { + self.spawn_delay = if self.max_spawn_delay <= self.min_spawn_delay { + self.min_spawn_delay + } else { + self.min_spawn_delay + + random + .next_int_bound(self.max_spawn_delay - self.min_spawn_delay) + .unwrap_or(0) + }; + if let Some(i) = self.random_potential(random) { + self.next = Some(Next::Potential(i)); + events.push(SpawnerEvent::BlockUpdated); + } + events.push(SpawnerEvent::BlockEvent(1)); + } + /// `serverTick`. `spawn` adds an entity the spawner accepted and returns + /// it, or None when the level would not take it. + pub fn server_tick( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option, + events: &mut Vec, + ) { + if !self.near_player(l, pos) || !l.spawner_blocks_work() { + return; + } + if self.spawn_delay == -1 { + self.delay(random, events); + } + if self.spawn_delay > 0 { + self.spawn_delay -= 1; + return; + } + let mut delay = false; + self.next_or_create(random, events); + let Some(data) = self.next_data().cloned() else { + return; + }; + // Boxes of what this tick added, for the obstruction test. + let mut added: Vec = Vec::new(); + for _ in 0..self.spawn_count { + // EntityType.by: an unknown type delays. + let Some(id) = data.id().filter(|id| l.entity_exists(id)) else { + self.delay(random, events); + return; + }; + let at = match read_pos(data.entity.get(&JavaString::from("Pos"))) { + Some(p) => p, + None => { + let range = f64::from(self.spawn_range); + let x = f64::from(pos[0]) + + (random.next_double() - random.next_double()) * range + + 0.5; + let y = f64::from(pos[1] + random.next_int_bound(3).unwrap_or(0) - 1); + let z = f64::from(pos[2]) + + (random.next_double() - random.next_double()) * range + + 0.5; + [x, y, z] + } + }; + let kind = l.mob_type(&id); + let (species, width, height, category) = match kind { + Some((s, w, h, c)) => (Some(s), w, h, c), + // Entity types Horizon cannot create: a unit box, misc. + None => (None, 1.0, 1.0, Category::Misc), + }; + let spawn_box = match species { + Some(s) => spawn_selection::spawn_aabb(s, at[0], at[1], at[2], width, height), + None => spawn_selection::spawn_box(at[0], at[1], at[2], width, height), + }; + if !l.no_collision(spawn_box) { + continue; + } + let block = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + if let Some(rules) = data.custom_spawn_rules { + if !category.friendly() && l.peaceful() { + continue; + } + if !SpawnData::valid_position(rules, l, block[0], block[1], block[2]) { + continue; + } + } else if let Some(s) = species + && !spawn_rules::check_spawn_rules( + s, + l, + Reason::Spawner, + random, + block[0], + block[1], + block[2], + ) + { + continue; + } + // loadEntityRecursive: a type the game cannot create delays. + let Some(s) = species else { + self.delay(random, events); + return; + }; + let around = Aabb::new( + Vec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])), + Vec3::new( + f64::from(pos[0] + 1), + f64::from(pos[1] + 1), + f64::from(pos[2] + 1), + ), + ) + .inflate(Vec3::new( + f64::from(self.spawn_range), + f64::from(self.spawn_range), + f64::from(self.spawn_range), + )); + if l.count_entities(&id, around) as i64 >= i64::from(self.max_nearby_entities) { + self.delay(random, events); + return; + } + let yaw = random.next_float() * 360.0; + // The entity's own position (Entity.setPos, which a shulker snaps + // to its block) for its box and its block. + let placed = entity_position(s, at); + let own = [ + placed[0].floor() as i32, + placed[1].floor() as i32, + placed[2].floor() as i32, + ]; + let bounds = spawn_selection::spawn_box(placed[0], placed[1], placed[2], width, height); + let rules_ok = data.custom_spawn_rules.is_some() + || spawn_selection::mob_spawn_rules(s, l, own[0], own[1], own[2]); + if !rules_ok + || !spawn_selection::spawn_obstruction(s, l, bounds, &added, own[0], own[1], own[2]) + { + continue; + } + let request = SpawnerSpawn { + entity: &data.entity, + id: &id, + position: placed, + yaw, + finalize: data.unconfigured(), + equipment: data.equipment.as_ref(), + }; + let Some(result) = spawn(l, &request) else { + self.delay(random, events); + return; + }; + added.push(result.bounds); + events.push(SpawnerEvent::LevelEvent(2004)); + events.push(SpawnerEvent::EntityPlace(result.id, block)); + if result.mob { + events.push(SpawnerEvent::SpawnAnim(result.id)); + } + delay = true; + } + if delay { + self.delay(random, events); + } + } + /// `clientTick`: with a player near and a mob to show, a smoke and flame + /// particle at a random point of the block (returned) and the spin. + pub fn client_tick( + &mut self, + near_player: bool, + has_display: bool, + random: &mut impl RandomSource, + pos: [i32; 3], + ) -> Option<[f64; 3]> { + if !near_player { + self.o_spin = self.spin; + return None; + } + if !has_display { + return None; + } + let p = [ + f64::from(pos[0]) + random.next_double(), + f64::from(pos[1]) + random.next_double(), + f64::from(pos[2]) + random.next_double(), + ]; + if self.client_delay > 0 { + self.client_delay -= 1; + } + self.o_spin = self.spin; + self.spin = + (self.spin + f64::from(1000.0_f32 / (self.client_delay as f32 + 200.0))) % 360.0; + Some(p) + } + /// `onEventTriggered` on the client: event 1 resets the delay. + pub fn client_event(&mut self, id: i32) -> bool { + if id == 1 { + self.client_delay = self.min_spawn_delay; + true + } else { + false + } + } + /// The client copy received an update tag (`load`): its delay follows. + pub fn client_loaded(&mut self) { + self.client_delay = self.spawn_delay; + } + /// `TrialSpawnerRenderer.extractSpawnerData`: the spin in degrees and + /// the scale of a display mob of the given size. + pub fn display_pose(&self, alpha: f32, width: f32, height: f32) -> (f32, f32) { + let spin = (self.o_spin + f64::from(alpha) * (self.spin - self.o_spin)) as f32 * 10.0; + let longest = width.max(height); + let scale = if longest > 1.0 { + 0.53125 / longest + } else { + 0.53125 + }; + (spin, scale) + } +} + +/// `Entity.setPos` of a fresh mob: a shulker sits at the centre of its block. +pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] { + if s == Species::Shulker { + [ + at[0].floor() + 0.5, + (at[1] + 0.5).floor(), + at[2].floor() + 0.5, + ] + } else { + at + } +} + +/// `Vec3.CODEC`: a list of three doubles. +fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> { + let Tag::List(v) = tag? else { + return None; + }; + if v.len() != 3 { + return None; + } + let mut out = [0.0; 3]; + for (o, t) in out.iter_mut().zip(v) { + *o = match t { + Tag::Double(b) => f64::from_bits(*b), + Tag::Float(b) => f64::from(f32::from_bits(*b)), + _ => return None, + }; + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + fn tag(snbt: &str) -> Tag { + horizon_world::nbt::parse_snbt(snbt).expect("snbt").0 + } + + #[test] + fn load_without_potentials_shares_the_next_data() { + let mut s = Spawner::load(&tag("{SpawnData:{entity:{id:\"zombie\"}}}")); + assert_eq!(s.potentials.len(), 1); + assert_eq!( + s.next_data().and_then(SpawnData::id).as_deref(), + Some("minecraft:zombie") + ); + let mut events = Vec::new(); + s.set_entity_id("minecraft:skeleton", &mut LegacyRandom::new(0), &mut events); + assert!(events.is_empty()); + assert_eq!( + s.potentials[0].0.id().as_deref(), + Some("minecraft:skeleton") + ); + } + + #[test] + fn generated_spawner_keeps_no_potentials() { + let s = Spawner::load(&tag( + "{SpawnData:{entity:{id:\"minecraft:cave_spider\"}},SpawnPotentials:[]}", + )); + assert!(s.potentials.is_empty()); + let saved = Tag::compound(s.save()); + assert_eq!(saved.get("SpawnPotentials"), Some(&Tag::List(Vec::new()))); + assert_eq!(saved.get("Delay"), Some(&Tag::Short(20))); + } + + #[test] + fn invalid_ids_are_removed() { + let d = SpawnData::new( + match tag("{id:\"Zombie\"}") { + Tag::Compound(c) => c, + _ => unreachable!(), + }, + None, + None, + ); + assert!(d.id().is_none()); + assert_eq!(normalize_id(":pig").as_deref(), Some("minecraft:pig")); + } + + #[test] + fn light_limits_decode_and_encode() { + assert_eq!(light_limit(Some(&tag("7"))), Some((7, 7))); + assert_eq!(light_limit(Some(&tag("[I;0,7]"))), Some((0, 7))); + assert_eq!( + light_limit(Some(&tag("{min_inclusive:2,max_inclusive:9}"))), + Some((2, 9)) + ); + assert_eq!(light_limit(Some(&tag("[I;9,2]"))), None); + assert_eq!(encode_range((3, 3)), Tag::Int(3)); + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 970432080..94b60f3b0 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -466,6 +466,7 @@ pub fn encode_block_entity( entries.push(("creaking", uuid_tag(uuid))); } } + BlockEntity::Spawner(s) => entries.extend(s.save()), } Tag::compound(entries) } @@ -588,6 +589,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Lectern(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) => {} + BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), } Some((pos, entity)) } diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 09288359b..86d83f4ed 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -44,6 +44,10 @@ pub fn block_entities( let Some(mut entity) = BlockEntity::for_block(block) else { continue; }; + // MonsterRoomFeature and the structures' setEntityId. + if let BlockEntity::Spawner(s) = &mut entity { + **s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone())); + } if let (BlockEntity::Chest(slots), Some(table), Some(loot)) = (&mut entity, text(nbt, "LootTable"), loot) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index ce6b8cdc7..4093c0538 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -478,6 +478,9 @@ public final class VanillaBlockUpdateOracle { /** The levels by dimension (the portal oracle's two). */ Map, net.minecraft.server.level.ServerLevel> levels; @Override public net.minecraft.server.level.ServerLevel getLevel(net.minecraft.resources.ResourceKey key) { return levels == null ? null : levels.get(key); } + /** The player list of the oracles whose player is an operator; null elsewhere. */ + static net.minecraft.server.players.PlayerList players; + @Override public net.minecraft.server.players.PlayerList getPlayerList() { return players; } @Override public int getMaxPlayers() { return 0; } @Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; } @Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 721d260f4..abbd13dc4 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -250,6 +250,7 @@ public final class VanillaDispenserOracle { if (f.has("rules")) { for (var rule : f.getAsJsonObject("rules").entrySet()) { if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null); + if (rule.getKey().equals("spawner_blocks_work")) w.rules.set(GameRules.SPAWNER_BLOCKS_WORK, rule.getValue().getAsBoolean(), null); } } if (f.has("items")) { @@ -284,6 +285,10 @@ public final class VanillaDispenserOracle { // Creating the targets must not move the stream the dispenser draws from. w.rng = new LegacyRandomSource(f.get("seed").getAsLong()); VanillaBlockUpdateOracle.set(Level.class, w, "random", w.rng); + // Spawners have their block entity from the start (the oracle level makes them on demand). + for (var cell : List.copyOf(w.cells.entrySet())) { + if (cell.getValue().getBlock() instanceof net.minecraft.world.level.block.SpawnerBlock) w.getBlockEntity(cell.getKey()); + } w.log = new StringBuilder(); w.blockEvents.clear(); Map before = new HashMap<>(w.cells); @@ -330,6 +335,18 @@ public final class VanillaDispenserOracle { + " signal=" + crafter.getRedstoneSignal() + " disabled=" + disabled); } } + for (BlockPos at : containers) { + // A spawner's next spawn data, potentials and delay (BaseSpawner.save). + if (w.blockEntities.get(at) instanceof net.minecraft.world.level.block.entity.SpawnerBlockEntity spawner) { + var out = net.minecraft.world.level.storage.TagValueOutput.createWithContext(net.minecraft.util.ProblemReporter.DISCARDING, ParityData.access); + spawner.getSpawner().save(out); + var saved = out.buildResult(); + var entity = saved.getCompound("SpawnData").flatMap(d -> d.getCompound("entity")); + String next = entity.map(e -> e.getString("id").orElse("?") + "/" + e.size()).orElse("-"); + result.add("spawner " + VanillaBlockUpdateOracle.pos(at) + " next=" + next + " potentials=" + saved.getListOrEmpty("SpawnPotentials").size() + + " delay=" + saved.getShortOr("Delay", (short) 0)); + } + } for (BlockPos at : containers) { if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue; List items = w.blockEntities.get(at) instanceof Container c && !hasList(c) ? List.of(c.getItem(0)) : slots(w.blockEntities.get(at)); @@ -449,6 +466,16 @@ public final class VanillaDispenserOracle { @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count); } + @Override public net.minecraft.server.players.NameAndId nameAndId() { return new net.minecraft.server.players.NameAndId(new UUID(0L, 0L), "Player"); } + @Override public void sendSystemMessage(net.minecraft.network.chat.Component message) { + stats.add("msg " + (message.getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents t ? t.getKey() : message.getString())); + } + } + + /** The single player's list: the player is an operator (cheats are on). */ + static final class Ops extends net.minecraft.server.players.PlayerList { + Ops() { super(null, null, null, null); } + @Override public boolean isOp(net.minecraft.server.players.NameAndId nameAndId) { return true; } } /** @@ -460,6 +487,9 @@ public final class VanillaDispenserOracle { * the item the player started using follow. */ static List useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception { + if (VanillaBlockUpdateOracle.Server.players == null) { + VanillaBlockUpdateOracle.Server.players = (Ops) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Ops.class); + } Clicker player = (Clicker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Clicker.class); player.world = w; player.creative = use.get("creative").getAsBoolean(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java index 7f1420eba..641b096a9 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java @@ -113,6 +113,23 @@ public final class VanillaNaturalSpawnOracle { @Override public double nextGaussian() { return 0.0; } } + /** + * finalizeSpawn's random in spawner cases: the neutral answers, except that + * nextInt(100) answers 99 so no spider spawns with a skeleton riding it. + */ + static final class SpawnerNeutral implements RandomSource { + @Override public RandomSource fork() { return this; } + @Override public net.minecraft.world.level.levelgen.PositionalRandomFactory forkPositional() { throw new UnsupportedOperationException(); } + @Override public void setSeed(long seed) {} + @Override public int nextInt() { return 0; } + @Override public int nextInt(int bound) { return bound == 100 ? 99 : 0; } + @Override public long nextLong() { return 0L; } + @Override public boolean nextBoolean() { return false; } + @Override public float nextFloat() { return 0.75F; } + @Override public double nextDouble() { return 0.75; } + @Override public double nextGaussian() { return 0.0; } + } + static final class Lvl extends ServerLevel { Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } RegistryAccess registries; @@ -140,6 +157,11 @@ public final class VanillaNaturalSpawnOracle { ServerChunkCache chunkSource; StructureManager structures; RandomSource neutral = new Neutral(); + RandomSource spawnerNeutral = new SpawnerNeutral(); + /** Spawner cases: the level's own random, but for finalizeSpawn's draws. */ + RandomSource spawnerRandom; + /** Spawner cases: the tick whose events are logged (-1 while loading). */ + int tick = -1; List log; boolean logColumns; int next = 1; @@ -183,7 +205,23 @@ public final class VanillaNaturalSpawnOracle { @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 neutral; } + @Override public RandomSource getRandom() { + if (spawnerRandom == null) return neutral; + boolean finalizing = StackWalker.getInstance().walk(f -> f.anyMatch(x -> x.getMethodName().equals("finalizeSpawn"))); + return finalizing ? spawnerNeutral : spawnerRandom; + } + @Override public boolean tryAddFreshEntityWithPassengers(Entity entity) { + addFreshEntityWithPassengers(entity); + log.add(tick + " spawn " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()) + " " + bits(entity.getX()) + " " + bits(entity.getY()) + " " + bits(entity.getZ()) + " " + yaw(entity)); + return true; + } + @Override public void blockEvent(BlockPos pos, net.minecraft.world.level.block.Block block, int b0, int b1) { if (tick >= 0) log.add(tick + " bevent " + b0 + " " + b1); } + @Override public void sendBlockUpdated(BlockPos pos, BlockState old, BlockState current, int flags) { if (tick >= 0) log.add(tick + " update"); } + @Override public void levelEvent(Entity source, int type, BlockPos pos, int data) { if (tick >= 0) log.add(tick + " levent " + type + " " + data); } + @Override public void gameEvent(Holder event, Vec3 at, net.minecraft.world.level.gameevent.GameEvent.Context context) { + if (tick >= 0) log.add(tick + " gevent " + event.unwrapKey().orElseThrow().identifier() + " " + Mth.floor(at.x) + " " + Mth.floor(at.y) + " " + Mth.floor(at.z)); + } + @Override public void broadcastEntityEvent(Entity entity, byte event) { if (tick >= 0) log.add(tick + " eevent " + event); } @Override public ServerChunkCache getChunkSource() { return chunkSource; } @Override public StructureManager structureManager() { return structures; } @Override public LevelData.RespawnData getRespawnData() { return respawn; } @@ -299,6 +337,7 @@ public final class VanillaNaturalSpawnOracle { @Override public boolean isSpectator() { return mode == GameType.SPECTATOR; } @Override public boolean isCreative() { return mode == GameType.CREATIVE; } @Override public GameType gameMode() { return mode; } + @Override public boolean isAlive() { return true; } } static String bits(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } @@ -358,6 +397,7 @@ public final class VanillaNaturalSpawnOracle { level.playerList = new ArrayList<>(); level.border = new WorldBorder(); level.neutral = new Neutral(); + level.spawnerNeutral = new SpawnerNeutral(); 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.biomeAt(pos.getX(), pos.getY(), pos.getZ()); } @@ -424,6 +464,7 @@ public final class VanillaNaturalSpawnOracle { level.seed = Long.parseLong(c.getOrDefault("wseed", "0")); level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal")); level.rules.set(net.minecraft.world.level.gamerules.GameRules.SPAWN_MOBS, !c.getOrDefault("rules", "1").equals("0"), null); + level.rules.set(net.minecraft.world.level.gamerules.GameRules.SPAWNER_BLOCKS_WORK, !c.getOrDefault("spawners", "1").equals("0"), null); // The dimension and biome layers; the moon timeline's surface slime chance as a constant. level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level) .addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder() @@ -476,7 +517,37 @@ public final class VanillaNaturalSpawnOracle { Chunk chunk = (Chunk) alloc(Chunk.class); chunk.level = level; chunk.at = new ChunkPos(Integer.parseInt(cp[0]), Integer.parseInt(cp[1])); - if (mode.equals("gen")) { + if (mode.equals("spawner")) { + // SpawnerBlockEntity.serverTick, `ticks` times, at `spos`, loaded from `snbt` (base64 SNBT). + level.spawnerRandom = mainRandom; + level.tick = -1; + String[] sp = c.get("spos").split(","); + BlockPos at = new BlockPos(Integer.parseInt(sp[0]), Integer.parseInt(sp[1]), Integer.parseInt(sp[2])); + var nbt = net.minecraft.nbt.TagParser.parseCompoundFully(new String(Base64.getDecoder().decode(c.get("snbt")), StandardCharsets.UTF_8)); + var spawner = new net.minecraft.world.level.block.entity.SpawnerBlockEntity(at, Blocks.SPAWNER.defaultBlockState()); + spawner.getSpawner().load(level, at, net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, access, nbt)); + int ticks = Integer.parseInt(c.getOrDefault("ticks", "1")); + try { + for (int t = 0; t < ticks; t++) { + level.tick = t; + net.minecraft.world.level.block.entity.SpawnerBlockEntity.serverTick(level, at, Blocks.SPAWNER.defaultBlockState(), spawner); + } + } finally { + level.tick = -1; + level.spawnerRandom = null; + } + var out = net.minecraft.world.level.storage.TagValueOutput.createWithContext(net.minecraft.util.ProblemReporter.DISCARDING, access); + spawner.getSpawner().save(out); + CompoundTag saved = out.buildResult(); + String next = saved.getCompound("SpawnData").flatMap(d -> d.getCompound("entity")).flatMap(e -> e.getString("id")).orElse("-"); + StringBuilder pots = new StringBuilder(); + for (var p : saved.getListOrEmpty("SpawnPotentials")) { + String id = ((CompoundTag) p).getCompound("data").flatMap(d -> d.getCompound("entity")).flatMap(e -> e.getString("id")).orElse("-"); + pots.append(pots.isEmpty() ? "" : ",").append(id).append('*').append(((CompoundTag) p).getIntOr("weight", 0)); + } + log.add("end delay=" + saved.getShortOr("Delay", (short) 0) + " next=" + next + " pots=" + pots); + log.add("next " + mainRandom.nextInt(1000)); + } else if (mode.equals("gen")) { level.logColumns = true; int n = level.entities.size(); RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("gseed", "0"))); diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py new file mode 100644 index 000000000..028f48442 --- /dev/null +++ b/tools/test_spawner_parity.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Compare monster spawners (BaseSpawner.serverTick) with vanilla. + +Java (VanillaNaturalSpawnOracle, mode=spawner) loads a SpawnerBlockEntity from +each case's NBT on the oracle's stand-in ServerLevel and runs +`SpawnerBlockEntity.serverTick` for a number of ticks. Rust +(natural_spawn_fixture, mode=spawner) loads `mobs::spawner::Spawner` from the +same NBT and ticks it on the same world. Both log, tick by tick, every spawn +(type, exact position and yaw bits), `sendBlockUpdated`, the block event, the +2004 level event, the entity_place game event and the spawn animation, then +the saved delay, next spawn data and potentials, and the next draw of the +level random, which pins every draw in between. + +Worlds are rooms around the spawner (dungeons, caves, open fields, flooded +rooms, nether halls) with dark, dim and lit light, players inside and outside +the required range (spectators, a negative range), mobs of the spawner's type +already around it, every difficulty and the spawner_blocks_work rule. Spawn +data covers generated spawners (no potentials), loaded ones (potentials +missing, so shared with the next data), weighted potentials (zero weights +included), custom light rules, fixed `Pos`, configured entities (no +finalizeSpawn), ids without a namespace, unknown, invalid and missing ids, and +delays, counts, caps and ranges from the edge values up. + +finalizeSpawn runs with a fixed random in the oracle (nextInt(100) answers 99 +so spiders do not grow skeleton jockeys); its own outcomes are not compared. +Entity types that are not mobs (Horizon creates only mobs from a spawner) are +not in the corpus. +""" +import argparse +import base64 +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base, test_natural_spawn_parity as natural +except ImportError: + import lab + import test_rust_parity as base + import test_natural_spawn_parity as natural + +box = natural.box +MONSTERS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'blaze', 'silverfish', 'magma_cube', 'creeper', 'witch', + 'enderman', 'zombified_piglin', 'husk', 'stray', 'bogged', 'slime', 'drowned', 'piglin', 'wither_skeleton', + 'endermite', 'parched', 'zombie_villager', 'breeze'] +CREATURES = ['pig', 'cow', 'chicken', 'sheep', 'rabbit', 'wolf', 'bat', 'squid', 'cod', 'strider', 'fox', 'horse'] +FLOORS = ['minecraft:cobblestone', 'minecraft:mossy_cobblestone', 'minecraft:stone', 'minecraft:deepslate', + 'minecraft:grass_block', 'minecraft:netherrack', 'minecraft:sand', 'minecraft:infested_stone'] + + +def entity_snbt(rng, mob, spos): + r = rng.random() + if r < 0.55: + return f'{{id:"minecraft:{mob}"}}' + if r < 0.65: + return f'{{id:"{mob}"}}' + if r < 0.75: + return f'{{id:"minecraft:{mob}",PersistenceRequired:1b}}' + if r < 0.83: + x, y, z = (spos[0] + rng.uniform(-3, 3), spos[1] + rng.choice([0, 0, 1, -1, 3]), spos[2] + rng.uniform(-3, 3)) + return f'{{id:"minecraft:{mob}",Pos:[{x:.4f}d,{y}.0d,{z:.4f}d]}}' + if r < 0.88: + return '{id:"minecraft:not_an_entity"}' + if r < 0.93: + return f'{{id:"{mob.capitalize()}"}}' + return '{}' + + +def spawn_data(rng, mob, spos, rules=True): + out = f'entity:{entity_snbt(rng, mob, spos)}' + if rules and rng.random() < 0.2: + def limit(): + lo = rng.randrange(0, 16) + hi = rng.randrange(lo, 16) + return rng.choice([str(lo), f'[I;{lo},{hi}]', f'{{min_inclusive:{lo},max_inclusive:{hi}}}']) + parts = [] + if rng.random() < 0.7: + parts.append(f'block_light_limit:{limit()}') + if rng.random() < 0.7: + parts.append(f'sky_light_limit:{limit()}') + out += ',custom_spawn_rules:{' + ','.join(parts) + '}' + return '{' + out + '}' + + +def spawner_snbt(rng, mob, spos, pool): + fields = [] + shape = rng.random() + if shape < 0.35: + # Generated (setEntityId): the next data and no potentials. + fields.append(f'SpawnData:{{entity:{{id:"minecraft:{mob}"}}}}') + fields.append('SpawnPotentials:[]') + elif shape < 0.55: + # Potentials missing: the next data becomes the one potential. + fields.append(f'SpawnData:{spawn_data(rng, mob, spos)}') + elif shape < 0.85: + n = rng.randrange(1, 5) + entries = [] + for _ in range(n): + other = mob if rng.random() < 0.5 else rng.choice(pool) + weight = rng.choice([1, 1, 2, 5, 0, 20]) + entries.append(f'{{data:{spawn_data(rng, other, spos)},weight:{weight}}}') + fields.append('SpawnPotentials:[' + ','.join(entries) + ']') + if rng.random() < 0.5: + fields.append(f'SpawnData:{spawn_data(rng, mob, spos)}') + elif shape < 0.95: + fields.append(f'SpawnData:{spawn_data(rng, mob, spos)}') + fields.append(f'SpawnPotentials:[{{data:{spawn_data(rng, mob, spos)},weight:1}}]') + # else: an empty spawner (placed from the item). + fields.append(f'Delay:{rng.choice([0, 0, 1, 3, 20, -1, 5])}s') + if rng.random() < 0.8: + lo = rng.choice([0, 1, 5, 10, 20, 200]) + hi = rng.choice([lo, lo + 1, lo + 10, lo + 40, max(lo - 5, 0)]) + fields.append(f'MinSpawnDelay:{lo}s') + fields.append(f'MaxSpawnDelay:{hi}s') + if rng.random() < 0.6: + fields.append(f'SpawnCount:{rng.choice([1, 2, 4, 4, 6, 8, 0])}s') + if rng.random() < 0.5: + fields.append(f'MaxNearbyEntities:{rng.choice([0, 1, 3, 6, 6, 10])}s') + if rng.random() < 0.4: + fields.append(f'RequiredPlayerRange:{rng.choice([16, 16, 4, 32, -1, 0])}s') + if rng.random() < 0.5: + fields.append(f'SpawnRange:{rng.choice([1, 2, 4, 4, 6, 8])}s') + return '{' + ','.join(fields) + '}' + + +def room(rng): + """A world around the spawner; returns (world, spawner position, the mob).""" + w = natural.World(rng) + dim = rng.choices(['overworld', 'nether', 'end'], [80, 17, 3])[0] + w.dim = f'minecraft:{"the_" if dim != "overworld" else ""}{dim}' + w.kv['dim'] = w.dim + w.min_y = -64 if dim == 'overworld' else 0 + sx, sy, sz = rng.randrange(-8, 9), rng.randrange(-20, 60) if dim == 'overworld' else rng.randrange(30, 90), rng.randrange(-8, 9) + w.surface = sy + if dim == 'nether': + w.kv['biome'] = rng.choice(list(natural.NETHER)) + pool = ['blaze', 'magma_cube', 'zombified_piglin', 'wither_skeleton', 'piglin', 'skeleton', 'strider', 'ghast'] + elif dim == 'end': + w.kv['biome'] = 'minecraft:the_end' + pool = ['enderman', 'endermite', 'zombie', 'shulker'] + else: + w.kv['biome'] = rng.choice(['minecraft:plains', 'minecraft:desert', 'minecraft:dripstone_caves', + 'minecraft:deep_dark', 'minecraft:swamp', 'minecraft:forest']) + pool = MONSTERS + CREATURES + mob = rng.choice(pool) + half, height = rng.choice([3, 4, 4, 5, 6]), rng.choice([3, 4, 4, 6]) + kind = rng.random() + floor = rng.choice(FLOORS if dim == 'overworld' else ['minecraft:netherrack', 'minecraft:nether_bricks', 'minecraft:end_stone']) + if kind < 0.65: + # A dungeon or hall: solid all around, an air room. + w.block(box(sx - 12, sy - 6, sz - 12, sx + 12, sy + 10, sz + 12), rng.choice(['minecraft:stone', 'minecraft:cobblestone', 'minecraft:netherrack'])) + w.block(box(sx - half, sy - 1, sz - half, sx + half, sy - 1, sz + half), floor) + w.block(box(sx - half, sy, sz - half, sx + half, sy + height - 1, sz + half), rng.choice(['minecraft:cave_air', 'minecraft:air'])) + elif kind < 0.85: + # Open ground. + w.block(box(sx - 16, sy - 6, sz - 16, sx + 16, sy - 2, sz + 16), 'minecraft:dirt') + w.block(box(sx - 16, sy - 1, sz - 16, sx + 16, sy - 1, sz + 16), floor) + else: + # A flooded room. + w.block(box(sx - 12, sy - 6, sz - 12, sx + 12, sy + 10, sz + 12), 'minecraft:stone') + w.block(box(sx - half, sy - 1, sz - half, sx + half, sy - 1, sz + half), floor) + w.block(box(sx - half, sy, sz - half, sx + half, sy + height - 1, sz + half), 'minecraft:water') + if rng.random() < 0.5: + mob = rng.choice(['drowned', 'squid', 'cod', 'guardian', 'zombie']) + if rng.random() < 0.3: + # Pillars and slabs in the way. + for _ in range(rng.randrange(1, 6)): + px, pz = sx + rng.randrange(-half, half + 1), sz + rng.randrange(-half, half + 1) + w.block(box(px, sy, pz, px, sy + rng.randrange(0, 3), pz), rng.choice(['minecraft:cobblestone', 'minecraft:oak_slab', 'minecraft:torch', 'minecraft:glass'])) + w.block(box(sx, sy, sz, sx, sy, sz), 'minecraft:spawner') + sky, light = rng.choice([(0, 0), (0, 0), (0, 0), (0, 3), (0, 7), (0, 12), (15, 0), (15, 15), (8, 8)]) + w.light(box(sx - 16, sy - 2, sz - 16, sx + 16, sy + 12, sz + 16), sky, light) + if rng.random() < 0.25: + # A torch's glow on one side. + w.light(box(sx, sy - 1, sz - half, sx + half, sy + height, sz + half), sky, rng.choice([7, 11, 14])) + return w, (sx, sy, sz), mob, pool + + +def players(w, rng, spos): + for _ in range(rng.choice([1, 1, 1, 2, 0])): + r = rng.random() + if r < 0.7: + d = rng.uniform(0, 15) + elif r < 0.85: + d = rng.uniform(14, 18) + else: + d = rng.uniform(18, 40) + import math + a, b = rng.uniform(0, 6.283), rng.uniform(-0.6, 0.6) + x = spos[0] + 0.5 + d * math.cos(a) * math.cos(b) + y = spos[1] + 0.5 + d * math.sin(b) + z = spos[2] + 0.5 + d * math.sin(a) * math.cos(b) + mode = rng.choice(['survival'] * 7 + ['creative', 'adventure', 'spectator']) + w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}') + + +def corpus(): + rng = random.Random(0x5350574E) + cases = [] + for k in range(6000): + w, spos, mob, pool = room(rng) + players(w, rng, spos) + if rng.random() < 0.5: + for _ in range(rng.choice([1, 2, 3, 5, 6, 8])): + t = mob if rng.random() < 0.8 else rng.choice(pool) + x, z = spos[0] + rng.uniform(-6, 7), spos[2] + rng.uniform(-6, 7) + w.entities.append(f'minecraft:{t}/{x:.3f},{spos[1] + rng.choice([0, 0, -1, 2])},{z:.3f}') + natural.common(w, rng, rng.randrange(-2**47, 2**47)) + w.kv.pop('unloaded', None) + if rng.random() < 0.05: + w.kv['spawners'] = 0 + snbt = spawner_snbt(rng, mob, spos, pool) + w.kv['spos'] = f'{spos[0]},{spos[1]},{spos[2]}' + w.kv['snbt'] = base64.b64encode(snbt.encode()).decode() + w.kv['ticks'] = rng.choice([1, 2, 5, 21, 40, 80, 120]) + cases.append(f'spawner/{k} mode=spawner {w.tokens()}') + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-spawner-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/VanillaNaturalSpawnOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] + tested = base.source_hashes(sources) + 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): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + 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.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_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/natural_spawn_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + 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]}') + 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)} cases differ (rust {len(rust)} lines):\n{report}') + base.ensure_sources_unchanged(sources, tested) + spawns = sum(line.count(' spawn minecraft:') for line in vanilla) + delays = sum(line.count(' bevent 1 ') for line in vanilla) + updates = sum(line.count(' update') for line in vanilla) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'spawns': spawns, 'delays': delays, 'block_updates': updates, 'sources_sha256': tested, + 'scope': 'BaseSpawner: load (SpawnData and potentials codecs, shared next data), serverTick (player range, ' + 'spawner_blocks_work, delay, getOrCreateNextSpawnData, Pos, getSpawnAABB collision, custom spawn ' + 'rules and peaceful, SpawnPlacements, the nearby cap, yaw, checkSpawnRules and checkSpawnObstruction, ' + 'events) and delay (weighted potentials), with every level random draw. finalizeSpawn runs with a ' + 'fixed random in the oracle; its own outcomes are not compared.'}) + print(f'{len(cases):,} spawner cases match vanilla ({spawns:,} spawns, {delays:,} delays, {updates:,} block updates)') + + +if __name__ == '__main__': + main() diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index 57080c880..f71bbbe4d 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Compare a player's right click on a block with vanilla's, for items that are -both food and blocks (sweet and glow berries, carrots, potatoes) and for sweet -berry bushes. +both food and blocks (sweet and glow berries, carrots, potatoes), for sweet +berry bushes and for spawn eggs used on a monster spawner. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -10,11 +10,13 @@ right-clicks the top face of the origin holding an item. Vanilla runs the real harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and `useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its -`mayPlaceOn` rules, `BoneMealItem.useOn`, and eating a consumable that could -not be placed). Horizon runs `use_item_as_player` on that hit in a headless -game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, +`mayPlaceOn` rules, `BoneMealItem.useOn`, eating a consumable that could +not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Horizon runs +`use_item_as_player` on that hit in a headless game +(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level events, sounds, game events, the used statistic, the held stack, the -item the player started using, and the level random afterwards. +item the player started using, spawners' next spawn data, potentials and +delay, system messages and the level random afterwards. """ import json import os @@ -34,6 +36,7 @@ ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'car 'wheat_seeds', 'beetroot_seeds', 'apple'] # What is in the way above the clicked block. ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern'] +EGGS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'pig', 'creeper', 'blaze', 'ghast', 'villager', 'bee', 'cod'] def cases(facts, count, seed): @@ -45,7 +48,15 @@ def cases(facts, count, seed): case.pop('thundering', None) cells = [] item = rng.choice(ITEMS) - if rng.random() < 0.3: + if rng.random() < 0.15: + # A spawn egg on a fresh monster spawner (SpawnEggItem.useOn). + cells.append([0, 0, 0, states.get('spawner')]) + if rng.random() < 0.3: + cells.append([0, 1, 0, states.get(rng.choice(['stone', 'water', 'short_grass']))]) + item = rng.choice([f'{e}_spawn_egg' for e in EGGS] + ['apple', '-']) + if rng.random() < 0.15: + case['rules'] = {'spawner_blocks_work': False} + elif rng.random() < 0.3: # A sweet berry bush on grass: pick it, bone meal it, or plant against it. age = rng.randrange(4) cells.append([0, 0, 0, states.get('sweet_berry_bush', age=str(age))])