diff --git a/README.md b/README.md index 9d20a6f5c..9696517eb 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ round-trip harness has not been rerun. | Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences | | Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering | | Audio | 0.75 | Sound engine, music and ambience not compared with vanilla | -| Block behaviours and ticking | 0.75 | Block updates, random ticks and redstone match vanilla; dispensers lack several behaviours | +| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone and dispensers match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems | ### Next steps @@ -50,7 +50,7 @@ round-trip harness has not been rerun. 2. Draw every item through the item model pipeline, and add the resource pack screen. 3. An audio harness: sound engine attenuation, weighted sound events, music and ambience. 4. A mob AI harness, and an oracle for drowned, villagers, traders and the wither. -5. The missing commands and dispenser behaviours, the tab list and world border rendering. +5. The missing commands, containers spilling when replaced, copper golems, the tab list and world border rendering. 6. Test LAN hosting with a vanilla client, and add a dedicated server mode. ```sh diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index b38fb8469..f5f9306db 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1136,22 +1136,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { a.on_ground = flag(tag, "OnGround"); Some(a) } -/// A boat entity (`minecraft:_boat`, `minecraft:bamboo_raft`). +/// A boat entity (`minecraft:_boat`, `minecraft:bamboo_chest_raft`...): +/// chest boats keep their slots in `Items` (`ContainerHelper.saveAllItems`). pub fn boat_to_nbt( - wood: &str, + id: &str, position: Vec3, motion: Vec3, yaw: f32, uuid: [i32; 4], raw: Option<&Tag>, + items: Option<&[Option]>, ) -> Tag { - let id = if wood == "bamboo" { - "minecraft:bamboo_raft".to_owned() - } else { - format!("minecraft:{wood}_boat") - }; - Base { - id: &id, + let mut tag = Base { + id, uuid, position, motion, @@ -1159,7 +1156,11 @@ pub fn boat_to_nbt( on_ground: false, fall_distance: 0.0, } - .tag(raw) + .tag(raw); + if let (Some(items), Tag::Compound(map)) = (items, &mut tag) { + map.insert("Items".into(), crate::save::encode_items(items)); + } + tag } /// A vehicle's base entity tag (boats and minecarts). pub fn vehicle_to_nbt( diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 667e7d911..692875878 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -19,6 +19,7 @@ mod control; mod creaking; mod creatures; mod crossbow; +mod dispense_fixture; mod dispenser; mod dragon; mod enchant_effects; @@ -1020,8 +1021,9 @@ impl Game<'_> { f64::from(pos[2]) + d(z), ]; let v = [d(x) - 0.5, d(y) - 0.5, d(z) - 0.5]; + // LevelEventHandler (2001) runs on the client: its random, not the level's. let particle = - Particle::terrain(&mut self.world.random, p, v, sprite.clone(), tint); + Particle::terrain(self.particles.random(), p, v, sprite.clone(), tint); self.particles.push(particle); } } @@ -1032,7 +1034,8 @@ impl Game<'_> { let Some((sprite, tint)) = self.particle_sprite(state) else { return; }; - let r = &mut self.world.random; + // Client-side particles draw from the client random, not the level's. + let r = self.particles.random(); let mut p = [0.0; 3]; for i in 0..3 { let base = f64::from(pos[i]); @@ -1059,7 +1062,8 @@ impl Game<'_> { ) { self.next_entity += 1; let p = Vec3::new(position[0], position[1], position[2]); - let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0; + // ItemEntity.bobOffs comes from the entity's own random, not the level's. + let bob = self.particles.random().next_float() * std::f32::consts::PI * 2.0; self.dropped.push(ItemEntity { id: self.next_entity, stack, @@ -1072,23 +1076,36 @@ impl Game<'_> { bob_offset: bob, }); } + /// `Block.getDrops`: the block's loot table, drawing from its server random + /// sequence (`LootContext.Builder.create`), else the level random. + fn block_loot(&mut self, state: BlockStateId, held: Option<&ItemStack>) -> Vec { + let registry = self.res.assets.registry; + match self.res.items.block_loot_sequence(registry, state) { + Some(sequence) => { + let random = self.rand_sequences.get(&sequence, self.level.seed); + self.res.items.block_drops(registry, state, held, random) + } + None => self + .res + .items + .block_drops(registry, state, held, &mut self.world.random), + } + } /// Block.popResource fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { self.attach_shulker_contents(pos, &mut stack); self.attach_container_name(pos, &mut stack); self.attach_banner_layers(pos, &mut stack); + // Block.popResource: Mth.nextDouble offsets from the level random; the + // motion is `new ItemEntity(..)`'s own, from the item's random. let r = &mut self.world.random; - let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; + let mut offset = || -0.25 + r.next_double() * 0.5; let p = [ f64::from(pos[0]) + 0.5 + offset(), f64::from(pos[1]) + 0.5 + offset() - 0.125, f64::from(pos[2]) + 0.5 + offset(), ]; - let v = [ - r.next_double() * 0.2 - 0.1, - 0.2, - r.next_double() * 0.2 - 0.1, - ]; + let v = dispenser::new_item_motion(); self.spawn_item(stack, p, v, 10); } /// Player.drop: thrown from the eyes along the view direction. @@ -1363,6 +1380,7 @@ impl Game<'_> { fn process_level_events(&mut self) -> Result<()> { let events = std::mem::take(&mut self.level_events); self.lan_record_events(&events); + dispense_fixture::record_events(&events); for event in events { match event { LevelEvent::LevelEvent { @@ -1370,10 +1388,14 @@ impl Game<'_> { pos, data, } => { - // LevelRenderer: destroy particles and the block's break sound. + // LevelEventHandler: destroy particles and the block's + // break sound (none for air). let state = BlockStateId(data as u32); let p = [pos.x, pos.y, pos.z]; self.destroy_particles(p, state); + if self.res.facts.is_air(state) { + continue; + } let sounds = self.res.facts.get(state).sounds.clone(); let c = [ f64::from(pos.x) + 0.5, @@ -1436,12 +1458,7 @@ impl Game<'_> { let name = self.res.facts.get(state).name.clone(); self.release_contents([pos.x, pos.y, pos.z], entity, &name); } - let drops = self.res.items.block_drops( - self.res.assets.registry, - state, - None, - &mut self.world.random, - ); + let drops = self.block_loot(state, None); for d in drops { if &*d.item != "minecraft:air" { self.pop_resource([pos.x, pos.y, pos.z], d); @@ -1787,12 +1804,7 @@ impl Game<'_> { let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); if harvest { - let drops = self.res.items.block_drops( - self.res.assets.registry, - state, - held.as_ref(), - &mut self.world.random, - ); + let drops = self.block_loot(state, held.as_ref()); let silk = held .as_ref() .is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); @@ -8143,6 +8155,9 @@ pub fn run() -> Result<()> { eprintln!("Horizon: control socket {}", server.path().display()); game.control = Some(server); } + if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") { + return game.dispense_fixture(&spec); + } match game.options.world.clone() { _ if game.options.server.is_some() => { let (address, name) = ( diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 2f6086e17..fbac6ab14 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -48,7 +48,12 @@ pub(super) struct Boat { /// left, right, up, down pub input: [bool; 4], pub on_ground: bool, + /// `ChestBoat`: a chest with 27 slots in the back seat. + pub chest: bool, + pub items: Vec>, } +/// `ChestBoat.CONTAINER_SIZE`. +pub(super) const CHEST_SLOTS: usize = 27; const WIDTH: f64 = 1.375; const HEIGHT: f64 = 0.5625; /// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment. @@ -76,8 +81,16 @@ impl Boat { paddling: [false; 2], input: [false; 4], on_ground: false, + chest: false, + items: Vec::new(), } } + /// A chest boat or chest raft. + pub fn with_chest(mut self) -> Self { + self.chest = true; + self.items = vec![None; CHEST_SLOTS]; + self + } pub fn bounds(&self) -> Aabb { let (w, p) = (WIDTH / 2.0, self.position); Aabb::new( @@ -95,6 +108,30 @@ impl Boat { } } /// Item id -> (boat entity id, wood). +impl Boat { + /// The vanilla entity type id (`oak_boat`, `bamboo_chest_raft`), also + /// the item it drops. + pub(super) fn entity_type(&self) -> String { + let chest = if self.chest { "chest_" } else { "" }; + if &*self.wood == "bamboo" { + format!("minecraft:bamboo_{chest}raft") + } else { + format!("minecraft:{}_{chest}boat", self.wood) + } + } +} +/// The wood of a boat or chest boat item or entity type, and whether it +/// carries a chest. +pub(super) fn any_boat_wood(item: &str) -> Option<(&str, bool)> { + let name = item.strip_prefix("minecraft:")?; + if let Some(wood) = name + .strip_suffix("_chest_boat") + .or_else(|| name.strip_suffix("_chest_raft")) + { + return Some((wood, true)); + } + boat_wood(item).map(|w| (w, false)) +} pub(super) fn boat_wood(item: &str) -> Option<&str> { let name = item.strip_prefix("minecraft:")?; name.strip_suffix("_boat") @@ -103,10 +140,20 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> { } pub(super) struct BoatModels { pub models: HashMap, + pub chest_models: HashMap, } impl BoatModels { + /// Whether a boat of this wood (with or without a chest) can be drawn. + pub fn has(&self, wood: &str, chest: bool) -> bool { + if chest { + self.chest_models.contains_key(wood) + } else { + self.models.contains_key(wood) + } + } pub fn load(root: &std::path::Path) -> Self { let mut models = HashMap::new(); + let mut chest_models = HashMap::new(); if let Ok(bytes) = std::fs::read(root.join("entity-models.json")) && let Ok(serde_json::Value::Object(all)) = serde_json::from_slice::(&bytes) @@ -119,9 +166,19 @@ impl BoatModels { { models.insert(wood.to_owned(), part); } + if let Some(wood) = key + .strip_prefix("minecraft:chest_boat/") + .and_then(|k| k.strip_suffix("#main")) + && let Some(part) = horizon_client::mobs::load_model(root, key) + { + chest_models.insert(wood.to_owned(), part); + } } } - Self { models } + Self { + models, + chest_models, + } } } impl Game<'_> { @@ -457,10 +514,10 @@ impl Game<'_> { } /// `BoatItem.use`: aim at a block or the water surface. pub(super) fn place_boat(&mut self, stack: &ItemStack) -> bool { - let Some(wood) = boat_wood(&stack.item) else { + let Some((wood, chest)) = any_boat_wood(&stack.item) else { return false; }; - if !self.boat_models.models.contains_key(wood) { + if !self.boat_models.has(wood, chest) { return false; } let Some(eye) = self.eye_position() else { @@ -507,12 +564,15 @@ impl Game<'_> { (None, Some(w)) => w.0, (None, None) => return false, }; - let boat = Boat::new( + let mut boat = Boat::new( self.next_entity + 1, Arc::from(wood), Vec3::new(hit[0], hit[1], hit[2]), self.yaw, ); + if chest { + boat = boat.with_chest(); + } let bb = boat.bounds(); let (lo, hi) = (bb.min_position(), bb.max_position()); let e = 1.0e-7; @@ -575,11 +635,24 @@ impl Game<'_> { return false; }; let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); - if !self.before_block(d) - || sneaking - || self.boats[i].out_of_control >= 60.0 - || self.riding.is_some() - { + if !self.before_block(d) { + return false; + } + // ChestBoat.interact: sneaking (or a full seat) opens the chest. + if self.boats[i].chest && (sneaking || self.riding.is_some()) { + let b = &self.boats[i]; + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, b.id as i32); + self.world.block_entities.insert( + key, + horizon_client::containers::BlockEntity::Chest(b.items.clone()), + ); + self.container = Some(key); + self.screen = super::Screen::Inventory; + self.capture(false); + self.right = false; + return true; + } + if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() { return false; } self.riding = Some(self.boats[i].id); @@ -601,13 +674,13 @@ impl Game<'_> { let destroyed = self.creative || b.damage > 40.0; if destroyed { let b = self.boats.remove(i); + let at = [b.position.x, b.position.y, b.position.z]; if !self.creative && self.ui.rules.bool("entity_drops") { - let item = if &*b.wood == "bamboo" { - "minecraft:bamboo_raft".to_owned() - } else { - format!("minecraft:{}_boat", b.wood) - }; - let at = [b.position.x, b.position.y, b.position.z]; + // ChestBoat.destroy: chestVehicleDestroyed spills the contents. + for stack in b.items.iter().flatten() { + self.spawn_item(stack.clone(), at, super::dispenser::new_item_motion(), 10); + } + let item = b.entity_type(); self.spawn_item( ItemStack { item: Arc::from(item.as_str()), @@ -628,14 +701,20 @@ impl Game<'_> { pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; for b in &self.boats { - let Some(model) = self.boat_models.models.get(&*b.wood) else { + let models = if b.chest { + &self.boat_models.chest_models + } else { + &self.boat_models.models + }; + let Some(model) = models.get(&*b.wood) else { continue; }; + let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self .res .atlas .sprites - .get(&format!("entity/boat/{}", b.wood)) + .get(&format!("entity/{folder}/{}", b.wood)) .map(|r| [r.u0, r.v0, r.u1, r.v1]) else { continue; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 9dfed52ea..2f0a7acc9 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -266,13 +266,11 @@ impl Game<'_> { } } Target::Painting(_) => "minecraft:painting".into(), - Target::Boat(id) => self.boats.iter().find(|b| b.id == id).map_or_else( - || "minecraft:oak_boat".into(), - |b| { - let kind = if &*b.wood == "bamboo" { "raft" } else { "boat" }; - format!("minecraft:{}_{kind}", b.wood) - }, - ), + Target::Boat(id) => self + .boats + .iter() + .find(|b| b.id == id) + .map_or_else(|| "minecraft:oak_boat".into(), |b| b.entity_type()), Target::Cart(id) => self .carts .iter() diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index d7436a628..85d298f8f 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -73,12 +73,13 @@ impl Game<'_> { let uuid = self.uuid_for(id); let b = self.boats.iter().find(|b| b.id == id)?; entity_nbt::boat_to_nbt( - &b.wood, + &b.entity_type(), b.position, b.velocity, b.yaw, uuid, self.persist.raw.get(&id), + b.chest.then_some(&b.items[..]), ) } Target::Cart(id) => { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs new file mode 100644 index 000000000..a906ba259 --- /dev/null +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -0,0 +1,510 @@ +//! The Rust side of tools/test_dispenser_parity.py: with +//! `HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT` the game loads its resources, runs +//! every case (a dispenser or dropper with items, blocks and target entities +//! around it) through `dispense_from` on a fresh headless world and prints what +//! changed in the format of `VanillaDispenserOracle`. +use super::{ + Game, + dispenser::{Slot, body_in_head, mob_set_slot, mob_slot_item}, +}; +use horizon_client::{ + Result, + chunk::Chunk, + containers::BlockEntity, + gamerules::Value as RuleValue, + item_data::{canon_stack, parse_stack}, + mobs::{Mob, Species}, + projectiles::ProjectileKind, + world::World, +}; +use horizon_core::{ + position::BlockPos, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::{level::Ticks, registry::BlockStateId}; +use serde_json::Value; +use std::{cell::RefCell, collections::HashMap, fmt::Write as _, io::Write as _, sync::Arc}; + +thread_local! { + /// Level and game events recorded while a fixture case runs. + static LOG: RefCell>> = const { RefCell::new(None) }; +} + +/// Record a line if a fixture case is running. +pub(super) fn record(line: impl FnOnce() -> String) { + LOG.with(|log| { + if let Some(lines) = log.borrow_mut().as_mut() { + lines.push(line()); + } + }); +} +/// `Level.levelEvent` lines for the level events the behaviour library reported. +pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) { + for event in events { + if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = event { + record(|| format!("L {id} {},{},{} {data}", pos.x, pos.y, pos.z)); + } + } +} + +fn num(v: f64) -> String { + format!("{v:.6}") +} +fn floor_pos(p: [f64; 3]) -> String { + format!( + "{},{},{}", + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32 + ) +} + +/// The targets a case put in front of the dispenser. +enum Target { + Mob(u32), + Stand(u32), +} + +impl Game<'_> { + /// Run every case of `spec` ("CASES,OUTPUT") and write the results. + pub(super) fn dispense_fixture(&mut self, spec: &str) -> Result<()> { + let (input, output) = spec + .split_once(',') + .ok_or("HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT")?; + // Saplings and feature placers grow from the live feature registry. + self.install_live_features(); + let text = std::fs::read_to_string(input)?; + let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); + for (index, line) in text.lines().enumerate() { + let case: Value = serde_json::from_str(line)?; + writeln!(out, "case {index}")?; + match self.dispense_case(&case) { + Ok(lines) => { + for l in lines { + writeln!(out, "{l}")?; + } + } + Err(e) => writeln!(out, "failed {e}")?, + } + } + LOG.with(|log| *log.borrow_mut() = None); + Ok(()) + } + + fn fixture_reset(&mut self, seed: i64) { + self.world = World::new(self.res.facts.air, seed); + // The oracle level is plains everywhere (bone meal's flowers, freezing). + let plains = u32::from(self.res.biomes.id("minecraft:plains")); + for cx in -2..=2 { + for cz in -2..=2 { + let mut chunk = Chunk::empty(cx, cz); + for section in &mut chunk.sections { + Arc::make_mut(section).biomes = horizon_core::paletted::PalettedContainer::new( + horizon_client::chunk::BIOME_STRATEGY, + plains, + ); + } + self.world.chunks.insert((cx, cz), Arc::new(chunk)); + } + } + self.block_ticks = Ticks::new(0); + self.tick_chunks.clear(); + self.sync_tick_chunks(); + self.mobs.clear(); + self.dropped.clear(); + self.creatures.projectiles.clear(); + self.tnts.clear(); + self.boats.clear(); + self.carts.clear(); + self.armor_stands.clear(); + self.rockets.clear(); + self.potions.clear_thrown(); + self.level_events.clear(); + self.orbs.clear(); + self.falling.clear(); + self.ui.rules = Default::default(); + // The oracle level plays on normal difficulty. + self.ui.difficulty = 2; + // The oracle level has world seed 0 and fresh random sequences. + self.level.seed = 0; + self.rand_sequences = Default::default(); + } + + fn dispense_case(&mut self, case: &Value) -> Result> { + let seed = case["seed"].as_i64().unwrap_or(0); + self.fixture_reset(seed); + // The oracle level answers one sky and one block light everywhere. + let light = case["light"].as_array(); + let level = |i: usize, default: i64| { + light + .and_then(|l| l.get(i)) + .and_then(Value::as_i64) + .unwrap_or(default) as u8 + }; + let packed = (level(0, 15) << 4) | level(1, 0); + for chunk in self.world.chunks.values_mut() { + for section in &mut Arc::make_mut(chunk).sections { + Arc::make_mut(section).light = horizon_client::chunk::Light::Uniform(packed); + } + } + self.world.game_time = case["time"].as_i64().unwrap_or(0); + // The oracle level's clock stands at day time 6000. + self.world.day_time = 6000; + if let Some(rules) = case["rules"].as_object() { + for (name, value) in rules { + if let Some(b) = value.as_bool() { + self.ui.rules.set(name, RuleValue::Bool(b)); + } + } + } + let mut before: HashMap<(i32, i32, i32), u32> = HashMap::new(); + for cell in case["cells"].as_array().into_iter().flatten() { + let p = ( + cell[0].as_i64().unwrap_or(0) as i32, + cell[1].as_i64().unwrap_or(0) as i32, + cell[2].as_i64().unwrap_or(0) as i32, + ); + let state = BlockStateId(cell[3].as_u64().unwrap_or(0) as u32); + self.world.set(p.0, p.1, p.2, state)?; + before.insert(p, state.0); + if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + self.world.block_entities.insert(p, entity); + } + } + for item in case["items"].as_array().into_iter().flatten() { + let p = ( + item[0].as_i64().unwrap_or(0) as i32, + item[1].as_i64().unwrap_or(0) as i32, + item[2].as_i64().unwrap_or(0) as i32, + ); + let slot = item[3].as_u64().unwrap_or(0) as usize; + let stack = parse_stack(item[4].as_str().unwrap_or("-"))?; + if let Some(cell) = self + .world + .block_entities + .get_mut(&p) + .and_then(|e| e.slots_mut().get_mut(slot)) + { + *cell = stack; + } + } + let mut targets = Vec::new(); + for e in case["entities"].as_array().into_iter().flatten() { + targets.push(self.fixture_target(e)?); + } + // Leashable.setLeashedTo: a lead from a target to an earlier one. + for (e, t) in case["entities"] + .as_array() + .into_iter() + .flatten() + .zip(&targets) + { + let (Some(holder), Target::Mob(id)) = (e["leash"].as_u64(), t) else { + continue; + }; + let holder = match targets.get(holder as usize) { + Some(Target::Mob(h)) => horizon_client::mobs::leash::Holder::Mob(*h), + _ => continue, + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id) { + m.extra.leash = Some(holder); + } + } + // Creating the targets must not move the stream the dispenser draws from. + self.world.random = LegacyRandom::new(seed); + self.world.block_log = Some(Vec::new()); + self.audio.capture = Some(Vec::new()); + LOG.with(|log| *log.borrow_mut() = Some(Vec::new())); + let old_mobs: Vec = self.mobs.iter().map(|m| m.id).collect(); + let old_stands: Vec = self.armor_stands.iter().map(|s| s.id).collect(); + + let pos = &case["pos"]; + let origin = BlockPos::new( + pos[0].as_i64().unwrap_or(0) as i32, + pos[1].as_i64().unwrap_or(0) as i32, + pos[2].as_i64().unwrap_or(0) as i32, + ); + let state = self.world.block(origin.x, origin.y, origin.z); + self.dispense_from(origin, state)?; + + let mut out = Vec::new(); + let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default(); + changed.sort_unstable(); + changed.dedup(); + for p in changed { + let now = self.world.block(p.0, p.1, p.2).0; + if before.get(&p).copied().unwrap_or(self.res.facts.air.0) != now { + out.push(format!("set {},{},{} {now}", p.0, p.1, p.2)); + } + } + let mut containers: Vec<_> = self.world.block_entities.keys().copied().collect(); + containers.sort_unstable(); + for p in containers { + let entity = &self.world.block_entities[&p]; + for (i, slot) in entity.slots().iter().enumerate() { + if let Some(stack) = slot { + out.push(format!( + "inv {},{},{} {i} {}", + p.0, + p.1, + p.2, + canon_stack(Some(stack)) + )); + } + } + } + self.fixture_entities(&old_mobs, &old_stands, &mut out); + for (i, t) in targets.iter().enumerate() { + out.push(self.fixture_describe(i, t)); + } + let log = LOG.with(|log| log.borrow_mut().take()).unwrap_or_default(); + out.extend(log); + for (sound, at, _, _) in self.audio.capture.take().unwrap_or_default() { + out.push(format!("S {} {sound}", floor_pos(at))); + } + out.push(format!("rng {}", self.world.random.next_long())); + Ok(out) + } + + /// `EntityType.create` and `snapTo` for one target: no spawn finalization. + fn fixture_target(&mut self, e: &Value) -> Result { + let kind = e["type"].as_str().unwrap_or("minecraft:pig"); + let p = &e["pos"]; + let at = horizon_core::geometry::Vec3::new( + p[0].as_f64().unwrap_or(0.0), + p[1].as_f64().unwrap_or(0.0), + p[2].as_f64().unwrap_or(0.0), + ); + let yaw = e["yaw"].as_f64().unwrap_or(0.0) as f32; + self.next_entity += 1; + let id = self.next_entity; + if kind == "minecraft:armor_stand" { + self.armor_stands + .push(horizon_client::entities::ArmorStand::new(id, at, yaw)); + return Ok(Target::Stand(id)); + } + let t = self + .res + .mob_types + .get(kind) + .cloned() + .ok_or_else(|| format!("no mob type {kind}"))?; + let mut mob = Mob::new(id, t, at, yaw); + // EntityType.create equips nothing (that is finalizeSpawn's job). + for slot in [ + &mut mob.extra.main_hand, + &mut mob.extra.off_hand, + &mut mob.extra.head, + &mut mob.extra.chest, + &mut mob.extra.legs, + &mut mob.extra.feet, + ] { + *slot = None; + } + let s = mob.species(); + let flag = |name: &str| e[name].as_bool().unwrap_or(false); + let ageable = !matches!( + s, + Species::Zombie | Species::Skeleton | Species::Bogged | Species::SnowGolem + ); + if flag("baby") && ageable { + mob.extra.age = -24000; + } + let tamable = + body_in_head(s) || matches!(s, Species::Cat | Species::Parrot | Species::Ocelot); + if flag("tame") && tamable { + mob.extra.tame = true; + } + if flag("sheared") && matches!(s, Species::Sheep | Species::Bogged | Species::SnowGolem) { + mob.extra.sheared = true; + } + if flag("chest") + && matches!( + s, + Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama + ) + { + mob.extra.chested = true; + } + if flag("loot") { + mob.extra.pick_up_loot = true; + } + if flag("brown") && s == Species::Mooshroom { + mob.extra.variant = 1; + } + for (slot, snbt) in e["equip"].as_object().into_iter().flatten() { + if let (Some(slot), Some(stack)) = ( + Slot::from_name(slot), + parse_stack(snbt.as_str().unwrap_or("-"))?, + ) { + mob_set_slot(&mut mob, slot, stack); + } + } + self.mobs.push(mob); + Ok(Target::Mob(id)) + } + + /// `T` lines: removal, equipment by `EquipmentSlot`, shearing readiness, chests. + fn fixture_describe(&self, index: usize, target: &Target) -> String { + let mut line = format!("T {index} "); + match *target { + Target::Stand(id) => { + line.push_str("minecraft:armor_stand"); + let Some(stand) = self.armor_stands.iter().find(|s| s.id == id) else { + line.push_str(" removed"); + return line; + }; + for (slot, name) in [ + (0, "mainhand"), + (1, "offhand"), + (2, "feet"), + (3, "legs"), + (4, "chest"), + (5, "head"), + ] { + if let Some(s) = &stand.equipment[slot] { + let _ = write!(line, " {name}={}x{}", s.item, s.count); + } + } + } + Target::Mob(id) => { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return line + "removed"; + }; + line.push_str(&m.kind.id); + if m.removed || !m.alive() { + line.push_str(" removed"); + } + let s = m.species(); + let x = &m.extra; + for (slot, name) in [ + (Slot::MainHand, "mainhand"), + (Slot::OffHand, "offhand"), + (Slot::Feet, "feet"), + (Slot::Legs, "legs"), + (Slot::Chest, "chest"), + (Slot::Head, "head"), + (Slot::Body, "body"), + (Slot::Saddle, "saddle"), + ] { + if let Some(item) = mob_slot_item(m, slot) { + let _ = write!(line, " {name}={item}x1"); + } + } + let ready = match s { + Species::Sheep => Some(!x.sheared && !m.is_baby()), + Species::Mooshroom => Some(!m.is_baby()), + Species::Bogged => Some(!x.sheared), + Species::SnowGolem => Some(!x.sheared), + _ => None, + }; + if let Some(r) = ready { + line.push_str(if r { " ready" } else { " unready" }); + } + if x.chested + && matches!( + s, + Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama + ) + { + line.push_str(" chest"); + } + if x.leash.is_some() { + line.push_str(" leashed"); + } + } + } + line + } + + /// `N` lines for every entity the dispenser added. + fn fixture_entities(&self, old_mobs: &[u32], old_stands: &[u32], out: &mut Vec) { + let line = |kind: &str, p: [f64; 3], v: [f64; 3], extra: &str| { + let mut l = format!( + "N {kind} {} {} {} {} {} {}", + num(p[0]), + num(p[1]), + num(p[2]), + num(v[0]), + num(v[1]), + num(v[2]) + ); + if !extra.is_empty() { + l.push(' '); + l.push_str(extra); + } + l + }; + for m in self.mobs.iter().filter(|m| !old_mobs.contains(&m.id)) { + let (p, v) = (m.position, m.velocity); + out.push(line(&m.kind.id, [p.x, p.y, p.z], [v.x, v.y, v.z], "")); + } + for s in self + .armor_stands + .iter() + .filter(|s| !old_stands.contains(&s.id)) + { + let (p, v) = (s.position, s.velocity); + out.push(line( + "minecraft:armor_stand", + [p.x, p.y, p.z], + [v.x, v.y, v.z], + "", + )); + } + for d in &self.dropped { + let (p, v) = (d.position, d.velocity); + out.push(line( + "minecraft:item", + [p.x, p.y, p.z], + [v.x, v.y, v.z], + &canon_stack(Some(&d.stack)), + )); + } + for shot in &self.creatures.projectiles { + let kind = match &shot.kind { + ProjectileKind::Arrow { + effect: Some(("minecraft:glowing", 200)), + .. + } => "minecraft:spectral_arrow", + ProjectileKind::Arrow { .. } => "minecraft:arrow", + ProjectileKind::Snowball => "minecraft:snowball", + ProjectileKind::Egg => "minecraft:egg", + ProjectileKind::SmallFireball => "minecraft:small_fireball", + ProjectileKind::WindCharge => "minecraft:wind_charge", + _ => "minecraft:unknown_projectile", + }; + let (p, v) = (shot.position, shot.velocity); + out.push(line(kind, [p.x, p.y, p.z], [v.x, v.y, v.z], "")); + } + for (kind, p, v) in self.potions.thrown_entities() { + out.push(line(kind, [p.x, p.y, p.z], [v.x, v.y, v.z], "")); + } + for (p, v) in self.rockets.iter().map(|r| r.motion()) { + out.push(line( + "minecraft:firework_rocket", + [p.x, p.y, p.z], + [v.x, v.y, v.z], + "", + )); + } + for t in &self.tnts { + let (p, v) = (t.position, t.velocity); + out.push(line( + "minecraft:tnt", + [p.x, p.y, p.z], + [v.x, v.y, v.z], + &format!("fuse={}", t.fuse), + )); + } + for b in &self.boats { + let kind = b.entity_type(); + let (p, v) = (b.position, b.velocity); + out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], "")); + } + for c in &self.carts { + let (p, v) = (c.position, c.velocity); + out.push(line(c.kind.id(), [p.x, p.y, p.z], [v.x, v.y, v.z], "")); + } + } +} diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index f8754bbb1..f6a7e5a58 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -9,20 +9,21 @@ use horizon_client::{ collisions::SceneCollisions, containers::BlockEntity, items::ItemStack, - mobs::{MobEvent, SpawnSetup, Species}, + mobs::{Mob, Species, sulfur_cube}, particles::{ParticleOptions, ParticleType}, projectiles::{Projectile, ProjectileKind}, }; use horizon_core::{ geometry::{Aabb, Direction, Vec3}, position::BlockPos, - random::RandomSource, + random::{LegacyRandom, RandomSource}, }; use horizon_world::{ fluid::FluidKind, level::{BucketContent, PlaceContext, PlaceOutcome}, registry::BlockStateId, }; +use std::sync::Arc; type Pos = (i32, i32, i32); @@ -89,13 +90,222 @@ fn shrink(mut stack: ItemStack) -> Option { /// A dispenser's answer: the slot's new content and the level event played. type Dispensed = (Option, i32); +thread_local! { + /// `OptionalDispenseItemBehavior.success` of the registered behaviours + /// that leave it unset on some paths (brush, TNT, honeycomb, chest). + /// Vanilla keeps one behaviour instance per item for the whole run, so + /// there the flag carries over from that item's previous dispense. + static SUCCESS: std::cell::RefCell> = + std::cell::RefCell::new(std::collections::HashMap::new()); +} +fn set_success(behaviour: &'static str, success: bool) { + SUCCESS.with(|s| s.borrow_mut().insert(behaviour, success)); +} +/// The level event `OptionalDispenseItemBehavior.playSound` plays for the flag. +fn optional_event(behaviour: &'static str) -> i32 { + if SUCCESS.with(|s| s.borrow().get(behaviour).copied().unwrap_or(true)) { + CLICK + } else { + FAIL + } +} + /// Entities `getEntitiesOfClass(.., AABB(pos))` can find. +#[derive(Clone, Copy)] enum Target { Player, Mob(usize), Stand(usize), } +/// `RandomSource.create()`: the unseeded random an entity owns +/// (`RandomSupport.generateUniqueSeed`). Draws of an entity's own random never +/// touch the level's stream. +pub(super) fn entity_random() -> LegacyRandom { + use std::sync::atomic::{AtomicI64, Ordering}; + static UNIQUIFIER: AtomicI64 = AtomicI64::new(8_682_522_807_148_012); + const STEP: i64 = 1_181_783_497_276_652_981; + // seedUniquifier.updateAndGet(s -> s * STEP) + let mut current = UNIQUIFIER.load(Ordering::Relaxed); + let seed = loop { + let next = current.wrapping_mul(STEP); + match UNIQUIFIER.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) + { + Ok(_) => break next, + Err(actual) => current = actual, + } + }; + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64); + LegacyRandom::new(seed ^ nanos) +} +/// `new ItemEntity(level, x, y, z, stack)`'s motion, from the item's own random. +pub(super) fn new_item_motion() -> [f64; 3] { + let mut r = entity_random(); + let x = r.next_double() * 0.2 - 0.1; + let z = r.next_double() * 0.2 - 0.1; + [x, 0.2, z] +} + +/// `EquipmentSlot`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Slot { + MainHand, + OffHand, + Feet, + Legs, + Chest, + Head, + Body, + Saddle, +} +impl Slot { + pub(super) fn from_name(name: &str) -> Option { + Some(match name { + "mainhand" => Self::MainHand, + "offhand" => Self::OffHand, + "feet" => Self::Feet, + "legs" => Self::Legs, + "chest" => Self::Chest, + "head" => Self::Head, + "body" => Self::Body, + "saddle" => Self::Saddle, + _ => return None, + }) + } + /// The player's armour array index (head, chest, legs, feet). + fn armor_index(self) -> Option { + match self { + Self::Head => Some(0), + Self::Chest => Some(1), + Self::Legs => Some(2), + Self::Feet => Some(3), + _ => None, + } + } + /// `ArmorStand` equipment index (mainhand, offhand, feet, legs, chest, head). + fn stand_index(self) -> Option { + match self { + Self::MainHand => Some(0), + Self::OffHand => Some(1), + Self::Feet => Some(2), + Self::Legs => Some(3), + Self::Chest => Some(4), + Self::Head => Some(5), + _ => None, + } + } +} + +fn equine(s: Species) -> bool { + matches!( + s, + Species::Horse + | Species::Donkey + | Species::Mule + | Species::SkeletonHorse + | Species::ZombieHorse + | Species::Camel + | Species::CamelHusk + | Species::Llama + | Species::TraderLlama + ) +} +/// Mobs whose body slot Horizon keeps in `extra.head` (no helmet slot is drawn). +pub(super) fn body_in_head(s: Species) -> bool { + equine(s) + || matches!(s, Species::Wolf | Species::HappyGhast | Species::SulfurCube) + || horizon_client::mobs::nautilus::is_nautilus(s) +} +/// What a mob holds in a slot. +pub(super) fn mob_slot_item(m: &Mob, slot: Slot) -> Option> { + let x = &m.extra; + let body = body_in_head(m.species()); + match slot { + Slot::MainHand => x.main_hand.clone(), + Slot::OffHand => x.off_hand.clone(), + Slot::Feet => x.feet.clone(), + Slot::Legs => x.legs.clone(), + Slot::Chest => x.chest.clone(), + Slot::Head => x.head.clone().filter(|_| !body), + Slot::Body => x.head.clone().filter(|_| body), + Slot::Saddle => m.saddle_item().map(|s| s.item), + } +} +/// `LivingEntity.canUseSlot` and its overrides. +fn mob_can_use_slot(m: &Mob, slot: Slot) -> bool { + let s = m.species(); + let grown = m.alive() && !m.is_baby(); + match s { + Species::Pig | Species::Strider if slot == Slot::Saddle => grown, + Species::Horse + | Species::SkeletonHorse + | Species::ZombieHorse + | Species::Llama + | Species::TraderLlama => true, + _ if equine(s) && slot == Slot::Saddle => grown && m.extra.tame, + _ if horizon_client::mobs::nautilus::is_nautilus(s) + && matches!(slot, Slot::Saddle | Slot::Body) => + { + grown && m.extra.tame + } + Species::SulfurCube | Species::HappyGhast if slot == Slot::Body => grown, + _ => true, + } +} +/// `Mob.canDispenserEquipIntoSlot` and its overrides. +fn mob_can_dispenser_equip(m: &Mob, slot: Slot) -> bool { + let s = m.species(); + let loot = m.extra.pick_up_loot; + match s { + Species::Pig | Species::Strider => slot == Slot::Saddle || loot, + _ if equine(s) => matches!(slot, Slot::Body | Slot::Saddle) && m.extra.tame || loot, + _ if horizon_client::mobs::nautilus::is_nautilus(s) => { + matches!(slot, Slot::Body | Slot::Saddle) || loot + } + Species::SulfurCube | Species::HappyGhast => slot == Slot::Body, + Species::Dolphin | Species::Panda | Species::Fox => slot == Slot::MainHand && loot, + Species::Allay => false, + _ => loot, + } +} +/// `getEquipSound`: the saddle overrides of pigs, striders, horses, camels and nautili. +fn equip_sound(m: &Mob, slot: Slot, default: Option) -> Option { + if slot != Slot::Saddle { + return default; + } + let s = m.species(); + Some(match s { + Species::Pig => "minecraft:entity.pig.saddle".into(), + Species::Strider => "minecraft:entity.strider.saddle".into(), + Species::Camel => "minecraft:entity.camel.saddle".into(), + Species::CamelHusk => "minecraft:entity.camel_husk.saddle".into(), + _ if equine(s) => "minecraft:entity.horse.saddle".into(), + _ if horizon_client::mobs::nautilus::is_nautilus(s) => { + if m.fluids.eye_in_water { + "minecraft:item.nautilus_saddle_underwater_equip".into() + } else { + "minecraft:item.nautilus_saddle_equip".into() + } + } + _ => return default, + }) +} +pub(super) fn mob_set_slot(m: &mut Mob, slot: Slot, stack: ItemStack) { + let item: Arc = stack.item.clone(); + let x = &mut m.extra; + match slot { + Slot::MainHand => x.main_hand = Some(item), + Slot::OffHand => x.off_hand = Some(item), + Slot::Feet => x.feet = Some(item), + Slot::Legs => x.legs = Some(item), + Slot::Chest => x.chest = Some(item), + Slot::Head | Slot::Body => x.head = Some(item), + Slot::Saddle => m.set_saddle(Some(stack)), + } +} + impl Game<'_> { fn prop(&self, state: BlockStateId, key: &str) -> Option { self.res @@ -149,6 +359,7 @@ impl Game<'_> { /// The dispenser level events: 1000 click, 1001 fail, 1002 launch, 1004 /// firework shoot, 1018 blaze shoot and 2000 smoke shot out of the front. pub(super) fn dispenser_event(&mut self, id: i32, pos: Pos, data: i32) { + super::dispense_fixture::record(|| format!("L {id} {},{},{} {data}", pos.0, pos.1, pos.2)); let c = Self::center(pos); match id { 1000 => self @@ -163,12 +374,19 @@ impl Game<'_> { 1004 => self .audio .play("minecraft:entity.firework_rocket.shoot", Some(c), 1.0, 1.2), + // LevelEventHandler runs on the client: its pitch draws come from + // the client level's random, never the server stream. 1018 => { - let r = &mut self.world.random; + let r = self.particles.random(); let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0; self.audio .play("minecraft:entity.blaze.shoot", Some(c), 2.0, pitch); } + 1051 => { + let pitch = 0.4 / (self.particles.random().next_float() * 0.4 + 0.8); + self.audio + .play("minecraft:entity.wind_charge.throw", Some(c), 0.5, pitch); + } 2000 => { let s = match data { 0 => [0, -1, 0], @@ -237,8 +455,6 @@ impl Game<'_> { let mut at = [p.x, p.y, p.z]; at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 }; let r = &mut self.world.random; - // new ItemEntity(level, x, y, z, stack): its default motion draws first. - let _ = (r.next_double(), r.next_double()); let pow = r.next_double() * 0.1 + 0.2; let spread = 0.017_227_5 * f64::from(accuracy); let v = [ @@ -361,7 +577,8 @@ impl Game<'_> { | "minecraft:splash_potion" | "minecraft:lingering_potion" | "minecraft:firework_rocket" - | "minecraft:fire_charge" => self.dispense_projectile(pos, facing, stack), + | "minecraft:fire_charge" + | "minecraft:wind_charge" => self.dispense_projectile(pos, facing, stack), "minecraft:armor_stand" => self.dispense_armor_stand(pos, facing, stack), "minecraft:chest" => self.dispense_chest(pos, facing, stack), "minecraft:lava_bucket" @@ -372,7 +589,8 @@ impl Game<'_> { | "minecraft:pufferfish_bucket" | "minecraft:tropical_fish_bucket" | "minecraft:axolotl_bucket" - | "minecraft:tadpole_bucket" => self.dispense_filled_bucket(pos, facing, stack)?, + | "minecraft:tadpole_bucket" + | "minecraft:sulfur_cube_bucket" => self.dispense_filled_bucket(pos, facing, stack)?, "minecraft:bucket" => self.dispense_empty_bucket(pos, facing, stack)?, "minecraft:flint_and_steel" => self.dispense_flint_and_steel(pos, facing, stack)?, "minecraft:bone_meal" => self.dispense_bone_meal(pos, facing, stack)?, @@ -386,11 +604,13 @@ impl Game<'_> { "minecraft:honeycomb" => self.dispense_honeycomb(pos, facing, stack)?, "minecraft:potion" => self.dispense_potion(pos, facing, stack)?, _ if item.ends_with("shulker_box") => self.dispense_shulker_box(pos, facing, stack)?, - _ if super::boats::boat_wood(&item).is_some() => self.dispense_boat(pos, facing, stack), + _ if super::boats::any_boat_wood(&item).is_some() => { + self.dispense_boat(pos, facing, stack) + } _ if super::minecarts::CartKind::from_id(&item).is_some() => { self.dispense_minecart(pos, facing, stack) } - _ => self.dispense_default_method(pos, facing, stack), + _ => self.dispense_default_method(pos, facing, stack)?, }; self.dispenser_event(event, pos, 0); self.dispenser_event(2000, pos, data_value(facing)); @@ -402,7 +622,7 @@ impl Game<'_> { pos: Pos, facing: Direction, stack: ItemStack, - ) -> Dispensed { + ) -> Result { let equippable = self .res .items @@ -411,35 +631,51 @@ impl Game<'_> { if equippable { let mut stack = stack; if self.dispense_equipment(pos, facing, &mut stack) { - return (Some(stack).filter(|s| s.count > 0), CLICK); + return Ok((Some(stack).filter(|s| s.count > 0), CLICK)); } - return (self.default_execute(pos, facing, stack), CLICK); + return Ok((self.default_execute(pos, facing, stack), CLICK)); + } + let swallowable = self + .res + .items + .item_tags + .get("minecraft:sulfur_cube_swallowable") + .is_some_and(|t| t.contains(&*stack.item)); + if swallowable { + let front = offset(pos, facing); + if self.sulfur_cube_swallow(front, &stack) { + return Ok((shrink(stack), CLICK)); + } + return Ok((self.default_execute(pos, facing, stack), CLICK)); } if stack.item.ends_with("_spawn_egg") { return self.dispense_spawn_egg(pos, facing, stack); } - (self.default_execute(pos, facing, stack), CLICK) + Ok((self.default_execute(pos, facing, stack), CLICK)) } // ---- entities ---- - /// Entities whose box overlaps the block at `p`. + /// Entities whose box overlaps the block at `p`, in the order the level + /// added them (an entity section keeps insertion order; ids grow with it). fn targets_at(&self, p: Pos) -> Vec { let block = block_box(p); - let mut out: Vec = self + let mut found: Vec<(u32, Target)> = self .mobs .iter() .enumerate() - .filter(|(_, m)| m.alive() && overlaps(m.bounds(), block)) - .map(|(i, _)| Target::Mob(i)) + .filter(|(_, m)| !m.removed && overlaps(m.bounds(), block)) + .map(|(i, m)| (m.id, Target::Mob(i))) .collect(); - out.extend( + found.extend( self.armor_stands .iter() .enumerate() .filter(|(_, s)| overlaps(s.bounds(), block)) - .map(|(i, _)| Target::Stand(i)), + .map(|(i, s)| (s.id, Target::Stand(i))), ); + found.sort_by_key(|(id, _)| *id); + let mut out: Vec = found.into_iter().map(|(_, t)| t).collect(); if let Some(v) = self.player_view() && v.alive && !self.spectator() @@ -449,23 +685,48 @@ impl Game<'_> { } out } - /// The Y offset `EntityType.getYOffset` finds for a box set down into a block. + /// `EntityType.getYOffset(level, pos, false, box)`: the entity box set on + /// top of the block (`setPos(x + 0.5, y + 1, z + 0.5)`) falls one block + /// against the collision shapes overlapping that block alone. fn drop_offset(&self, width: f64, height: f64, p: Pos) -> f64 { + use horizon_world::{ + block_collision_scan::BlockCollisionScan, collision_context::CollisionContext, + }; let h = width / 2.0; let (x, z) = (f64::from(p.0) + 0.5, f64::from(p.2) + 0.5); let y = f64::from(p.1) + 1.0; - let bounds = Aabb::new( + let entity = Aabb::new( Vec3::new(x - h, y, z - h), Vec3::new(x + h, y + height, z + h), ); + let cell = Aabb::new( + Vec3::new(f64::from(p.0), f64::from(p.1), f64::from(p.2)), + Vec3::new( + f64::from(p.0) + 1.0, + f64::from(p.1) + 1.0, + f64::from(p.2) + 1.0, + ), + ); let mut scene = SceneCollisions { world: &self.world, binding: self.collision, }; - match scene.resolve(bounds, Vec3::new(0.0, -1.0, 0.0), 0.0, false) { - Ok(moved) => 1.0 + moved.y, - Err(_) => 0.0, + let mut amount = -1.0; + // Level.getCollisions(null, aabb): CollisionContext.empty(). + if let Ok(scan) = BlockCollisionScan::new( + &mut scene, + CollisionContext::empty(false), + cell, + false, + 1_000_000, + ) { + for hit in scan.flatten() { + amount = hit + .shape + .collide(horizon_core::geometry::Axis::Y, entity, amount); + } } + 1.0 + amount } /// `EntityType.spawn(.., pos, reason, tryMoveDown, false)` for a mob. fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option { @@ -485,137 +746,137 @@ impl Game<'_> { f64::from(p.1) + y_off, f64::from(p.2) + 0.5, ]; - self.spawn_mob(&name, at, true) + let id = self.spawn_mob(&name, at, true)?; + // finalizeSpawn's riders (chicken jockeys, spider jockeys...) come + // with a dispensed mob as with any spawn that is not natural. + self.spawn_jockeys(id, false); + Some(id) } - /// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first entity in - /// front that can wear the item gets one of it. - fn dispense_equipment(&mut self, pos: Pos, _facing: Direction, stack: &mut ItemStack) -> bool { + /// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first living + /// entity in front that `canEquipWithDispenser` gets one of the item. + fn dispense_equipment(&mut self, pos: Pos, facing: Direction, stack: &mut ItemStack) -> bool { let Some(info) = self.res.items.get(&stack.item) else { return false; }; - let (Some(slot), true) = (info.equip_slot.clone(), info.equip_dispensable) else { + let (Some(slot), true) = ( + info.equip_slot.as_deref().and_then(Slot::from_name), + info.equip_dispensable, + ) else { return false; }; let allowed = info.equip_allowed.clone(); - let sound = info.equip_sound.clone(); - let front = offset(pos, _facing); + // Equippable.equipSound defaults to the generic armour sound. + let sound = info + .equip_sound + .clone() + .or_else(|| Some("minecraft:item.armor.equip_generic".into())); + let front = offset(pos, facing); let one = ItemStack { count: 1, ..stack.clone() }; - let armor_index = match slot.as_str() { - "head" => Some(0), - "chest" => Some(1), - "legs" => Some(2), - "feet" => Some(3), - _ => None, + let allows = |id: &str| allowed.as_ref().is_none_or(|a| a.contains(id)); + // LivingEntity.canEquipWithDispenser: alive, the slot usable, the + // item's allowed entities, the slot empty and the dispenser rule. + let target = self.targets_at(front).into_iter().find(|t| match *t { + Target::Player => slot + .armor_index() + .is_some_and(|i| allows("minecraft:player") && self.armor[i].is_none()), + Target::Stand(i) => slot.stand_index().is_some_and(|s| { + allows("minecraft:armor_stand") && self.armor_stands[i].equipment[s].is_none() + }), + Target::Mob(i) => { + let m = &self.mobs[i]; + m.alive() + && mob_can_use_slot(m, slot) + && allows(&m.kind.id) + && mob_slot_item(m, slot).is_none() + && mob_can_dispenser_equip(m, slot) + } + }); + let Some(target) = target else { + return false; }; - let id_allowed = |id: &str| allowed.as_ref().is_none_or(|a| a.contains(id)); - let item: std::sync::Arc = stack.item.clone(); - for target in self.targets_at(front) { - let at = match target { - Target::Player => { - // The player wears armour only. - let Some(i) = armor_index else { continue }; - if !id_allowed("minecraft:player") || self.armor[i].is_some() { - continue; - } - self.armor[i] = Some(one.clone()); - self.apply_equipment(); - self.player_view().map(|v| v.position) + stack.count -= 1; + // setItemSlot: onEquipItem plays the equip sound and the equip event. + let (at, sound) = match target { + Target::Player => { + if let Some(i) = slot.armor_index() { + self.armor[i] = Some(one); } - Target::Stand(i) => { - let Some(ai) = armor_index else { continue }; - if !id_allowed("minecraft:armor_stand") { - continue; - } - // ArmorStand equipment: mainhand, offhand, feet, legs, chest, head. - let index = 5 - ai; - let stand = &mut self.armor_stands[i]; - if stand.equipment[index].is_some() { - continue; - } - stand.equipment[index] = Some(one.clone()); - Some(stand.position) + self.apply_equipment(); + (self.player_view().map(|v| v.position), sound) + } + Target::Stand(i) => { + let stand = &mut self.armor_stands[i]; + if let Some(s) = slot.stand_index() { + stand.equipment[s] = Some(one); } - Target::Mob(i) => { - let m = &mut self.mobs[i]; - if !id_allowed(&m.kind.id) { - continue; - } - let species = m.species(); - let tamed = m.extra.tame; - let equine = matches!( - species, - Species::Horse - | Species::Donkey - | Species::Mule - | Species::SkeletonHorse - | Species::ZombieHorse - | Species::Camel - | Species::CamelHusk - ); - // AbstractNautilus.canDispenserEquipIntoSlot: saddle and - // body on a tame adult. - let nautilus = horizon_client::mobs::nautilus::is_nautilus(species) - && tamed - && !m.is_baby(); - let slot_free = match (slot.as_str(), armor_index) { - (_, Some(0)) => m.extra.head.is_none(), - (_, Some(1)) => m.extra.chest.is_none(), - (_, Some(2)) => m.extra.legs.is_none(), - (_, Some(3)) => m.extra.feet.is_none(), - ("saddle", _) => !m.extra.saddled, - ("body", _) => { - (species == Species::Horse - || nautilus && item.ends_with("_nautilus_armor")) - && m.extra.head.is_none() - } - _ => false, - }; - // Mob.canDispenserEquipIntoSlot and the overrides. - let saddle_ok = slot == "saddle" - && (matches!(species, Species::Pig | Species::Strider) - || equine && tamed - || nautilus); - let body_ok = slot == "body" && (equine && tamed || nautilus); - if !slot_free || !(m.extra.pick_up_loot || saddle_ok || body_ok) { - continue; - } - if species == Species::Strider && slot == "saddle" && m.is_baby() { - continue; - } - match (slot.as_str(), armor_index) { - (_, Some(0)) => m.extra.head = Some(item.clone()), - (_, Some(1)) => m.extra.chest = Some(item.clone()), - (_, Some(2)) => m.extra.legs = Some(item.clone()), - (_, Some(3)) => m.extra.feet = Some(item.clone()), - ("saddle", _) => m.set_saddle(Some(one.clone())), - _ => m.extra.head = Some(item.clone()), - } - // setGuaranteedDrop / setPersistenceRequired. - m.persistent = true; - Some(m.position) - } - }; - if let (Some(sound), Some(at)) = (sound, at) { + (Some(stand.position), sound) + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + mob_set_slot(m, slot, one); + // setGuaranteedDrop / setPersistenceRequired. + m.persistent = true; + let sound = if m.silent { + None + } else { + equip_sound(m, slot, sound) + }; + (Some(m.position), sound) + } + }; + if let Some(at) = at { + if let Some(sound) = sound { self.audio.play(&sound, Some([at.x, at.y, at.z]), 1.0, 1.0); } - stack.count -= 1; - return true; + let who = match target { + Target::Player => Some(horizon_client::mobs::Who::Player), + Target::Mob(i) => Some(horizon_client::mobs::Who::Mob(self.mobs[i].id)), + Target::Stand(_) => None, + }; + let ctx = self.who_context(who, None); + self.post_game_event("minecraft:equip", [at.x, at.y, at.z], ctx); } - false + true } - fn dispense_spawn_egg(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + /// After `EntityType.spawn` / `MobBucketItem.spawn`: `mob.playAmbientSound()`. + fn mob_ambient(&mut self, id: u32) -> Result<()> { + let Some(i) = self.mobs.iter().position(|m| m.id == id) else { + return Ok(()); + }; + let mut m = self.mobs.remove(i); + let mut events = Vec::new(); + { + let w = self.mob_world_base(&[]); + horizon_client::mobs::ai::ambient_sound(&mut m, &w, &mut events); + } + self.mobs.insert(i, m); + self.handle_mob_events(events) + } + /// A mob a bucket emptied: `setFromBucket` keeps it, then it calls out. + fn mob_placed(&mut self, id: u32) -> Result<()> { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.persistent = true; + } + self.mob_ambient(id) + } + fn dispense_spawn_egg( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { let kind = stack.item.trim_end_matches("_spawn_egg").to_owned(); let front = offset(pos, facing); - if self - .spawn_mob_at(&kind, front, facing != Direction::Up) - .is_none() - { - return (Some(stack), CLICK); - } - (shrink(stack), CLICK) + let Some(id) = self.spawn_mob_at(&kind, front, facing != Direction::Up) else { + return Ok((Some(stack), CLICK)); + }; + self.mob_ambient(id)?; + // SpawnEggItemBehavior: the entity was placed by the dispenser. + self.post_block_game_event("minecraft:entity_place", [pos.0, pos.1, pos.2], None, None); + Ok((shrink(stack), CLICK)) } // ---- ProjectileDispenseBehavior ---- @@ -638,6 +899,12 @@ impl Game<'_> { 1.0, 1018, ), + "minecraft:wind_charge" => ( + Self::dispense_position(pos, facing, 1.0, [0.0; 3]), + 6.666_666_5, + 1.0, + 1051, + ), "minecraft:experience_bottle" | "minecraft:splash_potion" | "minecraft:lingering_potion" => ( @@ -657,17 +924,19 @@ impl Game<'_> { count: 1, ..stack.clone() }; + // Projectile.shoot spreads the shot with the projectile's own random. + let mut own = entity_random(); match item.as_str() { "minecraft:experience_bottle" | "minecraft:splash_potion" | "minecraft:lingering_potion" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); - shot.shoot(&mut self.world.random, dir, power, uncertainty); + shot.shoot(&mut own, dir, power, uncertainty); self.launch_thrown(one, at, shot.velocity); } "minecraft:firework_rocket" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); - shot.shoot(&mut self.world.random, dir, power, uncertainty); + shot.shoot(&mut own, dir, power, uncertainty); self.launch_dispensed_rocket(at, shot.velocity, &one); } _ => { @@ -698,15 +967,20 @@ impl Game<'_> { .map(|(id, duration, _)| (*id, (duration / 8).max(1))) }), }, - "minecraft:fire_charge" => { - // The fireball's own aim is drawn first, then shot along the facing. + "minecraft:fire_charge" | "minecraft:wind_charge" => { + // asProjectile aims with the level's random first; the + // shot along the facing then replaces that motion. let r = &mut self.world.random; let _ = ( r.triangle(dir[0], 0.114_85), r.triangle(dir[1], 0.114_85), r.triangle(dir[2], 0.114_85), ); - ProjectileKind::SmallFireball + if item == "minecraft:wind_charge" { + ProjectileKind::WindCharge + } else { + ProjectileKind::SmallFireball + } } "minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => { ProjectileKind::Egg @@ -714,7 +988,7 @@ impl Game<'_> { _ => ProjectileKind::Snowball, }; let mut shot = Projectile::new(kind, at, None); - shot.shoot(&mut self.world.random, dir, power, uncertainty); + shot.shoot(&mut own, dir, power, uncertainty); self.creatures.projectiles.push(shot); } } @@ -730,6 +1004,8 @@ impl Game<'_> { f64::from(front.1), f64::from(front.2) + 0.5, ); + // EntityType.create rolls a yaw from the level random before the stack config turns it. + let _ = self.world.random.next_float(); self.next_entity += 1; let stand = horizon_client::entities::ArmorStand::new(self.next_entity, foot, y_rot(facing)); @@ -746,18 +1022,25 @@ impl Game<'_> { if matches!( m.species(), Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama - ) && m.extra.tame + ) && m.alive() + && m.extra.tame && !m.extra.chested { m.extra.chested = true; + set_success("chest", true); return (shrink(stack), CLICK); } } - (self.default_execute(pos, facing, stack), CLICK) + ( + self.default_execute(pos, facing, stack), + optional_event("chest"), + ) } /// `BoatDispenseItemBehavior`. fn dispense_boat(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { - let Some(wood) = super::boats::boat_wood(&stack.item).map(str::to_owned) else { + let Some((wood, chest)) = + super::boats::any_boat_wood(&stack.item).map(|(w, c)| (w.to_owned(), c)) + else { return (self.dispense_default(pos, facing, stack), CLICK); }; let front = offset(pos, facing); @@ -778,16 +1061,19 @@ impl Game<'_> { } else { return (self.dispense_default(pos, facing, stack), CLICK); }; - if !self.boat_models.models.contains_key(&wood) { + if !self.boat_models.has(&wood, chest) { return (self.dispense_default(pos, facing, stack), CLICK); } self.next_entity += 1; - let boat = super::boats::Boat::new( + let mut boat = super::boats::Boat::new( self.next_entity, wood.as_str().into(), Vec3::new(x, y + y_offset, z), y_rot(facing), ); + if chest { + boat = boat.with_chest(); + } self.world.modified.insert((front.0 >> 4, front.2 >> 4)); self.boats.push(boat); (shrink(stack), CLICK) @@ -860,17 +1146,22 @@ impl Game<'_> { None, ), "minecraft:axolotl_bucket" => ( - BucketContent::Fluid(FluidKind::Water), + BucketContent::MobWater, "minecraft:item.bucket.empty_axolotl", Some("axolotl"), ), "minecraft:tadpole_bucket" => ( - BucketContent::Fluid(FluidKind::Water), + BucketContent::MobWater, "minecraft:item.bucket.empty_tadpole", Some("tadpole"), ), + "minecraft:sulfur_cube_bucket" => ( + BucketContent::Nothing, + "minecraft:item.bucket.empty_sulfur_cube", + Some("sulfur_cube"), + ), other => ( - BucketContent::Fluid(FluidKind::Water), + BucketContent::MobWater, "minecraft:item.bucket.empty_fish", Some(match other { "minecraft:salmon_bucket" => "salmon", @@ -888,7 +1179,10 @@ impl Game<'_> { return Ok((self.dispense_default(pos, facing, stack), CLICK)); } if self.dim == super::Dim::Nether - && matches!(content, BucketContent::Fluid(FluidKind::Water)) + && matches!( + content, + BucketContent::Fluid(FluidKind::Water) | BucketContent::MobWater + ) { // The water evaporates in a cloud of smoke. let c = Self::center(target); @@ -906,9 +1200,19 @@ impl Game<'_> { [0.0; 3], ); } - } else if let Some(kind) = mob { - // MobBucketItem.checkExtraContent. - self.spawn_mob_at(kind, target, true); + } + if let Some(kind) = mob { + // MobBucketItem.checkExtraContent: the mob (from the bucket, so + // persistent) calls out, then ENTITY_PLACE. + if let Some(id) = self.spawn_mob_at(kind, target, true) { + self.mob_placed(id)?; + } + self.post_block_game_event( + "minecraft:entity_place", + [target.0, target.1, target.2], + None, + None, + ); } let bucket = ItemStack::new("minecraft:bucket", 1); Ok(( @@ -928,6 +1232,12 @@ impl Game<'_> { self.process_level_events()?; match picked { Some(filled) => { + self.post_block_game_event( + "minecraft:fluid_pickup", + [target.x, target.y, target.z], + None, + None, + ); let filled = ItemStack::new(filled, 1); Ok(( self.consume_with_remainder(pos, facing, stack, filled), @@ -951,29 +1261,54 @@ impl Game<'_> { let state = self.block_at(target); let name = self.dispenser_block_name(target); let mut success = true; - if self.res.facts.is_air(state) { - // BaseFireBlock.canBePlacedAt: a fire that survives, or a portal. - let below = self.dispenser_block_name((target.0, target.1 - 1, target.2)); - let fire_name = if matches!(&*below, "minecraft:soul_sand" | "minecraft:soul_soil") { - "minecraft:soul_fire" - } else { - "minecraft:fire" - }; - let fire = self.res.assets.registry.default_state(fire_name); - if let Some(fire) = fire - && self.with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire)) - { - self.level_set([target.0, target.1, target.2], fire)?; - } else if !self.try_light_portal([target.0, target.1, target.2])? { - // Nothing to light; vanilla still counts it as a success. + // tryIgniteExplosiveEntities: the first sulfur cube that can explode is primed. + let cube = self.targets_at(target).into_iter().find_map(|t| match t { + Target::Mob(i) => { + let m = &self.mobs[i]; + (m.species() == Species::SulfurCube + && m.alive() + && !sulfur_cube::primed(m) + && sulfur_cube::archetype(m).is_some_and(|a| a.explosion.is_some())) + .then_some(i) } - } else if self.prop(state, "lit").as_deref() == Some("false") - && (name.contains("campfire") || name.contains("candle")) - && self.prop(state, "waterlogged").as_deref() != Some("true") + _ => None, + }); + if let Some(i) = cube { + // primeTime(false): the fuse is lit only while TNT explodes; the + // ignition counts either way. + if self.ui.rules.bool("tnt_explodes") && sulfur_cube::prime(&mut self.mobs[i], false) { + let m = &mut self.mobs[i]; + let (at, id) = (m.position, m.id); + let mut events = Vec::new(); + m.voice("entity.tnt.primed", &mut events); + self.handle_mob_events(events)?; + let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None); + self.post_game_event("minecraft:prime_fuse", [at.x, at.y, at.z], ctx); + } + return Ok((self.hurt_and_break(stack, 1), CLICK)); + } + if self + .with_level(|b, level, ticks| b.fire_can_be_placed_at(level, ticks, target_pos, facing)) { + let fire = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, target_pos)); + self.level_set([target.0, target.1, target.2], fire)?; + self.post_block_game_event( + "minecraft:block_place", + [target.0, target.1, target.2], + None, + None, + ); + } else if self.can_light(state, &name) { if let Some(lit) = self.with_props(state, &[("lit", "true")]) { self.level_set([target.0, target.1, target.2], lit)?; } + self.post_block_game_event( + "minecraft:block_change", + [target.0, target.1, target.2], + None, + None, + ); } else if &*name == "minecraft:tnt" { if self.ui.rules.bool("tnt_explodes") { self.spawn_primed_tnt(target_pos, false); @@ -989,6 +1324,17 @@ impl Game<'_> { } Ok((Some(stack), event)) } + /// `CampfireBlock.canLight || CandleBlock.canLight || CandleCakeBlock.canLight`. + fn can_light(&self, state: BlockStateId, name: &str) -> bool { + let lit = self.prop(state, "lit"); + let waterlogged = self.prop(state, "waterlogged"); + let dry_unlit = lit.as_deref() == Some("false") && waterlogged.as_deref() == Some("false"); + ((self.in_block_tag("minecraft:campfires", name) + || self.in_block_tag("minecraft:candles", name)) + && dry_unlit) + || (self.in_block_tag("minecraft:candle_cakes", name) + && lit.as_deref() == Some("false")) + } fn dispense_bone_meal( &mut self, pos: Pos, @@ -1018,10 +1364,34 @@ impl Game<'_> { } fn dispense_tnt(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { if !self.ui.rules.bool("tnt_explodes") { + set_success("tnt", false); return (Some(stack), FAIL); } - let target = Self::pos_of(offset(pos, facing)); - self.spawn_primed_tnt(target, false); + let front = offset(pos, facing); + if self.sulfur_cube_swallow(front, &stack) { + return (shrink(stack), optional_event("tnt")); + } + set_success("tnt", true); + // new PrimedTnt(level, x + 0.5, y, z + 0.5, null), its sound and ENTITY_PLACE. + let target = Self::pos_of(front); + let rot = self.world.random.next_double() * f64::from(std::f32::consts::TAU); + self.add_primed_tnt(target, rot, 80); + self.audio.play( + "minecraft:entity.tnt.primed", + Some([ + f64::from(target.x) + 0.5, + f64::from(target.y), + f64::from(target.z) + 0.5, + ]), + 1.0, + 1.0, + ); + self.post_block_game_event( + "minecraft:entity_place", + [front.0, front.1, front.2], + None, + None, + ); (shrink(stack), CLICK) } @@ -1042,8 +1412,8 @@ impl Game<'_> { let rotation = match facing { Direction::Up | Direction::Down => 0, other => { - // RotationSegment.convertToSegment: opposite 2D data value * 4. - (match other.opposite() { + // RotationSegment.convertToSegment: the 2D data value * 4. + (match other { Direction::South => 0, Direction::West => 1, Direction::North => 2, @@ -1062,6 +1432,12 @@ impl Game<'_> { if let Some(entity) = BlockEntity::for_block("minecraft:wither_skeleton_skull") { self.world.block_entities.insert(target, entity); } + self.post_block_game_event( + "minecraft:block_place", + [target.0, target.1, target.2], + None, + None, + ); self.check_wither_spawn([target.0, target.1, target.2])?; return Ok((shrink(stack), CLICK)); } @@ -1114,8 +1490,22 @@ impl Game<'_> { .registry .default_state("minecraft:carved_pumpkin") { - self.level_set([target.0, target.1, target.2], pumpkin)?; - self.check_golem_spawn([target.0, target.1, target.2])?; + let head = [target.0, target.1, target.2]; + if self.completes_golem(head) { + // CarvedPumpkinBlock.onPlace builds the golem inside + // setBlock; the spot is air again by the time setBlock + // would update neighbours, so it skips them. + let at = Self::pos_of(target); + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, at, pumpkin, 2 | 16) + }); + self.process_level_events()?; + self.check_golem_spawn(head)?; + } else { + self.level_set(head, pumpkin)?; + self.check_golem_spawn(head)?; + } + self.post_block_game_event("minecraft:block_place", head, None, None); } return Ok((shrink(stack), CLICK)); } @@ -1139,10 +1529,6 @@ impl Game<'_> { .facts .is_air(self.block_at((front.0, front.1 - 1, front.2))); let clicked_face = if below_empty { facing } else { Direction::Up }; - let front_state = self.block_at(front); - if !(self.res.facts.is_air(front_state) || self.res.facts.get(front_state).replaceable) { - return Ok((Some(stack), FAIL)); - } let ctx = PlaceContext { clicked_pos: Self::pos_of(front), face: clicked_face, @@ -1158,6 +1544,10 @@ impl Game<'_> { item: stack.item.to_string(), can_use_game_master_blocks: false, }; + // DirectionalPlaceContext places at the front block or nowhere. + if !self.with_level(|b, level, ticks| b.directional_can_place(level, ticks, &ctx)) { + return Ok((Some(stack), FAIL)); + } let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx)); let PlaceOutcome::Placed { pos: placed, state } = outcome else { self.process_level_events()?; @@ -1169,13 +1559,6 @@ impl Game<'_> { self.fill_placed_box([target.0, target.1, target.2], &stack); self.name_placed_container([target.0, target.1, target.2], &stack); } - let sounds = self.res.facts.get(state).sounds.clone(); - self.audio.play( - &sounds.place, - Some(Self::center(target)), - (sounds.volume + 1.0) / 2.0, - sounds.pitch * 0.8, - ); self.process_level_events()?; Ok((shrink(stack), CLICK)) } @@ -1203,6 +1586,7 @@ impl Game<'_> { self.level_set([target.0, target.1, target.2], reset)?; } let bottle = ItemStack::new("minecraft:honey_bottle", 1); + self.post_block_game_event("minecraft:fluid_pickup", [pos.0, pos.1, pos.2], None, None); return Ok(( self.consume_with_remainder(pos, facing, stack, bottle), CLICK, @@ -1210,6 +1594,7 @@ impl Game<'_> { } if self.water_at(target) { let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + self.post_block_game_event("minecraft:fluid_pickup", [pos.0, pos.1, pos.2], None, None); return Ok(( self.consume_with_remainder(pos, facing, stack, water), CLICK, @@ -1235,6 +1620,13 @@ impl Game<'_> { self.with_props(state, &[("charges", &(charge + 1).to_string())]) { self.level_set([target.0, target.1, target.2], next)?; + // RespawnAnchorBlock.charge: Context.of(null, newState). + self.post_block_game_event( + "minecraft:block_change", + [target.0, target.1, target.2], + None, + Some(next), + ); } self.audio.play( "minecraft:block.respawn_anchor.charge", @@ -1276,128 +1668,353 @@ impl Game<'_> { 1.0, 1.0, ); - // BeehiveBlock.dropHoneycomb, then the honey level resets. - self.pop_resource( - [target.0, target.1, target.2], - ItemStack::new("minecraft:honeycomb", 3), - ); - if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { - self.level_set([target.0, target.1, target.2], reset)?; + // BeehiveBlock.dropHoneycomb (harvest/beehive), then + // releaseBeesAndResetHoneyLevel and the shear event. + let p = [target.0, target.1, target.2]; + for stack in self.sequence_loot( + "minecraft:harvest/beehive", + "minecraft:harvest/beehive", + None, + ) { + self.pop_resource(p, stack); } + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set(p, reset)?; + } + self.post_block_game_event("minecraft:shear", p, None, None); Ok(true) } - /// `Shearable.shear` on the first ready entity in the block. + /// `LootTable.getRandomItems` of `table` in the context of `parent`: the + /// draws come from `parent`'s server random sequence when it names one (a + /// nested `loot_table` entry shares its parent's context), else the level's. + pub(super) fn sequence_loot( + &mut self, + parent: &str, + table: &str, + held: Option<&ItemStack>, + ) -> Vec { + match self.res.items.loot_sequence(parent) { + Some(sequence) => { + let random = self.rand_sequences.get(&sequence, self.level.seed); + self.res.items.loot_table_from(table, false, held, random) + } + None => self + .res + .items + .loot_table(table, false, held, &mut self.world.random), + } + } + /// `Entity.spawnAtLocation(level, stack, offset)`: an item at the entity's + /// feet plus the offset, moving as `new ItemEntity` makes it. + fn spawn_at_location(&mut self, at: Vec3, y_offset: f64, stack: ItemStack) -> [f64; 3] { + let v = new_item_motion(); + self.spawn_item(stack, [at.x, at.y + y_offset, at.z], v, 10); + v + } + /// `Mob.convertTo(type, ConversionParams.single(this, false, false))`: a + /// new mob of `kind` in the same place (no spawn finalization, so no + /// random draws) keeps the name, flags, persistence and age; the old one + /// is discarded. + pub(super) fn convert_mob(&mut self, index: usize, kind: &str) -> Option { + let t = self.res.mob_types.get(kind).cloned()?; + let old = &self.mobs[index]; + self.next_entity += 1; + let mut mob = Mob::new(self.next_entity, t, old.position, old.yaw); + mob.previous = old.previous; + mob.head_yaw = old.head_yaw; + mob.body_yaw = old.body_yaw; + mob.head_pitch = old.head_pitch; + mob.persistent = old.persistent; + mob.custom_name = old.custom_name.clone(); + mob.name_visible = old.name_visible; + mob.no_ai = old.no_ai; + mob.silent = old.silent; + mob.no_gravity = old.no_gravity; + mob.invulnerable_flag = old.invulnerable_flag; + mob.extra.age = if old.is_baby() { old.extra.age } else { 0 }; + for slot in [ + &mut mob.extra.main_hand, + &mut mob.extra.off_hand, + &mut mob.extra.head, + &mut mob.extra.chest, + &mut mob.extra.legs, + &mut mob.extra.feet, + ] { + *slot = None; + } + let id = mob.id; + self.mobs[index].removed = true; + self.mobs.push(mob); + Some(id) + } + /// `ShearsDispenseItemBehavior.tryShearEntity`: the first live, ready + /// `Shearable` in the block is sheared. fn shear_entity(&mut self, target: Pos) -> Result { + let shears = ItemStack::new("minecraft:shears", 1); for t in self.targets_at(target) { + // Entity.shearOffAllLeashConnections comes first, for any entity. + if self.shear_off_leashes(t) { + return Ok(true); + } let Target::Mob(i) = t else { continue }; let m = &self.mobs[i]; - let at = [m.position.x, m.position.y, m.position.z]; + if !m.alive() { + continue; + } + let at = m.position; + let sound_at = Some([at.x, at.y, at.z]); match m.species() { + Species::SulfurCube if sulfur_cube::has_body(m) => { + // SulfurCube.shear: the swallowed block comes out at the + // passenger attachment, and nothing is swallowed for 5 s. + let height = f64::from(m.height()); + let id = m.id; + if let Some(body) = self.mobs[i].extra.head.take() { + self.spawn_at_location(at, height, ItemStack::new(&body, 1)); + } + // setItemSlot(BODY, EMPTY): an unequip. + let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None); + self.post_game_event("minecraft:unequip", [at.x, at.y, at.z], ctx); + self.mobs[i].extra.ints[3] = sulfur_cube::PICKUP_TIMER; + self.audio + .play("minecraft:entity.sulfur_cube.eject", sound_at, 1.0, 1.0); + } Species::Sheep if !m.extra.sheared && !m.is_baby() => { let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; - self.mobs[i].extra.sheared = true; self.audio - .play("minecraft:entity.sheep.shear", Some(at), 1.0, 1.0); - let stacks = self.res.items.loot_table( + .play("minecraft:entity.sheep.shear", sound_at, 1.0, 1.0); + let drops = self.sequence_loot( + "minecraft:shearing/sheep", &format!("minecraft:shearing/sheep/{color}"), - false, - None, - &mut self.world.random, + Some(&shears), ); - self.drop_sheared(at, stacks); - return Ok(true); + for stack in drops { + for _ in 0..stack.count { + let one = ItemStack { + count: 1, + ..stack.clone() + }; + self.spawn_at_location(at, 1.0, one); + // Sheep.shear nudges each item with the sheep's own random. + let r = &mut self.mobs[i].random; + let push = [ + f64::from((r.next_float() - r.next_float()) * 0.1), + f64::from(r.next_float() * 0.05), + f64::from((r.next_float() - r.next_float()) * 0.1), + ]; + if let Some(item) = self.dropped.last_mut() { + item.velocity = Vec3::new( + item.velocity.x + push[0], + item.velocity.y + push[1], + item.velocity.z + push[2], + ); + } + } + } + self.mobs[i].extra.sheared = true; } Species::Bogged if !m.extra.sheared => { - self.mobs[i].extra.sheared = true; + let height = f64::from(m.height()); self.audio - .play("minecraft:entity.bogged.shear", Some(at), 1.0, 1.0); - let stacks = self.res.items.loot_table( + .play("minecraft:entity.bogged.shear", sound_at, 1.0, 1.0); + let drops = self.sequence_loot( "minecraft:shearing/bogged", - false, - None, - &mut self.world.random, + "minecraft:shearing/bogged", + Some(&shears), ); - self.drop_sheared(at, stacks); - return Ok(true); + for stack in drops { + self.spawn_at_location(at, height, stack); + } + self.mobs[i].extra.sheared = true; + } + Species::SnowGolem if !m.extra.sheared => { + let eye = m.eye_height(); + self.audio + .play("minecraft:entity.snow_golem.shear", sound_at, 1.0, 1.0); + self.mobs[i].extra.sheared = true; + let drops = self.sequence_loot( + "minecraft:shearing/snow_golem", + "minecraft:shearing/snow_golem", + Some(&shears), + ); + for stack in drops { + self.spawn_at_location(at, eye, stack); + } } Species::Mooshroom if !m.is_baby() => { - let mushroom = if m.extra.variant == 1 { - "minecraft:brown_mushroom" - } else { - "minecraft:red_mushroom" - }; - let setup = SpawnSetup { - yaw: m.yaw, - persistent: true, - ..Default::default() - }; - self.mobs[i].removed = true; + let variant = if m.extra.variant == 1 { "brown" } else { "red" }; + let height = f64::from(m.height()); self.audio - .play("minecraft:entity.mooshroom.shear", Some(at), 1.0, 1.0); - self.handle_mob_events(vec![MobEvent::SpawnKind { - kind: "minecraft:cow".into(), - at, - setup, - }])?; - for _ in 0..5 { - let v = [0.0, 0.2, 0.0]; - self.spawn_item( - ItemStack::new(mushroom, 1), - [at[0], at[1] + 1.0, at[2]], - v, - 10, - ); + .play("minecraft:entity.mooshroom.shear", sound_at, 1.0, 1.0); + // convertTo(COW): the cow takes its place, then the mushrooms drop. + self.convert_mob(i, "minecraft:cow"); + let drops = self.sequence_loot( + "minecraft:shearing/mooshroom", + &format!("minecraft:shearing/mooshroom/{variant}"), + Some(&shears), + ); + for stack in drops { + for _ in 0..stack.count { + let one = ItemStack { + count: 1, + ..stack.clone() + }; + self.spawn_at_location(at, height, one); + } } - return Ok(true); } - _ => {} + _ => continue, } + self.post_block_game_event( + "minecraft:shear", + [target.0, target.1, target.2], + None, + None, + ); + return Ok(true); } Ok(false) } - /// The drops of a sheared mob, one entity per item, a block above its feet. - fn drop_sheared(&mut self, at: [f64; 3], stacks: Vec) { - for stack in stacks { - for _ in 0..stack.count { - let r = &mut self.world.random; - let v = [ - f64::from((r.next_float() - r.next_float()) * 0.1), - f64::from(r.next_float() * 0.05), - f64::from((r.next_float() - r.next_float()) * 0.1), - ]; - let one = ItemStack { - count: 1, - ..stack.clone() - }; - self.spawn_item(one, [at[0], at[1] + 1.0, at[2]], v, 10); + /// `Entity.shearOffAllLeashConnections(null)`: the entity's own lead and + /// every lead held by it (within a 32 block box around its centre) drop; + /// a shear game event at the entity and a snip at its block follow. + fn shear_off_leashes(&mut self, t: Target) -> bool { + use horizon_client::mobs::{Who, leash::Holder}; + let (holder, centre, own) = match t { + Target::Mob(i) => { + let m = &self.mobs[i]; + let b = m.bounds(); + (Holder::Mob(m.id), b.center(), Some(i)) } + Target::Player => { + let Some(v) = self.player_view() else { + return false; + }; + (Holder::Player, v.bounds.center(), None) + } + Target::Stand(_) => return false, + }; + let area = Aabb::new(centre, centre).inflate(Vec3::new(16.0, 16.0, 16.0)); + let mut leashed: Vec<(u32, usize)> = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| { + !m.removed && m.extra.leash == Some(holder) && overlaps(m.bounds(), area) + }) + .map(|(j, m)| (m.id, j)) + .collect(); + leashed.sort_unstable(); + let own_leashed = own.is_some_and(|i| self.mobs[i].extra.leash.is_some()); + if leashed.is_empty() && !own_leashed { + return false; } + // Leashable.dropLeash: a lead item at the leashed entity's feet. + let drop = |game: &mut Self, j: usize| { + if game.mobs[j].extra.leash.take().is_some() { + let at = game.mobs[j].position; + game.spawn_at_location(at, 0.0, ItemStack::new("minecraft:lead", 1)); + } + }; + if let Some(i) = own.filter(|_| own_leashed) { + drop(self, i); + } + for (_, j) in leashed { + drop(self, j); + } + let (at, who) = match t { + Target::Mob(i) => { + let m = &self.mobs[i]; + (m.position, Who::Mob(m.id)) + } + _ => ( + self.player.as_ref().map_or(Vec3::ZERO, |p| p.position), + Who::Player, + ), + }; + let ctx = self.who_context(Some(who), None); + self.post_game_event("minecraft:shear", [at.x, at.y, at.z], ctx); + let block = [at.x.floor() + 0.5, at.y.floor() + 0.5, at.z.floor() + 0.5]; + self.audio + .play("minecraft:item.shears.snip", Some(block), 1.0, 1.0); + true } - /// A brush used on an adult armadillo in front. + /// The brush behaviour: the first armadillo in front that `brushOffScute`s. fn dispense_brush(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { let target = offset(pos, facing); - let armadillo = self.targets_at(target).into_iter().find_map(|t| match t { - Target::Mob(i) if self.mobs[i].species() == Species::Armadillo => Some(i), - _ => None, - }); - let Some(i) = armadillo.filter(|&i| !self.mobs[i].is_baby()) else { - return (Some(stack), FAIL); - }; - let m = &self.mobs[i]; - let at = [m.position.x, m.position.y, m.position.z]; - let drops = self.res.items.loot_table( - "minecraft:brush/armadillo", - false, - None, - &mut self.world.random, - ); - for d in drops { - self.spawn_item(d, [at[0], at[1] + 0.5, at[2]], [0.0, 0.2, 0.0], 10); + let armadillos: Vec = self + .targets_at(target) + .into_iter() + .filter_map(|t| match t { + Target::Mob(i) if self.mobs[i].species() == Species::Armadillo => Some(i), + _ => None, + }) + .collect(); + for i in armadillos { + if self.mobs[i].is_baby() { + continue; + } + let at = self.mobs[i].position; + let drops = self.sequence_loot( + "minecraft:brush/armadillo", + "minecraft:brush/armadillo", + Some(&stack), + ); + for d in drops { + self.spawn_at_location(at, 0.0, d); + } + self.audio.play( + "minecraft:entity.armadillo.brush", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + let who = horizon_client::mobs::Who::Mob(self.mobs[i].id); + let ctx = self.who_context(Some(who), None); + self.post_game_event("minecraft:entity_interact", [at.x, at.y, at.z], ctx); + return (self.hurt_and_break(stack, 16), optional_event("brush")); } - self.audio - .play("minecraft:entity.armadillo.brush", Some(at), 1.0, 1.0); - (self.hurt_and_break(stack, 16), CLICK) + set_success("brush", false); + (Some(stack), FAIL) + } + /// `SulfurCubeBlockDispenseItemBehavior.dispenseBlock`: the first sulfur + /// cube in the block that `equipItem`s the stack swallows one. + fn sulfur_cube_swallow(&mut self, target: Pos, stack: &ItemStack) -> bool { + let cubes: Vec = self + .targets_at(target) + .into_iter() + .filter_map(|t| match t { + Target::Mob(i) if self.mobs[i].species() == Species::SulfurCube => Some(i), + _ => None, + }) + .collect(); + for i in cubes { + let m = &self.mobs[i]; + if m.is_baby() || m.extra.head.as_deref() == Some(&*stack.item) { + continue; + } + let (at, height) = (m.position, f64::from(m.height())); + // The swallowed block comes out on top (the passenger attachment). + if let Some(old) = self.mobs[i].extra.head.take() { + self.spawn_at_location(at, height, ItemStack::new(&old, 1)); + } + let m = &mut self.mobs[i]; + m.extra.head = Some(stack.item.clone()); + m.persistent = true; + let (at, id) = (m.position, m.id); + // setItemSlot: a body item without `equippable` posts UNEQUIP. + let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None); + self.post_game_event("minecraft:unequip", [at.x, at.y, at.z], ctx); + self.audio.play( + "minecraft:entity.sulfur_cube.absorb", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + return true; + } + false } fn dispense_honeycomb( &mut self, @@ -1422,9 +2039,20 @@ impl Game<'_> { let Some(waxed) = waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod")) else { - return Ok((self.default_execute(pos, facing, stack), CLICK)); + return Ok(( + self.default_execute(pos, facing, stack), + optional_event("honeycomb"), + )); }; + set_success("honeycomb", true); self.level_set([target.0, target.1, target.2], waxed)?; + self.level_events + .push(horizon_world::level::LevelEvent::LevelEvent { + id: 3003, + pos: Self::pos_of(target), + data: 0, + }); + self.process_level_events()?; self.audio.play( "minecraft:item.honeycomb.wax_on", Some(Self::center(target)), @@ -1447,8 +2075,9 @@ impl Game<'_> { // events play on top. return Ok((self.dispense_default(pos, facing, stack), CLICK)); } + // The server picks the splash positions with the level random. for _ in 0..5 { - let r = self.particles.random(); + let r = &mut self.world.random; let p = [ f64::from(pos.0) + r.next_double(), f64::from(pos.1 + 1), @@ -1463,6 +2092,7 @@ impl Game<'_> { 1.0, 1.0, ); + self.post_block_game_event("minecraft:fluid_place", [pos.0, pos.1, pos.2], None, None); if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") { self.level_set([target.0, target.1, target.2], mud)?; } diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 4f0c3fa9c..80b72ad26 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -29,6 +29,12 @@ pub(super) struct Rocket { angled: bool, icon: Option, } +impl Rocket { + /// Position and motion (the dispenser parity fixture). + pub(super) fn motion(&self) -> (Vec3, Vec3) { + (self.position, self.velocity) + } +} fn fireworks_of(stack: &ItemStack) -> (u8, Vec) { // The item's default component: flight 1, no explosions. stack @@ -39,10 +45,9 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec) { impl Game<'_> { pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket { let (flight, explosions) = fireworks_of(stack); - let r = &mut self.world.random; - let tri = |r: &mut horizon_core::random::LegacyRandom| { - 0.002297 * (f64::from(r.next_float()) - f64::from(r.next_float())) - }; + // FireworkRocketEntity: motion and lifetime come from the rocket's own random. + let r = &mut super::dispenser::entity_random(); + let tri = |r: &mut horizon_core::random::LegacyRandom| r.triangle(0.0, 0.002297); let velocity = Vec3::new(tri(r), 0.05, tri(r)); let lifetime = 10 * (1 + i32::from(flight)) + r.next_int_bound(6).unwrap_or(0) diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs index 3d673656b..a67e05af8 100644 --- a/crates/horizon-client/src/game/golems.rs +++ b/crates/horizon-client/src/game/golems.rs @@ -24,6 +24,7 @@ impl Game<'_> { if self.golem_block(below(1)) == "minecraft:snow_block" && self.golem_block(below(2)) == "minecraft:snow_block" { + // The pattern ("^", "#", "#") is one column. return Some(( "minecraft:snow_golem", vec![head, below(1), below(2)], @@ -38,9 +39,11 @@ impl Game<'_> { && self.golem_block(side(0, 2)) == "minecraft:iron_block" && [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2))) { - let mut blocks = vec![head]; - blocks.extend((-1..=1).map(|s| side(s, 1))); - blocks.push(side(0, 2)); + // Every cell of ("~^~", "###", "~#~"), the air ones included. + let blocks = (-1..=1) + .flat_map(|s| (0..3).map(move |row| (s, row))) + .map(|(s, row)| side(s, row)) + .collect(); return Some(("minecraft:iron_golem", blocks, side(0, 2))); } } @@ -58,27 +61,68 @@ impl Game<'_> { let Some((kind, blocks, base)) = self.find_golem(head) else { return self.try_spawn_copper_golem(head); }; - for p in blocks { - let state = self.world.block(p[0], p[1], p[2]); - self.destroy_particles(p, state); - self.level_set(p, self.world.air)?; - } + // CarvedPumpkinBlock.spawnGolemInWorld + self.clear_pattern_blocks(&blocks)?; let at = [ f64::from(base[0]) + 0.5, f64::from(base[1]) + 0.05, f64::from(base[2]) + 0.5, ]; - if let Some(id) = self.spawn_mob(kind, at, false) - && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) - { - m.yaw = 0.0; - m.body_yaw = 0.0; - m.head_yaw = 0.0; - m.previous_yaw = 0.0; - m.previous_body_yaw = 0.0; - m.previous_head_yaw = 0.0; + self.create_triggered(kind, at, 0.0); + self.update_pattern_blocks(&blocks) + } + /// Whether placing a golem head at `head` completes a snow or iron golem. + pub(super) fn completes_golem(&self, head: [i32; 3]) -> bool { + self.find_golem(head).is_some() + } + /// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or + /// wither has no spawn finalization and draws nothing from the level. + pub(super) fn create_triggered(&mut self, kind: &str, at: [f64; 3], yaw: f32) -> Option { + let t = self.res.mob_types.get(kind).cloned()?; + self.next_entity += 1; + let mut mob = horizon_client::mobs::Mob::new( + self.next_entity, + t, + horizon_core::geometry::Vec3::new(at[0], at[1], at[2]), + yaw, + ); + mob.head_yaw = yaw; + mob.body_yaw = yaw; + mob.previous_yaw = yaw; + mob.previous_body_yaw = yaw; + mob.previous_head_yaw = yaw; + let id = mob.id; + self.mobs.push(mob); + Some(id) + } + /// `CarvedPumpkinBlock.clearPatternBlocks`: every cell of the match + /// becomes air (flags 2) with its destroy event (2001). + pub(super) fn clear_pattern_blocks(&mut self, cells: &[[i32; 3]]) -> Result<()> { + let air = self.world.air; + for &p in cells { + let state = self.world.block(p[0], p[1], p[2]); + let pos = horizon_core::position::BlockPos::new(p[0], p[1], p[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, air, 2)); + self.level_events + .push(horizon_world::level::LevelEvent::LevelEvent { + id: 2001, + pos, + data: state.0 as i32, + }); } - Ok(()) + self.process_level_events() + } + /// `CarvedPumpkinBlock.updatePatternBlocks`: neighbours of every cell + /// hear that air arrived. + pub(super) fn update_pattern_blocks(&mut self, cells: &[[i32; 3]]) -> Result<()> { + let air = self.world.air; + for &p in cells { + let pos = horizon_core::position::BlockPos::new(p[0], p[1], p[2]); + self.with_level(|b, level, ticks| { + b.update_neighbors_at(level, ticks, pos, b.block(air)) + }); + } + self.process_level_events() } /// A pumpkin on a copper block: the block turns into the matching copper /// chest (facing the pumpkin's way) and a copper golem appears where the diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index dfcb34746..77ccc9a97 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -8,7 +8,6 @@ use horizon_client::{ mesher::Vertex, mobs::leash::{self, Holder, Pending}, }; -use horizon_core::random::RandomSource; use horizon_world::nbt::Tag; /// `Vec3.yRot(angle)`. @@ -66,13 +65,10 @@ impl Game<'_> { }) .collect() } + /// `Entity.spawnAtLocation(level, Items.LEAD)`: the item entity draws its + /// motion from its own random, not the level's. fn drop_lead_item(&mut self, at: [f64; 3]) { - let r = &mut self.world.random; - let v = [ - f64::from(r.next_float()) * 0.2 - 0.1, - 0.2, - f64::from(r.next_float()) * 0.2 - 0.1, - ]; + let v = super::dispenser::new_item_motion(); self.spawn_item(ItemStack::new("minecraft:lead", 1), at, v, 10); } /// `Leashable.dropLeash` / `removeLeash`: the lead falls as an item. diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 967bef7e4..c9baac7d9 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -28,6 +28,9 @@ pub(super) enum CartKind { Hopper, Furnace, Tnt, + /// `MinecartCommandBlock`; its command block holds no command, so an + /// activator rail runs nothing. + CommandBlock, } impl CartKind { pub fn from_id(id: &str) -> Option { @@ -37,6 +40,7 @@ impl CartKind { "hopper_minecart" => Self::Hopper, "furnace_minecart" => Self::Furnace, "tnt_minecart" => Self::Tnt, + "command_block_minecart" => Self::CommandBlock, _ => return None, }) } @@ -47,6 +51,7 @@ impl CartKind { Self::Hopper => "minecraft:hopper_minecart", Self::Furnace => "minecraft:furnace_minecart", Self::Tnt => "minecraft:tnt_minecart", + Self::CommandBlock => "minecraft:command_block_minecart", } } fn slots(self) -> usize { @@ -192,6 +197,7 @@ impl CartModels { CartKind::Hopper, CartKind::Furnace, CartKind::Tnt, + CartKind::CommandBlock, ]; let models = kinds .into_iter() @@ -981,6 +987,8 @@ impl Game<'_> { self.prime_cart(&mut c); self.carts[i] = c; } + // BaseCommandBlock.usedBy: only an operator in creative opens it. + CartKind::CommandBlock => return false, } self.swing_arm(); true @@ -990,9 +998,10 @@ impl Game<'_> { let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else { return; }; - if let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) - && let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) - { + let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else { + return; + }; + if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) { c.items = items; let at = [c.position.x, c.position.y, c.position.z]; if c.kind == CartKind::Chest { @@ -1000,15 +1009,24 @@ impl Game<'_> { self.audio .play("minecraft:block.chest.close", Some(at), 0.5, pitch); } + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) { + b.items = items; } } /// The open cart's kind when a cart container is shown. pub(super) fn open_cart_kind(&self) -> Option { let key = self.container.filter(|k| k.1 == CART_KEY_Y)?; + // A chest boat's chest shows like a chest minecart's. self.carts .iter() .find(|c| c.id as i32 == key.2) .map(|c| c.kind) + .or_else(|| { + self.boats + .iter() + .any(|b| b.chest && b.id as i32 == key.2) + .then_some(CartKind::Chest) + }) } /// `VehicleEntity.hurtServer` from the player's attack. pub(super) fn attack_cart(&mut self, damage: f32) -> bool { @@ -1121,6 +1139,7 @@ impl Game<'_> { ], ), CartKind::Tnt => registry.default_state("minecraft:tnt"), + CartKind::CommandBlock => registry.default_state("minecraft:command_block"), } } /// `AbstractMinecartRenderer` (old render): on the rail between the @@ -1283,6 +1302,13 @@ impl Minecart { put("Fuel", Tag::Short(self.fuel as i16)); } CartKind::Tnt => put("fuse", Tag::Int(self.fuse)), + // BaseCommandBlock.save of an empty command block. + CartKind::CommandBlock => { + put("Command", Tag::String(JavaString::from(""))); + put("SuccessCount", Tag::Int(0)); + put("TrackOutput", Tag::Byte(1)); + put("UpdateLastExecution", Tag::Byte(1)); + } CartKind::Rideable => {} } } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 2aa368383..de2ff8573 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -198,18 +198,27 @@ impl Game<'_> { }); } } - k if super::boats::boat_wood(k).is_some() - && self - .boat_models - .models - .contains_key(super::boats::boat_wood(k).unwrap_or("")) => + k if super::boats::any_boat_wood(k) + .is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) => { if let Some((position, velocity, yaw)) = entity_nbt::boat_from_nbt(&tag) { self.next_entity += 1; let id = self.next_entity; - let wood = - std::sync::Arc::from(super::boats::boat_wood(k).unwrap_or("oak")); - let mut b = super::boats::Boat::new(id, wood, position, yaw); + let (wood, chest) = + super::boats::any_boat_wood(k).unwrap_or(("oak", false)); + let mut b = super::boats::Boat::new( + id, + std::sync::Arc::from(wood), + position, + yaw, + ); + if chest { + b = b.with_chest(); + b.items = horizon_client::save::decode_items( + tag.get("Items"), + super::boats::CHEST_SLOTS, + ); + } b.velocity = velocity; self.remember(id, uuid, tag); self.boats.push(b); @@ -536,12 +545,13 @@ impl Game<'_> { .copied() .unwrap_or_else(random_uuid); let tag = entity_nbt::boat_to_nbt( - &b.wood, + &b.entity_type(), b.position, b.velocity, b.yaw, uuid, self.persist.raw.get(&b.id), + b.chest.then_some(&b.items[..]), ); out.entry(chunk_of(b.position)).or_default().push(tag); } diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index fd5e30b34..f0c5f57b1 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -65,6 +65,27 @@ pub(super) struct PotionState { std::collections::HashMap, } +impl PotionState { + /// Thrown potions in flight as (entity type, position, motion), for the + /// dispenser parity fixture. + pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> { + self.thrown + .iter() + .map(|t| { + let kind = match &*t.stack.item { + "minecraft:lingering_potion" => "minecraft:lingering_potion", + "minecraft:experience_bottle" => "minecraft:experience_bottle", + _ => "minecraft:splash_potion", + }; + (kind, t.position, t.velocity) + }) + .collect() + } + pub(super) fn clear_thrown(&mut self) { + self.thrown.clear(); + } +} + impl Game<'_> { /// Right-click with a potion, splash/lingering potion or glass bottle. pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result { diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 8602802c4..61ff84bd9 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -437,6 +437,14 @@ impl Game<'_> { /// `Level.gameEvent`: tell the listeners within reach. pub(super) fn post_game_event(&mut self, event: &'static str, pos: [f64; 3], ctx: Context) { + super::dispense_fixture::record(|| { + format!( + "G {},{},{} {event}", + pos[0].floor() as i32, + pos[1].floor() as i32, + pos[2].floor() as i32 + ) + }); if self.remote.is_some() || !self.sculk.tables.built { return; } diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 3668e5f9f..df24e06d6 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -40,35 +40,30 @@ impl Game<'_> { if !ok { continue; } - for row in 0..3 { - for c in 0..3 { - let p = at(c, row); - let state = self.world.block(p[0], p[1], p[2]); - if !self.res.facts.is_air(state) { - self.destroy_particles(p, state); - self.world.set(p[0], p[1], p[2], self.world.air)?; - } - } - } + // WitherSkullBlock.checkSpawn: clear the pattern, the wither + // appears on the middle of the bottom row, then neighbours update. + let cells: Vec<[i32; 3]> = (0..3) + .flat_map(|c| (0..3).map(move |row| (c, row))) + .map(|(c, row)| at(c, row)) + .collect(); + self.clear_pattern_blocks(&cells)?; let base = at(1, 2); let at = [ f64::from(base[0]) + 0.5, f64::from(base[1]) + 0.55, f64::from(base[2]) + 0.5, ]; - if let Some(id) = self.spawn_mob("minecraft:wither", at, true) + let yaw = if ax == 1 { 0.0 } else { 90.0 }; + if let Some(id) = self.create_triggered("minecraft:wither", at, yaw) && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - let yaw = if ax == 1 { 0.0 } else { 90.0 }; - m.yaw = yaw; - m.body_yaw = yaw; - m.previous_body_yaw = yaw; - m.head_yaw = yaw; + m.persistent = true; horizon_client::mobs::wither::make_invulnerable(m); let view = self.mob_entity(&self.mobs.iter().find(|m| m.id == id).cloned().unwrap()); self.trigger_entity("minecraft:summoned_entity", "entity", &view); } + self.update_pattern_blocks(&cells)?; return Ok(()); } } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index e0c5a0366..bfecad8ad 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -526,13 +526,27 @@ impl Items { pub fn has_loot_table(&self, id: &str) -> bool { self.loot.contains_key(id) } + /// The server random sequence the block's loot table draws from. + pub fn block_loot_sequence( + &self, + registry: &BlockRegistry, + state: BlockStateId, + ) -> Option { + let block = registry.state(state)?; + let name = block.name.trim_start_matches("minecraft:"); + let standing = name.replacen("_wall_", "_", 1); + let standing = standing.strip_prefix("wall_").unwrap_or(&standing); + let standing = standing.replacen("wall_", "", 1); + self.loot_sequence(&format!("minecraft:blocks/{name}")) + .or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}"))) + } /// Evaluate the block's loot table for a player break without explosions. pub fn block_drops( &self, registry: &BlockRegistry, state: BlockStateId, held: Option<&ItemStack>, - random: &mut LegacyRandom, + random: &mut impl RandomSource, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -581,6 +595,34 @@ impl Items { }; ctx.evaluate(table, random) } + /// The server random sequence a loot table draws from (`random_sequence`): + /// vanilla's `LootContext.Builder.create` uses it instead of the level random. + pub fn loot_sequence(&self, id: &str) -> Option { + self.loot.get(id)?["random_sequence"] + .as_str() + .map(str::to_owned) + } + /// `loot_table` drawing from any random (a random sequence). + pub fn loot_table_from( + &self, + id: &str, + killed_by_player: bool, + held: Option<&ItemStack>, + random: &mut impl RandomSource, + ) -> Vec { + let Some(table) = self.loot.get(id) else { + return vec![]; + }; + let empty = BTreeMap::new(); + let ctx = LootContext { + items: self, + block: "", + properties: &empty, + held, + killed_by_player, + }; + ctx.evaluate(table, random) + } pub fn entity_drops( &self, entity: &str, @@ -604,14 +646,15 @@ impl Items { } } impl LootContext<'_> { - fn evaluate(&self, table: &Value, random: &mut LegacyRandom) -> Vec { + fn evaluate(&self, table: &Value, random: &mut impl RandomSource) -> Vec { let ctx = self; let mut out = Vec::new(); for pool in table["pools"].as_array().into_iter().flatten() { if !ctx.conditions(pool, random) { continue; } - let rolls = ctx.number(&pool["rolls"], random).max(0.0) as u32; + // LootPool: rolls.getInt (Mth.randomBetweenInclusive for uniform rolls). + let rolls = ctx.int_number(&pool["rolls"], random).max(0) as u32; for _ in 0..rolls { let mut produced = Vec::new(); ctx.choose( @@ -643,7 +686,7 @@ impl LootContext<'_> { fn enchantment_level(&self, id: &str) -> u32 { self.held.map_or(0, |h| h.enchantment_level(id)) } - fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 { + fn number(&self, v: &Value, random: &mut impl RandomSource) -> f32 { match v { Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, Value::Object(o) => match o @@ -674,7 +717,7 @@ impl LootContext<'_> { _ => 1.0, } } - fn int_number(&self, v: &Value, random: &mut LegacyRandom) -> i32 { + fn int_number(&self, v: &Value, random: &mut impl RandomSource) -> i32 { if let Value::Object(o) = v && o.get("type") .and_then(Value::as_str) @@ -691,7 +734,7 @@ impl LootContext<'_> { } self.number(v, random).round() as i32 } - fn condition(&self, c: &Value, random: &mut LegacyRandom) -> bool { + fn condition(&self, c: &Value, random: &mut impl RandomSource) -> bool { let (kind, c) = match c { Value::String(s) => (s.as_str(), &Value::Null), Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c), @@ -800,7 +843,7 @@ impl LootContext<'_> { _ => true, } } - fn conditions(&self, o: &Value, random: &mut LegacyRandom) -> bool { + fn conditions(&self, o: &Value, random: &mut impl RandomSource) -> bool { if let Some(c) = o.get("condition") && !self.condition(c, random) { @@ -816,7 +859,7 @@ impl LootContext<'_> { fn expand( &self, e: &Value, - random: &mut LegacyRandom, + random: &mut impl RandomSource, out: &mut Vec<(i32, ItemStack, Value)>, ) -> bool { if !self.conditions(e, random) { @@ -874,7 +917,12 @@ impl LootContext<'_> { _ => false, } } - fn choose(&self, entries: &[Value], random: &mut LegacyRandom, produced: &mut Vec) { + fn choose( + &self, + entries: &[Value], + random: &mut impl RandomSource, + produced: &mut Vec, + ) { let mut candidates = Vec::new(); for e in entries { self.expand(e, random, &mut candidates); @@ -901,7 +949,7 @@ impl LootContext<'_> { self.modifiers(&modifiers, &mut stack, random); produced.push(stack); } - fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut LegacyRandom) { + fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut impl RandomSource) { let list: Vec<&Value> = match m { Value::Array(a) => a.iter().collect(), Value::Object(_) => vec![m], diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a80d29b83..e6dd71e45 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -995,6 +995,18 @@ impl Mob { }, kind, }; + // setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay, + // Dolphin, Fox and Panda constructors. + mob.extra.pick_up_loot = matches!( + mob.species(), + Species::Villager + | Species::Piglin + | Species::PiglinBrute + | Species::Allay + | Species::Dolphin + | Species::Fox + | Species::Panda + ); ai::register(&mut mob); mob } @@ -1216,7 +1228,8 @@ impl Mob { /// Mob.playSound with LivingEntity.getVoicePitch. pub fn voice(&mut self, event: &'static str, events: &mut Vec) { let pitch = self.voice_pitch(); - let at = [self.position.x, self.eye_y(), self.position.z]; + // Entity.playSound: at the entity's feet. + let at = [self.position.x, self.position.y, self.position.z]; events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch)); } } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index be23ad75b..4d5c1307e 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -420,6 +420,10 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { // Entity.baseTick ends with Leashable.tickLeash. super::leash::tick(m, w, events); } +/// `Mob.playAmbientSound` on demand: a spawn egg or a mob bucket just placed `m`. +pub fn ambient_sound(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + play_ambient(m, w, events); +} fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let sound = match m.species() { // Warden.getAmbientSound: by anger, silent while roaring or digging. diff --git a/crates/horizon-world/src/level/buckets.rs b/crates/horizon-world/src/level/buckets.rs index 8fe4907a9..5bffd2e57 100644 --- a/crates/horizon-world/src/level/buckets.rs +++ b/crates/horizon-world/src/level/buckets.rs @@ -19,6 +19,10 @@ pub enum BucketContent { Fluid(FluidKind), /// `SolidBucketItem`: the block placed into an empty space (powder snow). Powder, + /// `MobBucketItem` holding water: its empty sound posts no `FLUID_PLACE`. + MobWater, + /// `MobBucketItem` without a fluid (the sulfur cube bucket): only the sound. + Nothing, } impl Sim<'_, L> { @@ -58,14 +62,23 @@ impl Sim<'_, L> { if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) { let snow = b.table.default_state(b.named.powder_snow); self.set_block_and_update(pos, snow); + // SolidBucketItem.emptyContents: one FLUID_PLACE, then the place sound. self.game_event(pos, "minecraft:fluid_place"); - self.empty_sound(pos, sound); + let sound: Arc = sound.into(); + self.sound(pos, &sound, 1.0, 1.0); return true; } return false; } + BucketContent::Nothing => { + let sound: Arc = sound.into(); + self.sound(pos, &sound, 1.0, 1.0); + return true; + } + BucketContent::MobWater => FluidKind::Water, BucketContent::Fluid(fluid) => fluid, }; + let mob = content == BucketContent::MobWater; let state = self.state(pos); // canBeReplaced(fluid): replaceable or not solid (portals refuse). let may_replace = !b.instance_of(state, Class::EndPortal) @@ -91,7 +104,7 @@ impl Sim<'_, L> { } if liquid_container && water { self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false)); - self.empty_sound(pos, sound); + self.empty_sound(pos, sound, mob); return true; } if may_replace && !b.instance_of(state, Class::Liquid) { @@ -112,13 +125,16 @@ impl Sim<'_, L> { { return false; } - self.empty_sound(pos, sound); + self.empty_sound(pos, sound, mob); true } - fn empty_sound(&mut self, pos: BlockPos, sound: &str) { + /// `playEmptySound`: `MobBucketItem` overrides it without the game event. + fn empty_sound(&mut self, pos: BlockPos, sound: &str, mob: bool) { let sound: Arc = sound.into(); self.sound(pos, &sound, 1.0, 1.0); - self.game_event(pos, "minecraft:fluid_place"); + if !mob { + self.game_event(pos, "minecraft:fluid_place"); + } } } diff --git a/crates/horizon-world/src/level/fluids.rs b/crates/horizon-world/src/level/fluids.rs index b778f6511..47558e52d 100644 --- a/crates/horizon-world/src/level/fluids.rs +++ b/crates/horizon-world/src/level/fluids.rs @@ -265,7 +265,9 @@ impl Sim<'_, L> { return false; } if b.is_block(state, b.named.powder_snow) { + // PowderSnowBlock.pickupBlock: the block breaks with its particles and sound. self.set_block(pos, b.air(), 11); + self.level_event(2001, pos, state.0 as i32); return true; } false diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 677b12a4b..ee1e3cdd9 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -452,9 +452,22 @@ impl Sim<'_, L> { // ---- misc helpers ---- - /// `BaseFireBlock.onPlace` (portal ignition is not modelled). + /// `BaseFireBlock.onPlace`: a fire inside an empty obsidian frame (in the + /// overworld or the nether) lights it, otherwise one that cannot survive + /// goes out. fn base_fire_on_place(&mut self, pos: BlockPos, state: BlockStateId, same: bool) { - if !same && !self.can_survive(state, pos) { + if same { + return; + } + if matches!( + self.level.dimension(), + super::Dimension::Overworld | super::Dimension::Nether + ) && let Some(shape) = self.find_empty_portal_shape(pos, true) + { + self.create_portal_blocks(&shape); + return; + } + if !self.can_survive(state, pos) { self.remove_block(pos, false); } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 166483709..5192ea0aa 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -549,6 +549,26 @@ impl Behaviours { ) -> bool { self.sim(level, ticks).player_destroy(pos, creative) } + /// `BaseFireBlock.getState(level, pos)`: soul fire on its base blocks, + /// otherwise fire shaped by its neighbours. + pub fn fire_state_for( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> BlockStateId { + self.sim(level, ticks).fire_state_for(pos) + } + /// `BaseFireBlock.canBePlacedAt(level, pos, forwardDirection)`. + pub fn fire_can_be_placed_at( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + forward: horizon_core::geometry::Direction, + ) -> bool { + self.sim(level, ticks).fire_can_be_placed_at(pos, forward) + } /// `BlockState.canSurvive(level, pos)`. pub fn can_survive( &self, diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs index 9ab3f8917..16b2aad5e 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -1595,6 +1595,29 @@ impl Behaviours { ) -> PlaceOutcome { self.sim(level, ticks).place(ctx) } + /// `DirectionalPlaceContext.canPlace`: whether the block at the clicked + /// position can be replaced by the item (a dispenser places only there). + pub fn directional_can_place( + &self, + level: &mut L, + ticks: &mut Ticks, + ctx: &PlaceContext, + ) -> bool { + let sim = self.sim(level, ticks); + let inner = Ctx { + pos: ctx.clicked_pos, + hit_pos: ctx.clicked_pos, + face: ctx.face, + hit: ctx.hit, + inside: ctx.inside, + yaw: ctx.yaw, + pitch: ctx.pitch, + sneaking: ctx.sneaking, + item: ctx.item.clone(), + replace_clicked: true, + }; + sim.can_be_replaced(sim.state(ctx.clicked_pos), &inner) + } /// The position and state `BlockItem.place` would place for `ctx`, without /// writing anything (None when vanilla's placement fails). pub fn placement_state( diff --git a/crates/horizon-world/src/level/portal.rs b/crates/horizon-world/src/level/portal.rs index 047f474d9..b59dd477c 100644 --- a/crates/horizon-world/src/level/portal.rs +++ b/crates/horizon-world/src/level/portal.rs @@ -1,7 +1,7 @@ //! `PortalShape`: the obsidian frame search used by nether portal blocks. use super::{LevelAccess, Sim, update::rel}; use crate::registry::BlockStateId; -use horizon_core::{geometry::Direction, position::BlockPos}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; const MIN_WIDTH: i32 = 2; const MAX_WIDTH: i32 = 21; @@ -126,4 +126,59 @@ impl Sim<'_, L> { }; shape } + /// `PortalShape.findEmptyPortalShape`: a valid frame holding no portal + /// block yet, on the preferred axis first. + pub fn find_empty_portal_shape(&self, pos: BlockPos, x_axis: bool) -> Option { + [x_axis, !x_axis] + .into_iter() + .map(|axis| self.find_portal_shape(pos, axis)) + .find(|shape| shape.is_valid() && shape.portal_blocks == 0) + } + /// `PortalShape.createPortalBlocks`: fill the frame (flags 18). + pub fn create_portal_blocks(&mut self, shape: &PortalShape) { + let b = self.b; + let base = b.default_of(b.named.nether_portal); + let state = b + .table + .with_text(base, b.props.axis, if shape.x_axis { "x" } else { "z" }) + .unwrap_or(base); + for h in 0..shape.height { + for w in 0..shape.width { + let at = step(step(shape.bottom_left, Direction::Up, h), shape.right, w); + self.set_block(at, state, 18); + } + } + } + /// `BaseFireBlock.canBePlacedAt(level, pos, forwardDirection)`: air where + /// fire would survive, or the inside of an empty portal frame (vertical + /// directions pick the frame axis with the level random). + pub fn fire_can_be_placed_at(&mut self, pos: BlockPos, forward: Direction) -> bool { + if !self.b.is_air(self.state(pos)) { + return false; + } + if self.can_survive(self.fire_state_for(pos), pos) { + return true; + } + // isPortal + if !matches!( + self.level.dimension(), + super::Dimension::Overworld | super::Dimension::Nether + ) { + return false; + } + for face in Direction::ALL { + if self.portal_frame(self.state(rel(pos, face))) { + // getCounterClockWise().getAxis(): north/south turn to X. + let x_axis = match forward { + Direction::North | Direction::South => true, + Direction::West | Direction::East => false, + Direction::Up | Direction::Down => { + self.random().next_int_bound(2).unwrap_or(0) == 0 + } + }; + return self.find_empty_portal_shape(pos, x_axis).is_some(); + } + } + false + } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java index 09d75a7d8..34cb8d05e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java @@ -30,6 +30,8 @@ public final class ParityData { public static RegistryAccess access; public static RegistryOps ops; public static ServerLevel level; + /** The loot tables of the vanilla data pack. */ + public static ReloadableServerRegistries.Holder loot; public static void init() throws Exception { SharedConstants.tryDetectVersion(); @@ -44,6 +46,7 @@ public final class ParityData { RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + loot = new ReloadableServerRegistries.Holder(loaded.lookupWithUpdatedTags()); lookup = loaded.lookupWithUpdatedTags(); var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); staticTags.forEach(Registry.PendingTags::apply); 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 046b2d399..606e2ae34 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -91,6 +91,12 @@ public final class VanillaBlockUpdateOracle { return old; } @Override + public void markUnsaved() { } + @Override + public BlockState getBlockState(BlockPos pos) { return world.getBlockState(pos); } + @Override + public FluidState getFluidState(BlockPos pos) { return world.getFluidState(pos); } + @Override public net.minecraft.world.level.chunk.status.ChunkStatus getPersistedStatus() { return net.minecraft.world.level.chunk.status.ChunkStatus.FULL; } @@ -145,6 +151,23 @@ public final class VanillaBlockUpdateOracle { } @Override public LevelChunk getChunkAt(BlockPos p) { return chunk; } @Override public LevelChunk getChunk(int x, int z) { return chunk; } + @Override public net.minecraft.world.level.chunk.ChunkAccess getChunk(int x, int z, net.minecraft.world.level.chunk.status.ChunkStatus status, boolean load) { return chunk; } + net.minecraft.server.waypoints.ServerWaypointManager waypoints; + @Override public net.minecraft.server.waypoints.ServerWaypointManager getWaypointManager() { + if (waypoints == null) waypoints = new net.minecraft.server.waypoints.ServerWaypointManager(); + return waypoints; + } + net.minecraft.server.ServerScoreboard scoreboard; + @Override public net.minecraft.server.ServerScoreboard getScoreboard() { + if (scoreboard == null) scoreboard = new net.minecraft.server.ServerScoreboard(server); + return scoreboard; + } + /** The biome every position reads (plains), for the oracles that load the world registries. */ + net.minecraft.core.Holder biome; + @Override public net.minecraft.core.Holder getBiome(BlockPos p) { + if (biome == null) biome = registryAccess().lookupOrThrow(net.minecraft.core.registries.Registries.BIOME).getOrThrow(net.minecraft.world.level.biome.Biomes.PLAINS); + return biome; + } @Override public boolean isLoaded(BlockPos p) { return true; } @Override public boolean hasChunkAt(BlockPos p) { return true; } @Override public boolean hasChunksAt(int x0, int z0, int x1, int z1) { return true; } @@ -160,7 +183,7 @@ public final class VanillaBlockUpdateOracle { @Override public LevelTicks getFluidTicks() { return fluidTicks; } @Override public void sendBlockUpdated(BlockPos p, BlockState a, BlockState b, int f) { } @Override public void setBlocksDirty(BlockPos p, BlockState a, BlockState b) { } - @Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); } + @Override public net.minecraft.core.RegistryAccess registryAccess() { return registries != null ? registries : RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); } @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; } @Override public GameRules getGameRules() { return rules; } @Override public net.minecraft.server.MinecraftServer getServer() { return server; } @@ -174,12 +197,51 @@ public final class VanillaBlockUpdateOracle { @Override public boolean isRainingAt(BlockPos p) { return raining; } @Override public boolean isUnobstructed(BlockState state, BlockPos pos, net.minecraft.world.phys.shapes.CollisionContext c) { return true; } @Override public boolean isUnobstructed(Entity entity) { return true; } - @Override public List getEntities(Entity except, AABB box, java.util.function.Predicate filter) { return List.of(); } - @Override public List getEntitiesOfClass(Class type, AABB box, java.util.function.Predicate filter) { return List.of(); } + // Entities exist only when a harness opts in (the dispenser oracle); + // they are searched in the order they were added, as within one entity section. + List entities; + net.minecraft.core.RegistryAccess registries; + @Override public List getEntities(Entity except, AABB box, java.util.function.Predicate filter) { + if (entities == null) return List.of(); + List out = new ArrayList<>(); + for (Entity e : List.copyOf(entities)) if (e != except && !e.isRemoved() && e.getBoundingBox().intersects(box) && filter.test(e)) out.add(e); + return out; + } + @Override public void getEntities(net.minecraft.world.level.entity.EntityTypeTest type, AABB box, java.util.function.Predicate filter, List out, int max) { + if (entities == null) return; + for (Entity e : List.copyOf(entities)) { + T t = type.tryCast(e); + if (t != null && !e.isRemoved() && e.getBoundingBox().intersects(box) && filter.test(t)) { + out.add(t); + if (out.size() >= max) return; + } + } + } + /** ServerLevel.getEntity(id) over the level's entities. */ + @Override public Entity getEntity(int id) { + if (entities == null) return null; + for (Entity e : entities) if (e.getId() == id && !e.isRemoved()) return e; + return null; + } + /** Every entity of the level (no area), as ServerLevel's entity getter would. */ + @Override public void getEntities(net.minecraft.world.level.entity.EntityTypeTest type, java.util.function.Predicate filter, List out, int max) { + if (entities == null) return; + for (Entity e : List.copyOf(entities)) { + T t = type.tryCast(e); + if (t != null && !e.isRemoved() && filter.test(t)) { + out.add(t); + if (out.size() >= max) return; + } + } + } + @Override public List getEntitiesOfClass(Class type, AABB box, java.util.function.Predicate filter) { + return getEntities(net.minecraft.world.level.entity.EntityTypeTest.forClass(type), box, filter); + } @Override public List players() { return List.of(); } @Override public net.minecraft.world.entity.player.Player getNearestPlayer(double x, double y, double z, double d, boolean b) { return null; } @Override public boolean addFreshEntity(Entity entity) { emit("E " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())); + if (entities != null) entities.add(entity); return true; } @Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); } @@ -187,7 +249,7 @@ public final class VanillaBlockUpdateOracle { emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location()); } @Override public void playSeededSound(Entity except, Entity src, net.minecraft.core.Holder sound, SoundSource source, float volume, float pitch, long seed) { - emit("S entity " + sound.value().location()); + emit("S " + (entities != null ? pos(BlockPos.containing(src.position())) : "entity") + " " + sound.value().location()); } @Override public void gameEvent(net.minecraft.core.Holder e, Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { emit("G " + pos(BlockPos.containing(p)) + " " + e.getRegisteredName()); @@ -252,6 +314,12 @@ public final class VanillaBlockUpdateOracle { return attributes; } @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; } + /** The overworld (fire in an obsidian frame lights a portal here). */ + @Override public net.minecraft.resources.ResourceKey dimension() { return net.minecraft.world.level.Level.OVERWORLD; } + @Override public long getOverworldClockTime() { return DAY.totalTicks(); } + @Override public float getMoonBrightness(BlockPos p) { + return net.minecraft.world.level.dimension.DimensionType.MOON_BRIGHTNESS_PER_PHASE[environmentAttributes().getValue(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, p).index()]; + } @Override public net.minecraft.world.level.storage.ServerLevelData getLevelData() { return LEVEL_DATA; } @Override public boolean anyPlayerCloseEnoughForSpawning(BlockPos p) { return false; } @Override public void playSound(Entity except, double x, double y, double z, SoundEvent sound, SoundSource source, float volume, float pitch) { @@ -339,13 +407,15 @@ public final class VanillaBlockUpdateOracle { static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder { World world; + /** The real loot tables, for the oracles that compare drops (the dispenser's). */ + net.minecraft.server.ReloadableServerRegistries.Holder delegate; Loot() { super(null); } @Override public net.minecraft.world.level.storage.loot.LootTable getLootTable(net.minecraft.resources.ResourceKey id) { world.emit("D " + id.identifier()); - return net.minecraft.world.level.storage.loot.LootTable.EMPTY; + return delegate != null ? delegate.getLootTable(id) : net.minecraft.world.level.storage.loot.LootTable.EMPTY; } } @@ -371,6 +441,12 @@ public final class VanillaBlockUpdateOracle { @Override public boolean isPublished() { return false; } @Override public boolean shouldInformAdmins() { return false; } @Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; } + net.minecraft.world.RandomSequences sequences; + /** Loot tables with a random_sequence draw from the server's sequences (world seed 0). */ + @Override public RandomSource getRandomSequence(net.minecraft.resources.Identifier key) { + if (sequences == null) sequences = new net.minecraft.world.RandomSequences(); + return sequences.get(key, 0L); + } } static List summary(World w, Map before) { @@ -441,8 +517,34 @@ public final class VanillaBlockUpdateOracle { return new BlockPos(a.get(0).getAsInt(), a.get(1).getAsInt(), a.get(2).getAsInt()); } + /** + * The chunk source bone meal reaches for: saplings, grass and moss place + * their features with `getChunkSource().getGenerator()`, which none of + * them reads beyond passing it along. + */ + static final class Chunks extends net.minecraft.server.level.ServerChunkCache { + static net.minecraft.world.level.chunk.ChunkGenerator generator; + + private Chunks() { + super(null, null, null, null, null, null, 0, 0, false, null); + } + + @Override + public net.minecraft.world.level.chunk.ChunkGenerator getGenerator() { + return generator; + } + + /** Leads send entity link packets; nobody is tracking. */ + @Override + public void sendToTrackingPlayers(final net.minecraft.world.entity.Entity entity, final net.minecraft.network.protocol.Packet packet) { + } + } + static World build(JsonObject f) throws Exception { World w = make(World.class); + // Saplings, grass and moss place features through the chunk source's generator. + if (Chunks.generator == null) Chunks.generator = make(net.minecraft.world.level.levelgen.FlatLevelSource.class); + set(net.minecraft.server.level.ServerLevel.class, w, "chunkSource", make(Chunks.class)); w.cells = new HashMap<>(); w.log = new StringBuilder(); w.blockEvents = new java.util.LinkedHashSet<>(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java new file mode 100644 index 000000000..26bb9a745 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -0,0 +1,288 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.NonNullList; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.Container; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.LegacyRandomSource; + +/** + * Drives vanilla `DispenserBlock.dispenseFrom` (and the dropper's) over the + * headless level of {@link VanillaBlockUpdateOracle}, with entities: the + * dispenser holds the case's items, target entities stand in front, and the + * result lists block changes, container contents, spawned entities with their + * position and motion, the targets' state afterwards, level events, sounds + * (those the client plays for level events included), game events and the + * level random. Every case runs three times: numbers that differ between the + * runs come from an entity's own unseeded random and are marked with "~". + * Used by tools/test_dispenser_parity.py. + */ +public final class VanillaDispenserOracle { + /** The sound LevelEventHandler plays for a level event a dispenser can cause, or null. */ + static String eventSound(int id, int data) { + return switch (id) { + case 1000 -> "minecraft:block.dispenser.dispense"; + case 1001 -> "minecraft:block.dispenser.fail"; + case 1002 -> "minecraft:block.dispenser.launch"; + case 1004 -> "minecraft:entity.firework_rocket.shoot"; + case 1018 -> "minecraft:entity.blaze.shoot"; + case 1051 -> "minecraft:entity.wind_charge.throw"; + case 1505 -> "minecraft:item.bone_meal.use"; + case 1501 -> "minecraft:block.lava.extinguish"; + case 1009 -> data == 0 ? "minecraft:block.fire.extinguish" : data == 1 ? "minecraft:block.generic.extinguish_fire" : null; + case 2001 -> { + BlockState state = Block.stateById(data); + yield state.isAir() ? null : state.getSoundType().getBreakSound().location().toString(); + } + default -> null; + }; + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + VanillaBlockUpdateOracle.AIR = Blocks.AIR.defaultBlockState(); + Path resources = Path.of(args[0]); + VanillaLevelShapeOracle.bindFluidTags(resources.resolve("data/minecraft/tags/fluid")); + VanillaBlockUpdateOracle.OVERWORLD_TYPE = VanillaBlockUpdateOracle.loadOverworld(); + var allocator = Class.forName("sun.misc.Unsafe"); + var field = allocator.getDeclaredField("theUnsafe"); + field.setAccessible(true); + VanillaBlockUpdateOracle.unsafe = field.get(null); + VanillaBlockUpdateOracle.allocate = allocator.getMethod("allocateInstance", Class.class); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) { + int index = 0; + for (var line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + // Three runs: a value from an unseeded random rarely repeats thrice. + List a = attempt(f), b = attempt(f), c = attempt(f); + out.print("case " + index++ + "\n"); + for (String s : merge(merge(a, b), c)) out.print(s + "\n"); + } + } + } + + static List attempt(JsonObject f) { + List result = new ArrayList<>(); + try { + run(f, result); + } catch (Throwable e) { + Throwable c = e; + while (c.getCause() != null) c = c.getCause(); + if (System.getenv("ORACLE_TRACE") != null) c.printStackTrace(); + StackTraceElement[] st = c.getStackTrace(); + result.clear(); + result.add("error " + c.getClass().getSimpleName() + " " + (st.length > 0 ? st[0].toString() : "") + " " + c.getMessage()); + } + return result; + } + + /** Lines equal in both runs stay; numbers that differ are marked "~" (from an unseeded entity random). */ + static List merge(List a, List b) { + if (a.size() != b.size()) return a; + List out = new ArrayList<>(); + for (int i = 0; i < a.size(); i++) { + String x = a.get(i), y = b.get(i); + if (x.equals(y)) { + out.add(x); + continue; + } + String[] p = x.split(" "), q = y.split(" "); + if (p.length != q.length) { + out.add(x); + continue; + } + // A token already marked in an earlier merge stays marked. + for (int j = 0; j < p.length; j++) if (!p[j].equals(q[j]) && !p[j].startsWith("~")) p[j] = "~" + p[j]; + out.add(String.join(" ", p)); + } + return out; + } + + static String num(double v) { + return String.format(Locale.ROOT, "%.6f", v); + } + + static ItemStack stack(String snbt) throws Exception { + return ParityData.stack(snbt); + } + + /** The item list of a container block entity (dispensers, droppers, chests, hoppers, barrels...). */ + @SuppressWarnings("unchecked") + static NonNullList slots(BlockEntity be) throws Exception { + for (Class c = be.getClass(); c != null; c = c.getSuperclass()) { + for (Field fd : c.getDeclaredFields()) { + if (fd.getType() == NonNullList.class && !java.lang.reflect.Modifier.isStatic(fd.getModifiers())) { + fd.setAccessible(true); + return (NonNullList) fd.get(be); + } + } + } + throw new IllegalStateException("no slots in " + be); + } + + static Method dispenseFrom(Class type) throws Exception { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + Method m = c.getDeclaredMethod("dispenseFrom", ServerLevel.class, BlockState.class, BlockPos.class); + m.setAccessible(true); + return m; + } catch (NoSuchMethodException ignored) { + } + } + throw new IllegalStateException("no dispenseFrom on " + type); + } + + static Entity target(VanillaBlockUpdateOracle.World w, JsonObject e) throws Exception { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(e.get("type").getAsString())); + Entity ent = type.create(w, EntitySpawnReason.COMMAND); + var p = e.getAsJsonArray("pos"); + ent.snapTo(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble(), e.has("yaw") ? e.get("yaw").getAsFloat() : 0f, 0f); + if (e.has("baby") && ent instanceof AgeableMob ageable) ageable.setAge(-24000); + if (e.has("tame")) { + if (ent instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); + if (ent instanceof TamableAnimal tamable) tamable.setTame(true, false); + } + if (e.has("sheared")) { + if (ent instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true); + if (ent instanceof net.minecraft.world.entity.monster.skeleton.Bogged bogged) bogged.setSheared(true); + if (ent instanceof net.minecraft.world.entity.animal.golem.SnowGolem golem) golem.setPumpkin(false); + } + if (e.has("chest") && ent instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested) chested.setChest(true); + if (e.has("loot") && ent instanceof Mob mob) mob.setCanPickUpLoot(true); + if (e.has("brown") && ent instanceof net.minecraft.world.entity.animal.cow.MushroomCow cow) { + Method variant = net.minecraft.world.entity.animal.cow.MushroomCow.class.getDeclaredMethod("setVariant", net.minecraft.world.entity.animal.cow.MushroomCow.Variant.class); + variant.setAccessible(true); + variant.invoke(cow, net.minecraft.world.entity.animal.cow.MushroomCow.Variant.BROWN); + } + // A target has lived in the level for a while: past its first tick, so + // equipping it plays the equip sound. + VanillaBlockUpdateOracle.set(Entity.class, ent, "firstTick", false); + if (e.has("equip") && ent instanceof LivingEntity living) { + for (var slot : e.getAsJsonObject("equip").entrySet()) { + living.setItemSlot(EquipmentSlot.byName(slot.getKey()), stack(slot.getValue().getAsString())); + } + // A target that has ticked since it was equipped has run + // collectEquipmentChanges (a sulfur cube takes its archetype then). + Map last = new EnumMap<>(EquipmentSlot.class); + for (EquipmentSlot slot : EquipmentSlot.values()) last.put(slot, ItemStack.EMPTY); + Method collect = LivingEntity.class.getDeclaredMethod("collectEquipmentChanges", Map.class); + collect.setAccessible(true); + collect.invoke(ent, last); + } + return ent; + } + + static void run(JsonObject f, List result) throws Exception { + VanillaBlockUpdateOracle.World w = VanillaBlockUpdateOracle.build(f); + w.entities = new ArrayList<>(); + w.registries = ParityData.access; + w.server.loot.delegate = ParityData.loot; + VanillaBlockUpdateOracle.set(Level.class, w, "damageSources", new net.minecraft.world.damagesource.DamageSources(ParityData.access)); + 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 (f.has("items")) { + for (var item : f.getAsJsonArray("items")) { + var it = item.getAsJsonArray(); + BlockPos at = new BlockPos(it.get(0).getAsInt(), it.get(1).getAsInt(), it.get(2).getAsInt()); + slots(w.getBlockEntity(at)).set(it.get(3).getAsInt(), stack(it.get(4).getAsString())); + } + } + if (f.has("entities")) { + List created = new ArrayList<>(); + for (var e : f.getAsJsonArray("entities")) { + Entity ent = target(w, e.getAsJsonObject()); + created.add(ent); + w.entities.add(ent); + } + var list = f.getAsJsonArray("entities"); + for (int i = 0; i < list.size(); i++) { + var e = list.get(i).getAsJsonObject(); + if (e.has("leash") && created.get(i) instanceof Leashable leashable) { + leashable.setLeashedTo(created.get(e.get("leash").getAsInt()), true); + } + } + } + // 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); + w.log = new StringBuilder(); + w.blockEvents.clear(); + Map before = new HashMap<>(w.cells); + List targets = List.copyOf(w.entities); + BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos")); + BlockState state = w.getBlockState(origin); + dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin); + + result.addAll(VanillaBlockUpdateOracle.summary(w, before)); + List containers = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); + containers.sort(Comparator.comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ())); + for (BlockPos at : containers) { + if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue; + var items = slots(w.blockEntities.get(at)); + for (int i = 0; i < items.size(); i++) { + if (!items.get(i).isEmpty()) result.add("inv " + VanillaBlockUpdateOracle.pos(at) + " " + i + " " + ParityData.canon(items.get(i))); + } + } + for (Entity e : w.entities) { + if (targets.contains(e)) continue; + StringBuilder line = new StringBuilder("N ").append(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType())); + line.append(' ').append(num(e.getX())).append(' ').append(num(e.getY())).append(' ').append(num(e.getZ())); + var v = e.getDeltaMovement(); + line.append(' ').append(num(v.x)).append(' ').append(num(v.y)).append(' ').append(num(v.z)); + if (e instanceof ItemEntity item) line.append(' ').append(ParityData.canon(item.getItem())); + if (e instanceof PrimedTnt tnt) line.append(" fuse=").append(tnt.getFuse()); + result.add(line.toString()); + } + for (int i = 0; i < targets.size(); i++) result.add(describe(i, targets.get(i))); + for (String s : w.log.toString().split("\n")) { + if (s.isEmpty() || s.startsWith("E ")) continue; + result.add(s); + if (s.startsWith("L ")) { + String[] p = s.split(" "); + String sound = eventSound(Integer.parseInt(p[1]), Integer.parseInt(p[3])); + if (sound != null) result.add("S " + p[2] + " " + sound); + } + } + result.addAll(w.blockEvents); + result.add("rng " + w.rng.nextLong()); + } + + /** A target's state after dispensing: removal, equipment and readiness for shearing. */ + static String describe(int index, Entity e) { + StringBuilder line = new StringBuilder("T " + index + " " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType())); + if (e.isRemoved()) line.append(" removed"); + if (e instanceof LivingEntity living) { + for (EquipmentSlot slot : EquipmentSlot.values()) { + ItemStack s = living.getItemBySlot(slot); + if (!s.isEmpty()) line.append(' ').append(slot.getName()).append('=').append(BuiltInRegistries.ITEM.getKey(s.getItem())).append('x').append(s.getCount()); + } + } + boolean listed = e instanceof net.minecraft.world.entity.animal.sheep.Sheep || e instanceof net.minecraft.world.entity.animal.cow.MushroomCow + || e instanceof net.minecraft.world.entity.monster.skeleton.Bogged || e instanceof net.minecraft.world.entity.animal.golem.SnowGolem; + if (listed && e instanceof Shearable shearable) line.append(shearable.readyForShearing() ? " ready" : " unready"); + if (e instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested && chested.hasChest()) line.append(" chest"); + if (e instanceof Leashable leashable && leashable.isLeashed()) line.append(" leashed"); + return line.toString(); + } +} diff --git a/tools/test_dispenser_parity.py b/tools/test_dispenser_parity.py new file mode 100644 index 000000000..61f74d496 --- /dev/null +++ b/tools/test_dispenser_parity.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""Compare vanilla dispensers and droppers with Horizon's, one activation per case. + +A dispenser or dropper at the origin faces a random direction and holds the +case's items; the block in front (and below it) comes from a palette of blocks +the behaviours care about, and some cases put a target entity in front. Vanilla +`DispenserBlock.dispenseFrom` runs over the headless level of the block update +oracle (`VanillaDispenserOracle`); Horizon runs its game glue in a headless game +(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, container contents, +spawned entities (type, position, motion), the targets afterwards, level events, +sounds, game events and the level random. Motion drawn from an entity's own +unseeded random (vanilla marks it "~") is compared within its spread. +""" +import json +import os +import random +import subprocess +try: + from . import block_update_harness as h, lab, test_rust_parity as base +except ImportError: + import block_update_harness as h + import lab + import test_rust_parity as base + +DIRECTIONS = ['down', 'up', 'north', 'south', 'west', 'east'] +STEP = {'down': (0, -1, 0), 'up': (0, 1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)} + + +def potion(item, name): + return '{id:"minecraft:%s",count:1,components:{"minecraft:potion_contents":{potion:"minecraft:%s"}}}' % (item, name) + + +def plain(item, count=1): + return '{id:"minecraft:%s",count:%d}' % (item, count) + + +WOODS = ['oak', 'spruce', 'birch', 'jungle', 'acacia', 'cherry', 'dark_oak', 'mangrove', 'pale_oak', 'poplar'] + +# Items with the blocks and entities in front that exercise their behaviour: +# one entry per DispenseItemBehavior.bootStrap registration family, plus the +# defaults of DispenserBlock.getDefaultDispenseMethod (equippables, sulfur +# cube swallowables, spawn eggs, a plain drop). +ITEMS = { + 'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2), plain('lead'), + plain('wheat_seeds', 7)], + 'projectile': [plain('arrow', 3), potion('tipped_arrow', 'poison'), plain('spectral_arrow'), plain('egg', 2), plain('blue_egg'), + plain('brown_egg'), plain('snowball', 4), plain('experience_bottle'), potion('splash_potion', 'healing'), + potion('lingering_potion', 'swiftness'), plain('firework_rocket', 2), plain('fire_charge', 2), plain('wind_charge', 3)], + 'bucket': [plain('water_bucket'), plain('lava_bucket'), plain('powder_snow_bucket'), plain('salmon_bucket'), plain('cod_bucket'), + plain('pufferfish_bucket'), plain('tropical_fish_bucket'), plain('axolotl_bucket'), plain('tadpole_bucket'), + plain('sulfur_cube_bucket'), plain('bucket'), plain('bucket', 3)], + 'block': [plain('bone_meal', 4), plain('tnt', 2), plain('flint_and_steel'), plain('glowstone', 3), plain('honeycomb', 2), + plain('glass_bottle', 2), potion('potion', 'water'), potion('potion', 'healing'), plain('shulker_box'), + plain('red_shulker_box'), plain('lime_shulker_box'), plain('carved_pumpkin'), plain('wither_skeleton_skull'), + plain('shears'), plain('brush')], + 'vehicle': [plain('oak_boat'), plain('bamboo_raft'), plain('bamboo_chest_raft'), plain('minecart'), plain('chest_minecart'), + plain('furnace_minecart'), plain('tnt_minecart'), plain('hopper_minecart'), plain('command_block_minecart'), + plain('armor_stand', 2), 'BOAT', 'CHEST_BOAT'], + 'spawn': [plain('pig_spawn_egg'), plain('sheep_spawn_egg', 2), plain('zombie_spawn_egg'), plain('cow_spawn_egg'), + plain('chicken_spawn_egg'), plain('skeleton_spawn_egg'), plain('creeper_spawn_egg'), plain('villager_spawn_egg'), + plain('wolf_spawn_egg'), plain('horse_spawn_egg'), plain('squid_spawn_egg'), plain('slime_spawn_egg')], + 'equipment': [plain('iron_helmet'), plain('diamond_chestplate'), plain('leather_leggings'), plain('golden_boots'), + plain('chainmail_helmet'), plain('netherite_boots'), plain('turtle_helmet'), plain('saddle'), + plain('iron_horse_armor'), plain('diamond_horse_armor'), plain('leather_horse_armor'), plain('white_carpet'), + plain('red_carpet'), plain('chest'), plain('carved_pumpkin'), plain('elytra'), plain('wolf_armor'), plain('shears'), + plain('brush'), plain('player_head'), plain('zombie_head'), plain('white_harness')], + 'swallow': [plain('slime_block'), plain('oak_planks', 3), plain('packed_ice'), plain('soul_sand'), plain('magma_block'), + plain('white_wool'), plain('mud', 2), plain('andesite'), plain('iron_block'), plain('mushroom_stem'), + plain('honeycomb_block'), plain('tube_coral_block'), plain('tnt'), plain('stone')], +} + +FRONT = { + 'drop': ['air', 'stone', 'water', 'chest', 'hopper'], + 'projectile': ['air', 'air', 'water', 'stone', 'glass'], + 'bucket': ['air', 'air', 'water', 'water', 'lava', 'powder_snow', 'oak_slab', 'seagrass', 'stone', 'cauldron', 'kelp', + 'grass_block', 'fire'], + 'block': ['air', 'grass_block', 'wheat', 'oak_sapling', 'tnt', 'campfire', 'candle', 'respawn_anchor', 'beehive', 'bee_nest', + 'copper_block', 'exposed_cut_copper_stairs', 'dirt', 'coarse_dirt', 'rooted_dirt', 'water', 'seagrass', 'stone', + 'sweet_berry_bush', 'cocoa', 'obsidian', 'soul_campfire', 'candle_cake', 'netherrack', 'moss_block'], + 'vehicle': ['air', 'air', 'water', 'rail', 'powered_rail', 'activator_rail', 'stone', 'detector_rail'], + 'spawn': ['air', 'air', 'water', 'stone', 'grass_block'], + 'equipment': ['air'], + 'swallow': ['air'], +} +# The blocks a behaviour reacts to, drawn for that item most of the time. +FRONT_FOR = { + 'flint_and_steel': ['air', 'air', 'air', 'campfire', 'soul_campfire', 'candle', 'blue_candle', 'candle_cake', + 'red_candle_cake', 'tnt', 'stone', 'obsidian', 'netherrack', 'water'], + 'glowstone': ['respawn_anchor', 'respawn_anchor', 'respawn_anchor', 'air', 'stone', 'glowstone'], + 'bone_meal': ['grass_block', 'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling', + 'cherry_sapling', 'mangrove_propagule', 'moss_block', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo', + 'pumpkin_stem', 'melon_stem', 'torchflower_crop', 'pitcher_crop', 'rooted_dirt', 'glow_lichen', 'small_dripleaf', + 'big_dripleaf', 'crimson_nylium', 'warped_fungus', 'brown_mushroom', 'kelp', 'sea_pickle', 'seagrass', 'water', + 'short_grass', 'fern', 'dandelion', 'pink_petals', 'cave_vines', 'twisting_vines', 'weeping_vines', 'azalea', + 'pale_moss_block', 'stone', 'air'], + 'honeycomb': ['copper_block', 'exposed_copper', 'weathered_cut_copper', 'oxidized_cut_copper_slab', 'copper_door', + 'exposed_copper_trapdoor', 'copper_bulb', 'lightning_rod', 'waxed_copper_block', 'copper_grate', 'stone', 'air'], + 'glass_bottle': ['beehive', 'beehive', 'bee_nest', 'bee_nest', 'water', 'water', 'air', 'stone', 'seagrass'], + 'potion': ['dirt', 'coarse_dirt', 'rooted_dirt', 'dirt', 'stone', 'air', 'mud', 'water'], + 'shears': ['beehive', 'bee_nest', 'beehive', 'air', 'air', 'stone', 'pumpkin'], + 'brush': ['air', 'air', 'suspicious_sand', 'stone'], + 'tnt': ['air', 'air', 'stone', 'water', 'tnt'], + 'shulker_box': ['air', 'air', 'stone', 'water', 'short_grass', 'snow'], + 'carved_pumpkin': ['air', 'air', 'stone', 'snow'], + 'wither_skeleton_skull': ['air', 'air', 'stone'], + 'armor_stand': ['air', 'air', 'stone', 'water', 'short_grass'], +} +# Structures a behaviour completes (golems, the wither, a nether portal). +SCENES = {'carved_pumpkin': ['snow_golem', 'iron_golem'], 'wither_skeleton_skull': ['wither'], 'flint_and_steel': ['portal']} +# Plants that need soil (or a log) under them to exist at all. +ROOTED = {'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling', 'cherry_sapling', + 'mangrove_propagule', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo', 'pumpkin_stem', 'melon_stem', + 'torchflower_crop', 'pitcher_crop', 'small_dripleaf', 'big_dripleaf', 'warped_fungus', 'brown_mushroom', 'kelp', + 'sea_pickle', 'seagrass', 'short_grass', 'fern', 'dandelion', 'pink_petals', 'twisting_vines', 'azalea'} +BELOW = ['air', 'stone', 'water', 'rail', 'grass_block', 'soul_sand', 'dirt', 'farmland', 'netherrack'] + +TARGETS = { + 'iron_helmet': ['zombie', 'skeleton', 'armor_stand', 'pig'], + 'chainmail_helmet': ['zombie', 'armor_stand', 'villager'], + 'diamond_chestplate': ['zombie', 'armor_stand'], + 'leather_leggings': ['skeleton', 'armor_stand'], + 'golden_boots': ['zombie', 'armor_stand'], + 'netherite_boots': ['zombie', 'piglin', 'armor_stand'], + 'turtle_helmet': ['armor_stand', 'zombie'], + 'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama', 'mule', 'skeleton_horse', 'nautilus'], + 'iron_horse_armor': ['horse', 'donkey'], + 'diamond_horse_armor': ['horse', 'zombie_horse'], + 'leather_horse_armor': ['horse'], + 'white_carpet': ['llama', 'horse', 'trader_llama'], + 'red_carpet': ['llama', 'trader_llama'], + 'chest': ['donkey', 'mule', 'llama', 'horse', 'trader_llama'], + 'carved_pumpkin': ['zombie', 'armor_stand', 'snow_golem'], + 'elytra': ['armor_stand', 'zombie'], + 'wolf_armor': ['wolf'], + 'white_harness': ['happy_ghast'], + 'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem', 'sulfur_cube', 'pig', 'cow'], + 'brush': ['armadillo'], + 'tnt': ['sulfur_cube'], + 'flint_and_steel': ['sulfur_cube'], + 'player_head': ['armor_stand', 'zombie'], + 'zombie_head': ['armor_stand', 'skeleton'], +} +for _block in ('stone', 'slime_block', 'oak_planks', 'packed_ice', 'soul_sand', 'magma_block', 'white_wool', 'mud', 'andesite', + 'iron_block', 'mushroom_stem', 'honeycomb_block', 'tube_coral_block'): + TARGETS[_block] = ['sulfur_cube'] +SWALLOWED = ['tnt', 'stone', 'slime_block', 'magma_block', 'white_wool', 'iron_block'] + + +def item_choice(rng, kind): + item = rng.choice(ITEMS[kind]) + if item == 'BOAT': + return plain(rng.choice(WOODS) + '_boat') + if item == 'CHEST_BOAT': + return plain(rng.choice(WOODS) + '_chest_boat') + return item + + +class States: + def __init__(self, facts): + self.facts = facts + + def get(self, name, **props): + name = name if ':' in name else 'minecraft:' + name + best = self.facts.defaults[name] + if not props: + return best + for index in self.facts.by_block[name]: + have = self.facts.states[index][4].get('properties', {}) + if all(have.get(k) == v for k, v in props.items()): + return index + raise KeyError((name, props)) + + def any(self, rng, name): + name = name if ':' in name else 'minecraft:' + name + return rng.choice(self.facts.by_block[name]) + + +def build_scene(cells, states, rng, scene, front, facing): + """Put the rest of a structure the behaviour's block completes around the front.""" + x, y, z = front + across = rng.choice([(1, 0, 0), (0, 0, 1)]) + + def put(at, name, **props): + if at != (0, 0, 0) and at != front: + h.put(cells, at, states.get(name, **props)) + + def side(at, k): + return (at[0] + across[0] * k, at[1], at[2] + across[2] * k) + if scene == 'snow_golem': + put((x, y - 1, z), 'snow_block') + put((x, y - 2, z), 'snow_block') + elif scene == 'iron_golem': + put((x, y - 1, z), 'iron_block') + put((x, y - 2, z), 'iron_block') + put(side((x, y - 1, z), -1), 'iron_block') + put(side((x, y - 1, z), 1), 'iron_block') + elif scene == 'wither': + put((x, y - 1, z), 'soul_sand') + put((x, y - 2, z), 'soul_sand') + put(side((x, y - 1, z), -1), rng.choice(['soul_sand', 'soul_soil'])) + put(side((x, y - 1, z), 1), 'soul_sand') + put(side((x, y, z), -1), 'wither_skeleton_skull') + put(side((x, y, z), 1), rng.choice(['wither_skeleton_skull', 'wither_skeleton_skull', 'skeleton_skull'])) + elif scene == 'portal': + # An obsidian frame around a 2x3 inside that holds the front block. + width, height = rng.choice([(2, 3), (2, 3), (3, 4)]) + left, low = rng.randrange(width), rng.randrange(height) + for i in range(-1, width + 1): + for j in range(-1, height + 1): + at = side((x, y + j - low, z), i - left) + edge = i in (-1, width) or j in (-1, height) + if edge and not (i in (-1, width) and j in (-1, height)): + put(at, 'obsidian') + elif not edge: + if at not in ((0, 0, 0), front): + h.put(cells, at, states.get('air')) + + +def halves(states, name): + """Whether a block comes in an upper and a lower half (tall plants, dripleaves, pitchers).""" + name = name if ':' in name else 'minecraft:' + name + return any(states.facts.states[i][4].get('properties', {}).get('half') == 'upper' for i in states.facts.by_block[name]) + + +def front_state(states, rng, name): + """Mostly the default state, sometimes a random one (charges, honey, ages, lit...).""" + if halves(states, name): + # A lone half is not a world vanilla makes; the pair is placed by put_front. + return states.get(name) + if name in ('respawn_anchor', 'beehive', 'bee_nest', 'campfire', 'candle', 'wheat', 'sweet_berry_bush', 'rail', 'powered_rail', + 'candle_cake', 'soul_campfire') or rng.random() < 0.3: + return states.any(rng, name) + return states.get(name) + + +def cases(facts, count, seed, only): + rng = random.Random(seed) + states = States(facts) + kinds = list(ITEMS) + for n in range(count): + kind = kinds[n % len(kinds)] + item = item_choice(rng, kind) + if only and only not in item: + continue + bare = item.split('"')[1].split(':')[1] + facing = rng.choice(DIRECTIONS) + block = 'dropper' if rng.random() < 0.12 else 'dispenser' + cells = [[0, 0, 0, states.get(block, facing=facing, triggered='false')]] + dx, dy, dz = STEP[facing] + front = (dx, dy, dz) + below = (dx, dy - 1, dz) + palette = FRONT_FOR[bare] if bare in FRONT_FOR and rng.random() < 0.8 else FRONT[kind] + front_name = rng.choice(palette) + if facing == 'up' and front_name in ROOTED: + # Nothing grows out of a dispenser: vanilla never lets these stand on one. + front_name = 'air' + above = (dx, dy + 1, dz) + if halves(states, front_name) and front_name != 'pitcher_crop': + if above == (0, 0, 0): + front_name = 'air' + else: + # The upper half matches the lower one in everything but its half. + lower = states.facts.states[states.get(front_name)][4].get('properties', {}) + h.put(cells, above, states.get(front_name, **{**lower, 'half': 'upper'})) + if front_name != 'air': + h.put(cells, front, front_state(states, rng, front_name)) + if below != (0, 0, 0) and rng.random() < 0.8: + name = rng.choice(BELOW) + if name != 'air': + h.put(cells, below, front_state(states, rng, name)) + scene = rng.choice(SCENES[bare]) if bare in SCENES and rng.random() < 0.45 else None + # A few random blocks around (portal frames, fire supports, neighbours). + for _ in range(rng.randrange(0, 6)): + at = (rng.randrange(-2, 3), rng.randrange(-2, 3), rng.randrange(-2, 3)) + if at in ((0, 0, 0), front): + continue + h.put(cells, at, states.get(rng.choice(['stone', 'obsidian', 'dirt', 'water', 'soul_sand', 'grass_block', 'oak_planks']))) + if scene: + build_scene(cells, states, rng, scene, front, facing) + items = [] + slots = rng.sample(range(9), rng.choice([1, 1, 1, 2, 3, 9])) + for i, slot in enumerate(slots): + items.append([0, 0, 0, slot, item if i == 0 or rng.random() < 0.6 else plain('cobblestone', rng.randrange(1, 65))]) + case = {**h.environment(rng), 'mode': 'dispense', 'pos': [0, 0, 0], 'cells': cells, 'items': items} + case.pop('raining', None) + case.pop('thundering', None) + if rng.random() < 0.08: + case['rules'] = {'tnt_explodes': False} + if kind in ('equipment', 'swallow') or (bare in TARGETS and rng.random() < 0.5): + entities = [] + for _ in range(rng.choice([1, 1, 1, 2])): + target = {'type': 'minecraft:' + rng.choice(TARGETS.get(bare, ['zombie'])), + 'pos': [dx + 0.5, dy + rng.choice([0.0, 0.0, 0.25]), dz + 0.5], 'yaw': rng.choice([0.0, 90.0, 180.0])} + for flag, odds in (('baby', 0.2), ('tame', 0.6), ('sheared', 0.25), ('chest', 0.15), ('loot', 0.5), ('brown', 0.3)): + if rng.random() < odds: + target[flag] = True + if target['type'] == 'minecraft:sulfur_cube' and rng.random() < 0.5: + target['equip'] = {'body': plain(rng.choice(SWALLOWED))} + # Leads: tied to an earlier target, or that target holds this one's. + holders = [i for i, e in enumerate(entities) if e['type'] != 'minecraft:armor_stand'] + if holders and rng.random() < 0.3: + target['leash'] = rng.choice(holders) + entities.append(target) + if bare == 'shears' and len(entities) == 1 and rng.random() < 0.3: + # A holder out of the dispenser's reach whose lead runs to the target. + entities.append({'type': 'minecraft:' + rng.choice(['cow', 'wolf']), 'pos': [dx + 3.5, dy, dz + 3.5], 'yaw': 0.0}) + entities[0]['leash'] = 1 + case['entities'] = entities + if block == 'dropper' and rng.random() < 0.5: + h.put(cells, front, states.get(rng.choice(['chest', 'hopper', 'barrel', 'dispenser']))) + if rng.random() < 0.5: + items.append([dx, dy, dz, 0, plain(rng.choice(['stone', 'diamond', 'stick']), rng.randrange(1, 65))]) + yield case + + +# Items whose behaviour runs Mob.finalizeSpawn (spawn eggs, mob buckets). The +# finalization draws belong to the entity spawning port; for these cases the +# level random's end state is not compared, everything else is. +FINALIZED = ('_spawn_egg', 'salmon_bucket', 'cod_bucket', 'pufferfish_bucket', 'tropical_fish_bucket', 'axolotl_bucket', + 'tadpole_bucket', 'sulfur_cube_bucket') + + +def finalizes(case): + return any(any(tag in i[4] for tag in FINALIZED) for i in case['items'] if i[:3] == [0, 0, 0]) + +def spawned_type(case): + item = next(i[4] for i in case['items'] if i[:3] == [0, 0, 0]).split('"')[1].split(':')[1] + return 'minecraft:' + item.removesuffix('_spawn_egg').removesuffix('_bucket') + + +def rider(line, spawned): + parts = line.split(' ') + return parts[0] == 'N' and parts[1] not in (spawned, 'minecraft:item') + + +def voice(line): + parts = line.split(' ') + if parts[0] == 'S' and len(parts) == 3 and parts[2].lstrip('~').startswith('minecraft:entity.'): + parts[2] = 'entity-voice' + return ' '.join(parts) + + +def run(command, **kwargs): + done = subprocess.run(command, capture_output=True, text=True, **kwargs) + if done.returncode: + print((done.stdout + done.stderr)[-4000:]) + raise SystemExit(f'{command[0]} failed') + return done + + +def numbers_close(java, rust): + """Token-wise equality; a "~" token is an unseeded entity draw and only needs to fall in its spread.""" + a, b = java.split(' '), rust.split(' ') + if len(a) != len(b): + return False + for x, y in zip(a, b): + if x.startswith('~'): + try: + # An item's own motion spans 0.2 per axis, and a shearing + # sheep pushes each wool with its own random by up to 0.1 more. + if abs(float(x[1:]) - float(y)) > 0.4: + return False + except ValueError: + return False + elif x != y: + return False + return True + + +def same(java, rust): + java = sorted(java) + rust = sorted(rust) + if len(java) != len(rust): + return False + pending = list(rust) + for line in java: + if line in pending: + pending.remove(line) + continue + if '~' not in line: + return False + match = next((r for r in pending if numbers_close(line, r)), None) + if match is None: + return False + pending.remove(match) + return True + + +def main(): + parser = h.argument_parser(__doc__) + args = parser.parse_args() + if args.count == 40000: + args.count = 6000 + lock, jars, libraries = base.verify_artifacts() + facts = h.load_facts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + work = lab.LOCAL / 'dispenser-parity' + work.mkdir(parents=True, exist_ok=True) + all_cases = list(cases(facts, args.count, args.seed, args.only)) + (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases)) + classes = work / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + java_root = lab.ROOT / 'mods/horizon/src/test/java' + run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn', + '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) + run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', + str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) + run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) + run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + # Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared. + ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) + native = h.split_cases((work / 'native.txt').read_text(), ignore) + rust = h.split_cases((work / 'rust.txt').read_text(), ignore) + assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) + groups, errors = {}, {} + unseeded = 0 + for case, a, b in zip(all_cases, native, rust): + if a and a[0].startswith('error'): + errors.setdefault(a[0], []).append(case) + continue + if finalizes(case): + unseeded += 1 + # Riders finalizeSpawn adds (a baby zombie's chicken, a spider's + # skeleton) depend on whether the mob came out a baby and on the + # jockey odds, both finalization draws: only the egg's own mob is compared. + spawned = spawned_type(case) + a = [line for line in a if not rider(line, spawned)] + b = [line for line in b if not rider(line, spawned)] + # EntityType.spawn plays the new mob's ambient sound: which one (a + # wolf pants or barks, in its sound variant) comes from the mob's + # own unseeded random, so only that a voice plays, and where, is compared. + a = [voice(line) for line in a if not line.startswith('rng ')] + b = [voice(line) for line in b if not line.startswith('rng ')] + if not same(a, b): + item = next(i[4] for i in case['items'] if i[:3] == [0, 0, 0]) + block = facts.states[case['cells'][0][3]][0].split(':')[1] + groups.setdefault(f'{block} {item.split(chr(34))[1]}', []).append((case, a, b)) + for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])): + print(f'oracle error x{len(entries)}: {kind}') + for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): + print(f'{name}: {len(entries)} differing') + for case, a, b in entries[:args.show]: + print(' case ' + describe(case, facts)) + print(' native ' + ' | '.join(sorted(a))) + print(' rust ' + ' | '.join(sorted(b))) + total = sum(len(v) for v in groups.values()) + skipped = sum(len(v) for v in errors.values()) + print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors; ' + f'{unseeded} spawning cases compared without the final level random)') + (work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in groups.items()})) + h.finish(total) + + +def describe(case, facts): + cells = ' '.join(f'{c[0]},{c[1]},{c[2]}={facts.describe(c[3])}' for c in case['cells']) + extra = '' + if case.get('entities'): + extra += ' entities=' + json.dumps(case['entities']) + if case.get('rules'): + extra += ' rules=' + json.dumps(case['rules']) + return f'{cells} items={json.dumps(case["items"])}{extra} seed={case["seed"]}' + + +if __name__ == '__main__': + main()