From f78de6d9aefcfab8163c0b629a863b10aced77bc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:24:03 +0200 Subject: [PATCH] WIP: unfinished blocks parity work, stopped for the night Uncommitted changes the agent had in progress when it was stopped; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 53 +- crates/horizon-client/src/game/boats.rs | 10 + .../src/game/dispense_fixture.rs | 449 +++++++++ crates/horizon-client/src/game/dispenser.rs | 937 +++++++++++++----- crates/horizon-client/src/game/fireworks.rs | 13 +- crates/horizon-client/src/game/potions.rs | 21 + crates/horizon-client/src/game/sculk.rs | 3 + crates/horizon-client/src/items.rs | 59 +- crates/horizon-client/src/mobs.rs | 3 +- crates/horizon-client/src/mobs/ai.rs | 4 + crates/horizon-world/src/level/buckets.rs | 26 +- crates/horizon-world/src/level/fluids.rs | 2 + .../dev/horizonlab/parity/ParityData.java | 3 + .../parity/VanillaBlockUpdateOracle.java | 67 +- .../parity/VanillaDispenserOracle.java | 271 +++++ tools/test_dispenser_parity.py | 303 ++++++ 16 files changed, 1931 insertions(+), 293 deletions(-) create mode 100644 crates/horizon-client/src/game/dispense_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java create mode 100644 tools/test_dispenser_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..c29b221d0 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; @@ -1050,8 +1051,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); } } @@ -1062,7 +1064,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]); @@ -1089,7 +1092,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, @@ -1102,23 +1106,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. @@ -1390,6 +1407,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 { @@ -1463,12 +1481,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); @@ -1777,12 +1790,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); @@ -8641,6 +8649,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..1bac6b220 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -95,6 +95,16 @@ impl Boat { } } /// Item id -> (boat entity id, wood). +impl Boat { + /// The vanilla entity type id (`oak_boat`, `bamboo_raft`). + pub(super) fn entity_type(&self) -> String { + if &*self.wood == "bamboo" { + "minecraft:bamboo_raft".to_owned() + } else { + format!("minecraft:{}_boat", self.wood) + } + } +} pub(super) fn boat_wood(item: &str) -> Option<&str> { let name = item.strip_prefix("minecraft:")?; name.strip_suffix("_boat") 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..011523f52 --- /dev/null +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -0,0 +1,449 @@ +//! 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); + for cx in -2..=2 { + for cz in -2..=2 { + self.world + .chunks + .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); + } + } + 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 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); + 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)?); + } + // 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"); + } + } + } + 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..6389ec791 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,221 @@ 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:entity.nautilus.saddle_underwater_equip".into() + } else { + "minecraft:entity.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 +358,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 +373,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 +454,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 +576,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 +588,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)?, @@ -387,10 +604,15 @@ impl Game<'_> { "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), + // BoatDispenseItemBehavior for chest boats: Horizon has no chest boat + // entity, so they always take its fallback (an inner default dispense). + _ if item.ends_with("_chest_boat") || item.ends_with("_chest_raft") => { + 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 +624,7 @@ impl Game<'_> { pos: Pos, facing: Direction, stack: ItemStack, - ) -> Dispensed { + ) -> Result { let equippable = self .res .items @@ -411,35 +633,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() @@ -487,135 +725,127 @@ impl Game<'_> { ]; self.spawn_mob(&name, at, true) } - /// `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 +868,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 +893,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 +936,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 +957,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 +973,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,14 +991,16 @@ 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 { @@ -860,17 +1107,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 +1140,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 +1161,14 @@ 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 +1188,7 @@ 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,6 +1212,32 @@ impl Game<'_> { let state = self.block_at(target); let name = self.dispenser_block_name(target); let mut success = true; + // 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) + } + _ => 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.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)); @@ -1018,10 +1305,29 @@ 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) } @@ -1169,13 +1475,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 +1502,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 +1510,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, @@ -1276,128 +1577,260 @@ 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) { 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::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; + let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; 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); - } - } - } - /// 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 +1855,17 @@ 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 +1888,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 +1905,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/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..65245eaab 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -437,6 +437,9 @@ 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/items.rs b/crates/horizon-client/src/items.rs index e0c5a0366..4912b5408 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -526,13 +526,23 @@ 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 +591,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 +642,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 +682,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 +713,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 +730,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 +839,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 +855,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 +913,7 @@ 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 +940,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 f46420cad..7e7d2843e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1162,7 +1162,8 @@ impl Mob { pub fn voice(&mut self, event: &'static str, events: &mut Vec) { let pitch = (self.random.next_float() - self.random.next_float()) * 0.2 + if self.is_baby() { 1.5 } else { 1.0 }; - 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 d27024f31..41033acfc 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -414,6 +414,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/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..21908b3e2 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,34 @@ 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; + } + } + } + @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 +232,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 +297,10 @@ public final class VanillaBlockUpdateOracle { return attributes; } @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; } + @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 +388,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 +422,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) { 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..ab6f97b8f --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -0,0 +1,271 @@ +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 twice: 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 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(); + List a = attempt(f), b = attempt(f); + out.print("case " + index++ + "\n"); + for (String s : merge(a, b)) 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(); + 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; + } + for (int j = 0; j < p.length; j++) if (!p[j].equals(q[j])) 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")) { + for (var e : f.getAsJsonArray("entities")) w.entities.add(target(w, e.getAsJsonObject())); + } + // 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"); + return line.toString(); + } +} diff --git a/tools/test_dispenser_parity.py b/tools/test_dispenser_parity.py new file mode 100644 index 000000000..c6e130697 --- /dev/null +++ b/tools/test_dispenser_parity.py @@ -0,0 +1,303 @@ +#!/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) + + +# Items with the blocks and entities in front that exercise their behaviour. +ITEMS = { + 'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2)], + '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('carved_pumpkin'), plain('wither_skeleton_skull'), plain('shears'), plain('brush')], + 'vehicle': [plain('oak_boat'), plain('bamboo_raft'), plain('minecart'), plain('chest_minecart'), + plain('furnace_minecart'), plain('tnt_minecart'), plain('hopper_minecart'), plain('armor_stand', 2)], + 'spawn': [plain('pig_spawn_egg'), plain('sheep_spawn_egg', 2), plain('zombie_spawn_egg'), plain('cow_spawn_egg'), plain('chicken_spawn_egg')], + 'equipment': [plain('iron_helmet'), plain('diamond_chestplate'), plain('leather_leggings'), plain('golden_boots'), + plain('turtle_helmet'), plain('saddle'), plain('iron_horse_armor'), plain('white_carpet'), plain('chest'), + plain('carved_pumpkin'), plain('elytra'), plain('wolf_armor'), plain('shears'), plain('brush'), plain('player_head')], +} + +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'], +} +BELOW = ['air', 'stone', 'water', 'rail', 'grass_block', 'soul_sand', 'dirt', 'farmland', 'netherrack'] + +TARGETS = { + 'iron_helmet': ['zombie', 'skeleton', 'armor_stand', 'pig'], + 'diamond_chestplate': ['zombie', 'armor_stand'], + 'leather_leggings': ['skeleton', 'armor_stand'], + 'golden_boots': ['zombie', 'armor_stand'], + 'turtle_helmet': ['armor_stand', 'zombie'], + 'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama'], + 'iron_horse_armor': ['horse', 'donkey'], + 'white_carpet': ['llama', 'horse', 'trader_llama'], + 'chest': ['donkey', 'mule', 'llama', 'horse'], + 'carved_pumpkin': ['zombie', 'armor_stand', 'snow_golem'], + 'elytra': ['armor_stand', 'zombie'], + 'wolf_armor': ['wolf'], + 'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem'], + 'brush': ['armadillo'], + 'tnt': ['sulfur_cube'], + 'flint_and_steel': ['sulfur_cube'], + 'stone': ['sulfur_cube'], + 'player_head': ['armor_stand', 'zombie'], +} + + +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 front_state(states, rng, name): + """Mostly the default state, sometimes a random one (charges, honey, ages, lit...).""" + 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 = rng.choice(ITEMS[kind]) + if only and only not in item: + continue + 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) + front_name = rng.choice(FRONT[kind]) + 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)) + # 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']))) + 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} + bare = item.split('"')[1].split(':')[1] + if kind == 'equipment' 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(['tnt', 'stone', 'slime_block']))} + entities.append(target) + 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 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: + if abs(float(x[1:]) - float(y)) > 0.25: + 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 = 3000 + 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.ROOT / '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 + # The spawned mob's variant (and so its voice) is chosen in finalizeSpawn too. + a = [line for line in a if not line.startswith('rng ') and not line.endswith('.ambient')] + b = [line for line in b if not line.startswith('rng ') and not line.endswith('.ambient')] + 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()