diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 46447eb1c..38478117c 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -208,6 +208,7 @@ impl BlockEntity { } let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, + n if n.ends_with("copper_chest") => 27, "minecraft:hopper" => 5, "minecraft:dispenser" | "minecraft:dropper" => 9, n if n.ends_with("shulker_box") => 27, @@ -219,6 +220,7 @@ impl BlockEntity { pub fn id_for_block(name: &str) -> Option<&'static str> { Some(match name { "minecraft:chest" => "minecraft:chest", + n if n.ends_with("copper_chest") => "minecraft:chest", "minecraft:trapped_chest" => "minecraft:trapped_chest", "minecraft:barrel" => "minecraft:barrel", "minecraft:hopper" => "minecraft:hopper", diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..d70d153c4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -75,6 +75,7 @@ mod sculk; mod shield; mod sign_edit; mod sniffers; +mod spill; mod station_control; mod stations; mod stats; @@ -322,6 +323,10 @@ struct GameLevel<'w> { items: &'w Items, registry: &'static horizon_world::registry::BlockRegistry, rules: horizon_world::level::GameRules, + /// Block loot random sequences (`ServerLevel.getRandomSequence`). + rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, + pending: &'w mut spill::Pending, + spill: &'w mut spill::Spill, } impl LevelAccess for GameLevel<'_> { fn precipitation(&self, pos: BlockPos) -> Option { @@ -465,7 +470,14 @@ impl LevelAccess for GameLevel<'_> { } } fn emit(&mut self, event: LevelEvent) { - self.events.push(event); + match event { + // Block.dropResources draws its loot and spots right away. + LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state), + event => self.events.push(event), + } + } + fn remove_block_entity(&mut self, pos: BlockPos, old: BlockStateId, side_effects: bool) { + self.remove_entity(pos, old, side_effects); } } /// FallingBlockEntity carrying a block state. @@ -702,12 +714,11 @@ struct Game<'a> { /// The ender inventory (27 slots) and the ender chest showing it. ender_items: Vec>, ender_open: Option<(i32, i32, i32)>, - /// Contents of broken shulker boxes waiting for their dropped item. - pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, - /// Layers of broken banners waiting for their dropped item. - pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, - /// Custom names of broken containers, for the dropped item (`copy_components`). - pending_names: HashMap<[i32; 3], (String, String)>, + /// Block entity data of broken blocks waiting for their dropped item. + pending: spill::Pending, + /// Item entities spawned and block entities removed while the block + /// behaviour ran (spilled contents, popped resources). + spill: spill::Spill, /// The recipe book of the open screen (game/recipe_book.rs). recipe_ui: recipe_book::RecipeUi, /// The horse inventory (game/mount_menu.rs). @@ -1078,33 +1089,36 @@ impl Game<'_> { } /// `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 { + fn block_loot_at( + &mut self, + pos: [i32; 3], + state: BlockStateId, + held: Option<&ItemStack>, + ) -> Vec { let registry = self.res.assets.registry; + let dynamic = self.pending.dynamic(pos); 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) + self.res + .items + .block_drops_with(registry, state, held, &dynamic, random) } - None => self - .res - .items - .block_drops(registry, state, held, &mut self.world.random), + None => self.res.items.block_drops_with( + registry, + state, + held, + &dynamic, + &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); + self.pending.attach(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 = || -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 p = spill::pop_position(&mut self.world.random, pos); let v = dispenser::new_item_motion(); self.spawn_item(stack, p, v, 10); } @@ -1266,8 +1280,13 @@ impl Game<'_> { items: &self.res.items, registry: self.res.assets.registry, rules, + rand_sequences: &mut self.rand_sequences, + pending: &mut self.pending, + spill: &mut self.spill, }; - f(&self.res.behaviours, &mut level, &mut self.block_ticks) + let result = f(&self.res.behaviours, &mut level, &mut self.block_ticks); + self.flush_spill(); + result } /// Level.setBlock(pos, state, UPDATE_ALL) with neighbour/shape updates. fn level_set(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { @@ -1452,18 +1471,9 @@ impl Game<'_> { }; self.audio.play(&name, Some(c), volume, pitch); } + // Handled as the behaviour emits it (GameLevel::emit). LevelEvent::DropResources { pos, state } => { - self.jukebox_removed([pos.x, pos.y, pos.z]); - if let Some(entity) = self.world.block_entities.remove(&(pos.x, pos.y, pos.z)) { - let name = self.res.facts.get(state).name.clone(); - self.release_contents([pos.x, pos.y, pos.z], entity, &name); - } - 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); - } - } + self.with_level(|_, level, _| level.drop_resources_now(pos, state)); } LevelEvent::FallingBlock { pos, state } => { let p = Vec3::new( @@ -1788,23 +1798,63 @@ impl Game<'_> { self.with_player_actor(|game| game.break_block_as_player(pos)) } fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { + // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); let facts = self.res.facts.get(state).clone(); // Block.playerWillDestroy: mining their gold angers all nearby piglins. if self.guarded_by_piglins(&facts.name) { self.anger_piglins(false); } - if !self.creative { - // Block.playerDestroy: the mined statistic and the exhaustion. - self.stats.add("mined", &facts.name, 1); - if let Some(p) = self.player.as_mut() { - p.health.food.exhaustion = (p.health.food.exhaustion + 0.005).min(40.0); - } + // The block entity as it was, for what the drops copy from it. + let key = (pos[0], pos[1], pos[2]); + if let Some(entity) = self.world.block_entities.get(&key).cloned() { + let name = self.world.block_names.get(&key).cloned(); + self.pending.record(pos, &entity, &facts.name, name); + } else if let Some(tag) = spill::saved_entity(&self.world, pos) { + self.pending.record_saved(pos, &tag); + } + self.creaking_heart_broken(pos); + // playerWillDestroy and Level.removeBlock through the vanilla behaviour + // library: the block entity's side effects (containers spill), neighbour + // and shape updates, and the destroy event (particles, sound). + let creative = self.creative; + let removed = self.with_level(|b, level, ticks| { + b.player_destroy_block( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + creative, + ) + }); + if removed && !creative { let held = self.held().cloned(); + // ItemStack.mineBlock: tools lose durability on blocks with nonzero hardness. + if facts.hardness > 0.0 + && let Some(stack) = self.inventory[self.selected].clone() + && let Some(max) = self + .res + .items + .get(&stack.item) + .filter(|i| i.max_damage > 0 && !i.tool.is_empty()) + .map(|i| i.max_damage) + { + let loss = self.durability_loss(&stack, 1); + if let Some(stack) = self.inventory[self.selected].as_mut() { + stack.damage += loss; + if stack.damage >= max { + self.inventory[self.selected] = None; + } + } + } let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); if harvest { - let drops = self.block_loot(state, held.as_ref()); + // Block.playerDestroy: the mined statistic, the exhaustion and the drops. + self.stats.add("mined", &facts.name, 1); + if let Some(p) = self.player.as_mut() { + p.health.food.exhaustion = (p.health.food.exhaustion + 0.005).min(40.0); + } + let drops = self.block_loot_at(pos, state, held.as_ref()); let silk = held .as_ref() .is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); @@ -1829,53 +1879,8 @@ impl Game<'_> { ); } } - // Tools lose durability on blocks with nonzero hardness. - if facts.hardness > 0.0 - && let Some(stack) = self.inventory[self.selected].clone() - && let Some(max) = self - .res - .items - .get(&stack.item) - .filter(|i| i.max_damage > 0 && !i.tool.is_empty()) - .map(|i| i.max_damage) - { - let loss = self.durability_loss(&stack, 1); - if let Some(stack) = self.inventory[self.selected].as_mut() { - stack.damage += loss; - if stack.damage >= max { - self.inventory[self.selected] = None; - } - } - } } - let replacement = if facts.waterlogged { - self.res.assets.registry.default_state("minecraft:water") - } else { - None - } - .unwrap_or(self.world.air); - self.creaking_heart_broken(pos); - if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) { - // Containers.dropContents (shulker boxes keep theirs). - let name = facts.name.clone(); - self.release_contents(pos, entity, &name); - if self.container == Some((pos[0], pos[1], pos[2])) { - self.container = None; - self.screen = Screen::Playing; - } - } - let _ = replacement; - // Block.playerDestroy through the vanilla behaviour library: removal, - // neighbour and shape updates, and the destroy event (particles, sound). - let creative = self.creative; - self.with_level(|b, level, ticks| { - b.player_destroy_block( - level, - ticks, - BlockPos::new(pos[0], pos[1], pos[2]), - creative, - ); - }); + self.pending.clear(pos); self.process_level_events()?; Ok(()) } @@ -5961,26 +5966,36 @@ impl Game<'_> { Ok(false) } /// ExperienceOrb.award: split into vanilla orb sizes. + /// `ExperienceOrb.award`: orbs of the largest sizes; each draws the id + /// `tryMergeToExisting` compares from the level random, then moves with + /// its own random. fn spawn_orbs(&mut self, at: [f64; 3], mut value: u32) { while value > 0 { let v = ExperienceOrb::split(value); value -= v; - let r = &mut self.world.random; - let p = Vec3::new(at[0], at[1], at[2]); - self.orbs.push(ExperienceOrb { - position: p, - previous: p, - velocity: Vec3::new( - (r.next_double() * 0.2 - 0.1) * 2.0, - r.next_double() * 0.2 * 2.0, - (r.next_double() * 0.2 - 0.1) * 2.0, - ), - value: v, - age: 0, - on_ground: false, - }); + let _merge_id = self.world.random.next_int_bound(40); + self.add_orb(at, v); } } + /// `new ExperienceOrb(level, pos, Vec3.ZERO, value)`: yaw and motion from + /// the orb's own random. + fn add_orb(&mut self, at: [f64; 3], value: u32) { + let mut r = dispenser::entity_random(); + let _yaw = r.next_float(); + let p = Vec3::new(at[0], at[1], at[2]); + self.orbs.push(ExperienceOrb { + position: p, + previous: p, + velocity: Vec3::new( + (r.next_double() * 0.2 - 0.1) * 2.0, + r.next_double() * 0.2 * 2.0, + (r.next_double() * 0.2 - 0.1) * 2.0, + ), + value, + age: 0, + on_ground: false, + }); + } /// DropExperienceBlock / RedStoneOreBlock / SculkBlock experience ranges. fn block_experience(&mut self, name: &str) -> u32 { let (min, max) = match name.trim_start_matches("minecraft:") { @@ -8101,9 +8116,8 @@ pub fn run() -> Result<()> { riding: None, ender_items: vec![None; 27], ender_open: None, - pending_shulker: HashMap::new(), - pending_banner: HashMap::new(), - pending_names: HashMap::new(), + pending: Default::default(), + spill: Default::default(), recipe_ui: Default::default(), mount_menu: Default::default(), hook: None, diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs index d767dc9b8..d3f0df42b 100644 --- a/crates/horizon-client/src/game/banners.rs +++ b/crates/horizon-client/src/game/banners.rs @@ -4,7 +4,7 @@ use super::Game; use horizon_client::{ banner::{self, BannerLayer}, - containers::{Banner, BlockEntity}, + containers::BlockEntity, items::ItemStack, }; @@ -19,7 +19,7 @@ impl Game<'_> { } /// A placed banner takes the item's layers and name. pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) { - self.pending_banner.remove(&pos); + self.pending.banner.remove(&pos); if !stack.item.ends_with("_banner") { return; } @@ -30,20 +30,6 @@ impl Game<'_> { b.name = stack.custom_name().map(str::to_owned); } } - /// The layers a banner dropped at `pos` carries. - pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) { - if !stack.item.ends_with("_banner") { - return; - } - if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) { - let data = stack.data_mut(); - data.banner_patterns = layers; - if name.is_some() { - data.custom_name = name; - } - stack.tidy(); - } - } } /// Texture names and tints of banner layers (`Sheets.getBannerSprite`). diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 2f0a7acc9..9ca51e066 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1317,13 +1317,12 @@ impl Game<'_> { self.res.facts.get(previous).name.clone(), self.res.facts.get(state).name.clone(), ); + // The command clears the old block entity without its side effects + // (UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS); the new block gets a fresh one. + let key = (pos[0], pos[1], pos[2]); if old != new { - let key = (pos[0], pos[1], pos[2]); self.jukebox_removed(pos); self.world.block_entities.remove(&key); - if let Some(entity) = horizon_client::containers::BlockEntity::for_block(&new) { - self.world.block_entities.insert(key, entity); - } } if strict { self.with_level(|b, level, ticks| { @@ -1342,6 +1341,12 @@ impl Game<'_> { self.level_set(pos, state) .map_err(|e| CommandError::new(Text::literal(e.to_string())))?; } + if old != new + && self.world.block(pos[0], pos[1], pos[2]) == state + && let Some(entity) = horizon_client::containers::BlockEntity::for_block(&new) + { + self.world.block_entities.insert(key, entity); + } Ok(true) } fn cmd_setblock(&mut self, ctx: &Context) -> R { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index a906ba259..8747b4c25 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -13,6 +13,7 @@ use horizon_client::{ containers::BlockEntity, gamerules::Value as RuleValue, item_data::{canon_stack, parse_stack}, + items::ItemStack, mobs::{Mob, Species}, projectiles::ProjectileKind, world::World, @@ -179,14 +180,7 @@ impl Game<'_> { ); 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; - } + self.fixture_fill(p, slot, stack); } let mut targets = Vec::new(); for e in case["entities"].as_array().into_iter().flatten() { @@ -225,7 +219,11 @@ impl Game<'_> { 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)?; + if let Some(op) = case.get("remove") { + self.fixture_remove(origin, op)?; + } else { + 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(); @@ -241,7 +239,11 @@ impl Game<'_> { containers.sort_unstable(); for p in containers { let entity = &self.world.block_entities[&p]; - for (i, slot) in entity.slots().iter().enumerate() { + let single = match entity { + BlockEntity::Jukebox(j) => std::slice::from_ref(&j.record), + _ => entity.slots(), + }; + for (i, slot) in single.iter().enumerate() { if let Some(stack) = slot { out.push(format!( "inv {},{},{} {i} {}", @@ -266,6 +268,112 @@ impl Game<'_> { Ok(out) } + /// A stack in a block entity's slot: a container's, a jukebox's record, a + /// lectern's book, or the items of a block entity Horizon keeps as saved. + fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { + let jukebox = + &*self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox"; + match self.world.block_entities.get_mut(&p) { + Some(BlockEntity::Jukebox(j)) => j.record = stack, + Some(BlockEntity::Lectern(l)) => l.book = stack, + Some(e) => { + if let Some(cell) = e.slots_mut().get_mut(slot) { + *cell = stack; + } + } + None if jukebox => { + // JukeboxBlockEntity holding its record (setSongItemWithoutPlaying). + self.world.block_entities.insert( + p, + BlockEntity::Jukebox(horizon_client::containers::Jukebox { + record: stack, + ticks: 0, + playing: false, + }), + ); + } + None => self.fixture_fill_saved(p, slot, stack), + } + } + /// The saved block entity of a campfire, decorated pot, chiseled + /// bookshelf or shelf, as a loaded world keeps it. + fn fixture_fill_saved(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { + use horizon_world::nbt::Tag; + let name = self + .res + .facts + .get(self.world.block(p.0, p.1, p.2)) + .name + .clone(); + let id = match name.strip_prefix("minecraft:").unwrap_or(&name) { + "campfire" | "soul_campfire" => "minecraft:campfire", + "decorated_pot" => "minecraft:decorated_pot", + "chiseled_bookshelf" => "minecraft:chiseled_bookshelf", + n if n.ends_with("_shelf") => "minecraft:shelf", + _ => return, + }; + let Some(chunk) = self.world.chunks.get_mut(&(p.0 >> 4, p.2 >> 4)) else { + return; + }; + let chunk = Arc::make_mut(chunk); + let saved = Arc::make_mut(chunk.saved.get_or_insert_with(Default::default)); + let at = |t: &Tag| { + t.get("x") == Some(&Tag::Int(p.0)) + && t.get("y") == Some(&Tag::Int(p.1)) + && t.get("z") == Some(&Tag::Int(p.2)) + }; + let index = match saved.block_entities.iter().position(at) { + Some(i) => i, + None => { + saved.block_entities.push(Tag::compound([ + ("id", Tag::String(id.into())), + ("x", Tag::Int(p.0)), + ("y", Tag::Int(p.1)), + ("z", Tag::Int(p.2)), + ])); + saved.block_entities.len() - 1 + } + }; + let Tag::Compound(map) = &mut saved.block_entities[index] else { + return; + }; + let Some(stack) = stack else { return }; + if id == "minecraft:decorated_pot" { + map.insert("item".into(), horizon_client::save::item_to_nbt(&stack)); + return; + } + let mut item = horizon_client::save::item_to_nbt(&stack); + if let Tag::Compound(c) = &mut item { + c.insert("Slot".into(), Tag::Byte(slot as i8)); + } + match map + .entry("Items".into()) + .or_insert_with(|| Tag::List(Vec::new())) + { + Tag::List(list) => list.push(item), + other => *other = Tag::List(vec![item]), + } + } + /// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block. + fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> { + match op["op"].as_str().unwrap_or("") { + "set" => { + let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32); + let flags = op["flags"].as_i64().unwrap_or(3) as i32; + self.with_level(|b, level, ticks| b.set_block(level, ticks, origin, state, flags)); + } + "destroy" => { + let drop = op["drop"].as_bool().unwrap_or(true); + self.with_level(|b, level, ticks| b.destroy_block(level, ticks, origin, drop)); + } + "remove" => { + self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false)); + } + other => return Err(format!("unknown removal {other}").into()), + } + self.process_level_events() + } + /// `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"); @@ -502,6 +610,15 @@ impl Game<'_> { let (p, v) = (b.position, b.velocity); out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], "")); } + for o in &self.orbs { + let (p, v) = (o.position, o.velocity); + out.push(line( + "minecraft:experience_orb", + [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/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 4bd13bd15..9024b557c 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -390,17 +390,29 @@ impl Game<'_> { } let name = self.res.facts.get(state).name.clone(); let is_tnt = &*name == "minecraft:tnt"; + // Block.onExplosionHit: the drops copy from the block entity, which + // then spills its contents as the block turns to air. + let key = (pos[0], pos[1], pos[2]); + if let Some(entity) = self.world.block_entities.get(&key).cloned() { + let custom = self.world.block_names.get(&key).cloned(); + self.pending.record(pos, &entity, &name, custom); + } else if let Some(tag) = super::spill::saved_entity(&self.world, pos) { + self.pending.record_saved(pos, &tag); + } if !is_tnt { - let drops = self.res.items.block_drops( + let dynamic = self.pending.dynamic(pos); + let drops = self.res.items.block_drops_with( self.res.assets.registry, state, None, + &dynamic, &mut self.world.random, ); - for stack in drops { + for mut stack in drops { if &*stack.item == "minecraft:air" || stack.count == 0 { continue; } + self.pending.attach(pos, &mut stack); // survives_explosion / explosion_decay: 1 / radius per stack. if interaction == BlockInteraction::DestroyWithDecay && self.world.random.next_float() > 1.0 / radius @@ -410,17 +422,8 @@ impl Game<'_> { add_or_append_stack(stacks, stack, pos); } } - let contents = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); - let name = self - .res - .facts - .get(self.world.block(pos[0], pos[1], pos[2])) - .name - .clone(); + self.pending.clear(pos); self.level_set(pos, self.world.air)?; - if let Some(entity) = contents { - self.release_contents(pos, entity, &name); - } if is_tnt { self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true); } diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index f721e2352..6e2bcbfd4 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -126,16 +126,13 @@ impl Game<'_> { }; self.stop_song(pos); if let Some(record) = record { - let r = &mut self.world.random; - // offsetRandomXZ(random, 0.7) - let dx = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0; - let dz = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0; - let at = [ - f64::from(pos[0]) + 0.5 + dx, - f64::from(pos[1]) + 1.01, - f64::from(pos[2]) + 0.5 + dz, - ]; - self.spawn_item(record, at, [0.0, 0.0, 0.0], 10); + // atLowerCornerWithOffset(pos, 0.5, 1.01, 0.5).offsetRandomXZ(random, 0.7); + // `new ItemEntity` moves it with its own random. + let at = horizon_world::level::removal::jukebox_pop_position( + &mut self.world.random, + horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]), + ); + self.spawn_item(record, at, super::dispenser::new_item_motion(), 10); } self.set_has_record(pos, false); self.jukebox_changed(pos); diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs new file mode 100644 index 000000000..34b145420 --- /dev/null +++ b/crates/horizon-client/src/game/spill.rs @@ -0,0 +1,441 @@ +//! Block entities removed by the block behaviour (`LevelChunk.setBlockState` +//! running `BlockEntity.preRemoveSideEffects`) and the resources a destroyed +//! block drops (`Block.dropResources`), drawn from the level random at the +//! moment vanilla draws them. The item entities they make are added to the +//! world as soon as the behaviour returns, within the same tick. +use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box}; +use horizon_client::{ + containers::{Banner, BlockEntity}, + items::ItemStack, +}; +use horizon_core::position::BlockPos; +use horizon_core::random::RandomSource; +use horizon_world::{ + level::removal::{self, PreRemove}, + registry::BlockStateId, +}; +use std::collections::HashMap; + +/// What a broken block's entity gives its own dropped item (`copy_components` +/// in the block loot tables): a shulker box's contents, a banner's layers, a +/// container's custom name. +#[derive(Default)] +pub(super) struct Pending { + pub(super) shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, + pub(super) banner: HashMap<[i32; 3], Banner>, + /// The block's item and the custom name. + pub(super) names: HashMap<[i32; 3], (String, String)>, + /// A decorated pot's sherds (back, left, right, front). + pub(super) pot: HashMap<[i32; 3], [Option; 4]>, +} +impl Pending { + /// Remember what the block entity at `pos` copies into the drops of `block`. + pub(super) fn record( + &mut self, + pos: [i32; 3], + entity: &BlockEntity, + block: &str, + name: Option, + ) { + if let BlockEntity::Banner(banner) = entity { + self.banner.insert(pos, banner.clone()); + return; + } + if let Some(name) = name { + self.names.insert(pos, (block.to_owned(), name)); + } + if is_shulker_box(block) + && let BlockEntity::Chest(items) = entity + { + let kept = items + .iter() + .enumerate() + .filter_map(|(i, s)| Some((i as u8, s.clone()?))) + .collect(); + self.shulker.insert(pos, kept); + } + } + /// Copy what was remembered for `pos` into a drop of the block. + pub(super) fn attach(&mut self, pos: [i32; 3], stack: &mut ItemStack) { + if is_shulker_box(&stack.item) + && let Some(contents) = self.shulker.remove(&pos) + && !contents.is_empty() + { + stack.data_mut().container = contents; + } + if self + .names + .get(&pos) + .is_some_and(|(item, _)| **item == *stack.item) + && let Some((_, name)) = self.names.remove(&pos) + { + stack.data_mut().custom_name = Some(name); + } + if &*stack.item == "minecraft:decorated_pot" { + // The pot's block entity always copies its decorations, empty or not. + let sides = self.pot.remove(&pos).unwrap_or_default(); + stack.data_mut().pot_decorations = Some(Box::new(sides)); + } + if stack.item.ends_with("_banner") + && let Some(Banner { layers, name }) = self.banner.remove(&pos) + { + let data = stack.data_mut(); + data.banner_patterns = layers; + if name.is_some() { + data.custom_name = name; + } + stack.tidy(); + } + } + /// Remember a decorated pot's sherds from its saved block entity. + pub(super) fn record_saved(&mut self, pos: [i32; 3], tag: &horizon_world::nbt::Tag) { + use horizon_world::nbt::Tag; + if tag.get("id") != Some(&Tag::String("minecraft:decorated_pot".into())) { + return; + } + let sherds = tag.get("sherds"); + let side = |name: &str| match sherds.and_then(|s| s.get(name)) { + Some(Tag::String(id)) => Some(ItemStack { + item: std::sync::Arc::from(id.to_string_lossy().as_str()), + count: 1, + damage: 0, + extra: None, + }), + Some(t) => horizon_client::save::item_from_nbt(t), + None => None, + }; + self.pot.insert( + pos, + [side("back"), side("left"), side("right"), side("front")], + ); + } + /// The block entity's dynamic drops: a decorated pot's sherds, left, + /// back, front then right (`DecoratedPotBlock.getDrops`). + pub(super) fn dynamic(&self, pos: [i32; 3]) -> Vec { + self.pot + .get(&pos) + .map_or_else(Vec::new, |[back, left, right, front]| { + [left, back, front, right] + .into_iter() + .flatten() + .cloned() + .collect() + }) + } + pub(super) fn clear(&mut self, pos: [i32; 3]) { + self.pot.remove(&pos); + self.shulker.remove(&pos); + self.banner.remove(&pos); + self.names.remove(&pos); + } +} + +/// An item entity to add: where, its motion (None: `new ItemEntity`'s own +/// random motion) and its pickup delay. +pub(super) struct Spawn { + pub(super) stack: ItemStack, + pub(super) pos: [f64; 3], + pub(super) motion: Option<[f64; 3]>, + pub(super) delay: u32, +} + +#[derive(Default)] +pub(super) struct Spill { + pub(super) spawns: Vec, + /// Experience orbs (`ExperienceOrb.award`): where and how much, each + /// having drawn its merge id from the level random. + pub(super) orbs: Vec<([f64; 3], u32)>, + /// Block entities the behaviour removed, for the game's own follow-ups + /// (open screens, playing songs). + pub(super) removed: Vec<([i32; 3], BlockEntity)>, +} + +/// `Block.popResource`: a spot around the block's centre from the level random. +pub(super) fn pop_position( + random: &mut impl horizon_core::random::RandomSource, + pos: [i32; 3], +) -> [f64; 3] { + let mut offset = || -0.25 + random.next_double() * 0.5; + // EntityTypes.ITEM is 0.25 high. + let half_height = f64::from(0.25f32) / 2.0; + [ + f64::from(pos[0]) + 0.5 + offset(), + f64::from(pos[1]) + 0.5 + offset() - half_height, + f64::from(pos[2]) + 0.5 + offset(), + ] +} + +/// The block entity at `pos` Horizon keeps as it was loaded, if any +/// (campfires, decorated pots, chiseled bookshelves, shelves). +pub(super) fn saved_entity( + world: &horizon_client::world::World, + pos: [i32; 3], +) -> Option { + use horizon_world::nbt::Tag; + let saved = world + .chunks + .get(&(pos[0] >> 4, pos[2] >> 4))? + .saved + .as_ref()?; + saved + .block_entities + .iter() + .find(|t| { + t.get("x") == Some(&Tag::Int(pos[0])) + && t.get("y") == Some(&Tag::Int(pos[1])) + && t.get("z") == Some(&Tag::Int(pos[2])) + }) + .cloned() +} + +impl GameLevel<'_> { + /// `Block.popResource(level, pos, stack)` with the broken block's copied components. + fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { + self.pending.attach(pos, &mut stack); + let at = pop_position(&mut self.world.random, pos); + self.spill.spawns.push(Spawn { + stack, + pos: at, + motion: None, + delay: 10, + }); + } + /// `Block.dropResources(state, level, pos, blockEntity)`: the block's loot + /// (from its random sequence, else the level random), with what its block + /// entity copies into it, popped at once. + pub(super) fn drop_resources_now(&mut self, pos: BlockPos, state: BlockStateId) { + let key = (pos.x, pos.y, pos.z); + let at = [pos.x, pos.y, pos.z]; + if let Some(entity) = self.world.block_entities.get(&key) { + let entity = entity.clone(); + let name = self.world.block_names.get(&key).cloned(); + let block = self.facts.get(state).name.clone(); + self.pending.record(at, &entity, &block, name); + } else if let Some(tag) = saved_entity(self.world, [pos.x, pos.y, pos.z]) { + self.pending.record_saved(at, &tag); + } + let dynamic = self.pending.dynamic(at); + let drops = match self.items.block_loot_sequence(self.registry, state) { + Some(sequence) => { + let random = self.rand_sequences.get(&sequence, self.seed); + self.items + .block_drops_with(self.registry, state, None, &dynamic, random) + } + None => self.items.block_drops_with( + self.registry, + state, + None, + &dynamic, + &mut self.world.random, + ), + }; + for stack in drops { + if &*stack.item != "minecraft:air" && stack.count > 0 { + self.pop_resource(at, stack); + } + } + self.pending.clear(at); + // BlockBehaviour.spawnAfterBreak with no tool: ores, sculk and spawners + // award experience at the block's centre. + let name = self.facts.get(state).name.clone(); + if let Some(xp) = removal::break_experience(&mut self.world.random, &name) + && self.rules.block_drops + { + let centre = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + self.award_orbs(centre, xp); + } + } + /// `ExperienceOrb.award`: orbs of the largest sizes, each drawing the id + /// `tryMergeToExisting` compares from the level random. + pub(super) fn award_orbs(&mut self, at: [f64; 3], mut amount: u32) { + while amount > 0 { + let value = removal::orb_value(amount); + amount -= value; + let _merge_id = self.world.random.next_int_bound(40); + self.spill.orbs.push((at, value)); + } + } + /// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block + /// entity of `old` at `pos`. A block entity Horizon never created reads as + /// vanilla's fresh one: an empty container still draws a spot per slot. + pub(super) fn remove_entity(&mut self, pos: BlockPos, old: BlockStateId, side_effects: bool) { + let key = (pos.x, pos.y, pos.z); + if self.remove_saved_entity(pos, old, side_effects) { + return; + } + // Sculk blocks and creaking hearts notice their removal on their own tick. + if matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sculk(_) | BlockEntity::CreakingHeart(_)) + ) { + return; + } + let entity = self.world.block_entities.remove(&key); + self.world.block_names.remove(&key); + if side_effects { + let name = self.facts.get(old).name.clone(); + match removal::pre_remove(&name) { + PreRemove::Contents { slots, .. } => { + let items = entity.as_ref().map_or(&[][..], BlockEntity::slots); + for slot in 0..slots { + let stack = items.get(slot).cloned().flatten(); + self.drop_item_stack(pos, stack); + } + } + PreRemove::Campfire => { + for _ in 0..4 { + self.drop_item_stack(pos, None); + } + } + PreRemove::Jukebox => { + if let Some(BlockEntity::Jukebox(j)) = &entity + && let Some(record) = j.record.clone() + { + let at = removal::jukebox_pop_position(&mut self.world.random, pos); + self.spill.spawns.push(Spawn { + stack: record, + pos: at, + motion: None, + delay: 10, + }); + } + } + PreRemove::Lectern => { + let props = self.registry.state(old).map(|s| &s.properties); + let has_book = props + .and_then(|p| p.get("has_book")) + .is_some_and(|v| v == "true"); + let step = match props.and_then(|p| p.get("facing")).map(String::as_str) { + Some("north") => [0, -1], + Some("south") => [0, 1], + Some("west") => [-1, 0], + _ => [1, 0], + }; + if has_book + && let Some(BlockEntity::Lectern(l)) = &entity + && let Some(book) = l.book.clone() + { + self.spill.spawns.push(Spawn { + stack: book, + pos: removal::lectern_book_position(pos, step), + motion: None, + delay: 10, + }); + } + } + PreRemove::ShulkerBox + | PreRemove::SculkShrieker + | PreRemove::CreakingHeart + | PreRemove::Nothing => {} + } + } + if let Some(entity) = entity { + self.spill.removed.push(([pos.x, pos.y, pos.z], entity)); + } + } + /// A block entity Horizon keeps as it was loaded (campfires, decorated + /// pots, chiseled bookshelves, shelves): its items spill as vanilla's do. + fn remove_saved_entity( + &mut self, + pos: BlockPos, + old: BlockStateId, + side_effects: bool, + ) -> bool { + use horizon_world::nbt::Tag; + let chunk_key = (pos.x >> 4, pos.z >> 4); + let at = |t: &Tag| { + let int = |k: &str| match t.get(k) { + Some(Tag::Int(v)) => Some(*v), + _ => None, + }; + int("x") == Some(pos.x) && int("y") == Some(pos.y) && int("z") == Some(pos.z) + }; + let Some(chunk) = self.world.chunks.get_mut(&chunk_key) else { + return false; + }; + let Some(saved) = chunk.saved.as_ref() else { + return false; + }; + let Some(index) = saved.block_entities.iter().position(at) else { + return false; + }; + let chunk = std::sync::Arc::make_mut(chunk); + let Some(saved) = chunk.saved.as_mut() else { + return false; + }; + let tag = std::sync::Arc::make_mut(saved).block_entities.remove(index); + if !side_effects { + return true; + } + let name = self.facts.get(old).name.clone(); + let items = match removal::pre_remove(&name) { + PreRemove::Contents { slots, .. } if &*name == "minecraft:decorated_pot" => { + let mut items = vec![None; slots]; + items[0] = tag + .get("item") + .and_then(horizon_client::save::item_from_nbt); + items + } + PreRemove::Contents { slots, .. } => { + horizon_client::save::decode_items(tag.get("Items"), slots) + } + PreRemove::Campfire => horizon_client::save::decode_items(tag.get("Items"), 4), + _ => return true, + }; + for stack in items { + self.drop_item_stack(pos, stack); + } + true + } + /// `Containers.dropItemStack` of one slot (an empty one still draws its spot). + fn drop_item_stack(&mut self, pos: BlockPos, stack: Option) { + let count = stack.as_ref().map_or(0, |s| s.count); + for piece in removal::drop_item_stack(&mut self.world.random, pos, count) { + let Some(stack) = &stack else { break }; + self.spill.spawns.push(Spawn { + stack: ItemStack { + count: piece.count, + ..stack.clone() + }, + pos: piece.pos, + motion: Some(piece.motion), + delay: 0, + }); + } + } +} + +impl Game<'_> { + /// Add the item entities the block behaviour spawned and follow up on the + /// block entities it removed. + pub(super) fn flush_spill(&mut self) { + if self.spill.spawns.is_empty() + && self.spill.removed.is_empty() + && self.spill.orbs.is_empty() + { + return; + } + let spill = std::mem::take(&mut self.spill); + for s in spill.spawns { + let motion = s.motion.unwrap_or_else(new_item_motion); + self.spawn_item(s.stack, s.pos, motion, s.delay); + } + for (at, value) in spill.orbs { + self.add_orb(at, value); + } + for (pos, entity) in spill.removed { + let key = (pos[0], pos[1], pos[2]); + if matches!(entity, BlockEntity::Jukebox(_)) { + self.jukebox_removed(pos); + } + if self.container == Some(key) { + self.container = None; + self.screen = Screen::Playing; + } + } + } +} diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 2cb6d40a0..7017b2f5f 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -8,58 +8,6 @@ pub(super) fn is_shulker_box(name: &str) -> bool { name.ends_with("shulker_box") } impl Game<'_> { - /// Block-entity contents on removal: shulker boxes keep theirs for the - /// dropped box (`copy_components`), other containers spill them. - pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) { - if let Some(name) = self - .world - .block_names - .remove(&(pos[0], pos[1], pos[2])) - .filter(|_| !matches!(entity, BlockEntity::Banner(_))) - { - self.pending_names.insert(pos, (block.to_owned(), name)); - } - if let BlockEntity::Banner(banner) = entity { - self.pending_banner.insert(pos, banner); - return; - } - if is_shulker_box(block) { - if let BlockEntity::Chest(items) = entity { - let kept = items - .into_iter() - .enumerate() - .filter_map(|(i, s)| Some((i as u8, s?))) - .collect(); - self.pending_shulker.insert(pos, kept); - } - return; - } - for stack in entity.contents() { - self.pop_resource(pos, stack); - } - } - /// The contents a shulker box dropped at `pos` carries. - pub(super) fn attach_shulker_contents(&mut self, pos: [i32; 3], stack: &mut ItemStack) { - if !is_shulker_box(&stack.item) { - return; - } - if let Some(contents) = self.pending_shulker.remove(&pos) - && !contents.is_empty() - { - stack.data_mut().container = contents; - } - } - /// The custom name a broken container drops with (`copy_components`). - pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) { - if self - .pending_names - .get(&pos) - .is_some_and(|(item, _)| **item == *stack.item) - && let Some((_, name)) = self.pending_names.remove(&pos) - { - stack.data_mut().custom_name = Some(name); - } - } /// A placed container takes the item's custom name. pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) { let key = (pos[0], pos[1], pos[2]); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index bfecad8ad..3ddaff6de 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -158,6 +158,8 @@ pub struct ItemStack { /// Components beyond count and damage (see `item_data`); None when default. pub extra: Option>, } +/// Item ids standing for a loot table's `minecraft:dynamic` entries. +const DYNAMIC: &str = "#dynamic:"; pub struct Items { pub items: HashMap, ItemInfo>, pub order: Vec>, @@ -547,6 +549,40 @@ impl Items { state: BlockStateId, held: Option<&ItemStack>, random: &mut impl RandomSource, + ) -> Vec { + self.block_drops_with(registry, state, held, &[], random) + } + /// `block_drops` with the block entity's dynamic drops (`LootParams.withDynamicDrop`: + /// a decorated pot's sherds) in place of the `minecraft:dynamic` entries. + pub fn block_drops_with( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + dynamic: &[ItemStack], + random: &mut impl RandomSource, + ) -> Vec { + let drops = self.block_drops_raw(registry, state, held, random); + if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { + return drops; + } + drops + .into_iter() + .flat_map(|d| { + if d.item.starts_with(DYNAMIC) { + dynamic.to_vec() + } else { + vec![d] + } + }) + .collect() + } + fn block_drops_raw( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + random: &mut impl RandomSource, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -901,6 +937,21 @@ impl LootContext<'_> { } true } + // DynamicLoot: what the block entity adds (a cracked decorated + // pot's sherds), filled in by `block_drops_with`. + "minecraft:dynamic" => { + out.push(( + e["weight"].as_i64().unwrap_or(1) as i32, + ItemStack { + item: Arc::from(format!("{DYNAMIC}{}", e["name"].as_str().unwrap_or(""))), + count: 1, + damage: 0, + extra: None, + }, + Value::Null, + )); + true + } "minecraft:empty" => { out.push(( e["weight"].as_i64().unwrap_or(1) as i32, diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index 9590c90bb..e9aa90366 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -11,6 +11,7 @@ use horizon_world::{ level::{ Behaviours, Dimension, EntityQuery, GameRules, LevelAccess, LevelEvent, Ticks, data::load_registry, + removal::{PreRemove, drop_item_stack, pre_remove}, }, registry::BlockStateId, }; @@ -34,6 +35,8 @@ struct Cells { events: Vec, command_blocks: HashMap, lecterns_with_books: std::rc::Rc>, + /// `preRemoveSideEffects` of each state's block entity. + removals: std::rc::Rc>, } impl LevelAccess for Cells { fn block_state(&self, pos: BlockPos) -> BlockStateId { @@ -109,6 +112,30 @@ impl LevelAccess for Cells { fn emit(&mut self, event: LevelEvent) { self.events.push(event); } + /// The oracle level's block entities are fresh: containers spill only + /// empty slots (which still draw their spot), a lectern whose state has a + /// book drops its empty book, a fresh shrieker has no warning level. + fn remove_block_entity(&mut self, pos: BlockPos, old: BlockStateId, side_effects: bool) { + if !side_effects { + return; + } + let slots = match self.removals.get(old.0 as usize) { + Some(PreRemove::Contents { slots, .. }) => *slots, + Some(PreRemove::Campfire) => 4, + Some(PreRemove::Lectern) if self.lecterns_with_books.contains(&old) => { + self.events.push(LevelEvent::BlockEvent { + pos, + state: old, + kind: "spawn_item", + }); + return; + } + _ => return, + }; + for _ in 0..slots { + drop_item_stack(&mut self.random, pos, 0); + } + } } fn pos_of(value: &Value) -> BlockPos { @@ -161,6 +188,15 @@ fn main() -> Result<(), Box> { }) .collect(), ); + let removals: std::rc::Rc> = std::rc::Rc::new( + (0..registry.len() as u32) + .map(|id| { + registry + .state(BlockStateId(id)) + .map_or(PreRemove::Nothing, |s| pre_remove(&s.name)) + }) + .collect(), + ); let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); for (index, line) in std::io::BufReader::new(std::fs::File::open(cases)?) .lines() @@ -202,6 +238,7 @@ fn main() -> Result<(), Box> { events: Vec::new(), command_blocks: HashMap::new(), lecterns_with_books: lecterns_with_books.clone(), + removals: removals.clone(), }; let mut ticks = Ticks::new(0); for x in -3..=3 { @@ -328,6 +365,11 @@ fn main() -> Result<(), Box> { LevelEvent::PrimeTnt { .. } => { let _ = writeln!(result, "E minecraft:tnt"); } + LevelEvent::BlockEvent { + kind: "spawn_item", .. + } => { + let _ = writeln!(result, "E minecraft:item"); + } LevelEvent::GameEvent { pos, event, .. } => { let _ = writeln!(result, "G {} {}", p(*pos), event); } diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 3c62a39a4..455a2ed57 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -477,6 +477,8 @@ tags! { mushroom_grow_block = "mushroom_grow_block", guarded_by_piglins = "guarded_by_piglins", copper = "copper", + copper_chests = "copper_chests", + copper_golem_statues = "copper_golem_statues", } /// Property keys interned at load. diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 5192ea0aa..7a2255278 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -115,6 +115,7 @@ mod portal; mod query; mod rails; mod redstone; +pub mod removal; pub mod sculk; mod shapes; mod shelf; @@ -383,6 +384,12 @@ pub trait LevelAccess { true } fn emit(&mut self, _event: LevelEvent) {} + /// `LevelChunk.setBlockState` replaced a block that had a block entity by + /// another block: run `BlockEntity.preRemoveSideEffects` when + /// `side_effects` (containers spill their contents, a jukebox pops its + /// record, a lectern its book...) and remove the block entity. Called + /// after the storage write, before `affectNeighborsAfterRemoval`. + fn remove_block_entity(&mut self, _pos: BlockPos, _old: BlockStateId, _side_effects: bool) {} /// Biome identifier at `pos` (`minecraft:plains`), for features placed by /// block behaviour (bone meal flowers). None when unknown. fn biome_name(&self, _pos: BlockPos) -> Option<&str> { diff --git a/crates/horizon-world/src/level/removal.rs b/crates/horizon-world/src/level/removal.rs new file mode 100644 index 000000000..d873d9fc0 --- /dev/null +++ b/crates/horizon-world/src/level/removal.rs @@ -0,0 +1,159 @@ +//! What vanilla's `BlockEntity.preRemoveSideEffects` does when a block with a +//! block entity is replaced by another block (`LevelChunk.setBlockState` +//! without `UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS`), and the item spill of +//! `Containers.dropItemStack` those side effects use. +use horizon_core::{position::BlockPos, random::RandomSource}; + +/// `preRemoveSideEffects` of the block entity of a block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreRemove { + /// No side effect (signs, banners, beacons, skulls, ...). + Nothing, + /// `Containers.dropContents(level, pos, container)`: every slot, empty or + /// not, through `Containers.dropItemStack` (chests, barrels, hoppers, + /// dispensers, droppers, brewing stands, crafters, chiseled bookshelves, + /// shelves, decorated pots). Furnaces also award their recipes' experience. + Contents { slots: usize, furnace: bool }, + /// `CampfireBlockEntity`: `Containers.dropContents(level, pos, items)`. + Campfire, + /// `ShulkerBoxBlockEntity`: keeps its contents for the dropped box. + ShulkerBox, + /// `JukeboxBlockEntity.popOutTheItem`. + Jukebox, + /// `LecternBlockEntity`: the book, when the state has one. + Lectern, + /// `SculkShriekerBlockEntity.tryRespond` while shrieking. + SculkShrieker, + /// `CreakingHeartBlockEntity.removeProtector`. + CreakingHeart, +} + +/// The side effect of removing the block entity of block `name` (a +/// `minecraft:` identifier). +pub fn pre_remove(name: &str) -> PreRemove { + let n = name.strip_prefix("minecraft:").unwrap_or(name); + let contents = |slots| PreRemove::Contents { + slots, + furnace: false, + }; + match n { + "chest" | "trapped_chest" | "barrel" => contents(27), + _ if n.ends_with("copper_chest") => contents(27), + _ if n.ends_with("shulker_box") => PreRemove::ShulkerBox, + "hopper" => contents(5), + "dispenser" | "dropper" | "crafter" => contents(9), + "brewing_stand" => contents(5), + "chiseled_bookshelf" => contents(6), + _ if n.ends_with("_shelf") => contents(3), + "decorated_pot" => contents(1), + "furnace" | "blast_furnace" | "smoker" => PreRemove::Contents { + slots: 3, + furnace: true, + }, + "campfire" | "soul_campfire" => PreRemove::Campfire, + "jukebox" => PreRemove::Jukebox, + "lectern" => PreRemove::Lectern, + "sculk_shrieker" => PreRemove::SculkShrieker, + "creaking_heart" => PreRemove::CreakingHeart, + _ => PreRemove::Nothing, + } +} + +/// One item entity of a spill: position, stack size and motion. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Spilled { + pub pos: [f64; 3], + pub count: u32, + pub motion: [f64; 3], +} + +/// `Containers.dropItemStack(level, pos.x, pos.y, pos.z, stack)` for a stack +/// of `count` items: the spot inside the block, then pieces of 10 to 30 items +/// with triangular motions, all from the level random. An empty stack still +/// draws the spot. +pub fn drop_item_stack(random: &mut R, pos: BlockPos, count: u32) -> Vec { + // EntityTypes.ITEM is 0.25 wide. + let size = f64::from(0.25f32); + let center_range = 1.0 - size; + let half = size / 2.0; + let x = f64::from(pos.x) + random.next_double() * center_range + half; + let y = f64::from(pos.y) + random.next_double() * center_range; + let z = f64::from(pos.z) + random.next_double() * center_range + half; + let mut left = count; + let mut out = Vec::new(); + while left > 0 { + let piece = (random.next_int_bound(21).unwrap_or(0) + 10) as u32; + let piece = piece.min(left); + left -= piece; + let deviation = 0.114_850_001_711_398_36; + let motion = [ + random.triangle(0.0, deviation), + random.triangle(0.2, deviation), + random.triangle(0.0, deviation), + ]; + out.push(Spilled { + pos: [x, y, z], + count: piece, + motion, + }); + } + out +} + +/// `JukeboxBlockEntity.popOutTheItem`: `Vec3.atLowerCornerWithOffset(pos, 0.5, +/// 1.01, 0.5).offsetRandomXZ(level.random, 0.7)`. +pub fn jukebox_pop_position(random: &mut R, pos: BlockPos) -> [f64; 3] { + let dx = f64::from((random.next_float() - 0.5) * 0.7); + let dz = f64::from((random.next_float() - 0.5) * 0.7); + [ + f64::from(pos.x) + 0.5 + dx, + f64::from(pos.y) + 1.01, + f64::from(pos.z) + 0.5 + dz, + ] +} + +/// `LecternBlockEntity.preRemoveSideEffects`: the book a quarter block +/// towards the lectern's facing, one block up (`step` is the facing's x and z). +pub fn lectern_book_position(pos: BlockPos, step: [i32; 2]) -> [f64; 3] { + let xo = 0.25f32 * step[0] as f32; + let zo = 0.25f32 * step[1] as f32; + [ + f64::from(pos.x) + 0.5 + f64::from(xo), + f64::from(pos.y + 1), + f64::from(pos.z) + 0.5 + f64::from(zo), + ] +} + +/// `BlockBehaviour.spawnAfterBreak`'s experience for block `name` broken with +/// an unenchanted tool: `DropExperienceBlock` ranges (a `UniformInt` draws +/// `nextInt(max - min + 1) + min`, a `ConstantInt` draws nothing), redstone +/// ores, the sculk family and spawners. None when the block gives none. +pub fn break_experience(random: &mut R, name: &str) -> Option { + let n = name.strip_prefix("minecraft:").unwrap_or(name); + let mut uniform = |min: i32, max: i32| random.next_int_bound(max - min + 1).unwrap_or(0) + min; + let xp = match n { + "coal_ore" | "deepslate_coal_ore" => uniform(0, 2), + "nether_gold_ore" => uniform(0, 1), + "lapis_ore" | "deepslate_lapis_ore" | "nether_quartz_ore" => uniform(2, 5), + "diamond_ore" | "deepslate_diamond_ore" | "emerald_ore" | "deepslate_emerald_ore" => { + uniform(3, 7) + } + "redstone_ore" | "deepslate_redstone_ore" => uniform(1, 5), + "sculk" => 1, + "sculk_catalyst" | "sculk_sensor" | "calibrated_sculk_sensor" | "sculk_shrieker" => 5, + "spawner" => { + let a = random.next_int_bound(15).unwrap_or(0); + 15 + a + random.next_int_bound(15).unwrap_or(0) + } + _ => return None, + }; + (xp > 0).then_some(xp as u32) +} + +/// `ExperienceOrb.getExperienceValue`: the largest orb size not above `value`. +pub fn orb_value(value: u32) -> u32 { + [2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1] + .into_iter() + .find(|&v| value >= v) + .unwrap_or(1) +} diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index 15117c890..203718080 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -320,6 +320,14 @@ impl Sim<'_, L> { // PistonMovingBlockEntity.preRemoveSideEffects -> finalTick; the // block is already replaced, so only the entity goes away. self.remove_moving_piston(pos); + } else if block_changed + && self.b.has_flag(old, super::data::state_flags::BLOCK_ENTITY) + && !self.keeps_block_entity(state, old) + { + // BlockEntity.preRemoveSideEffects (unless UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS) + // and removeBlockEntity, before the neighbours hear of the removal. + let side_effects = update_flags & flags::UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS == 0; + self.level.remove_block_entity(pos, old, side_effects); } let moved = update_flags & flags::UPDATE_MOVE_BY_PISTON != 0; if (block_changed @@ -339,6 +347,14 @@ impl Sim<'_, L> { } Some(old) } + /// `BlockState.shouldChangedStateKeepBlockEntity(oldState)`: copper chests + /// and copper golem statues keep theirs across their weathering states. + fn keeps_block_entity(&self, new: BlockStateId, old: BlockStateId) -> bool { + let (new, old) = (self.block_of(new), self.block_of(old)); + let tags = &self.b.tags; + (tags.copper_chests.contains(new) && tags.copper_chests.contains(old)) + || (tags.copper_golem_statues.contains(new) && tags.copper_golem_statues.contains(old)) + } /// `Level.removeBlock`. pub fn remove_block(&mut self, pos: BlockPos, moved_by_piston: bool) -> bool { let fluid = self.fluid_at(pos); 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 606e2ae34..06f0a88c1 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -79,6 +79,16 @@ public final class VanillaBlockUpdateOracle { Block newBlock = state.getBlock(); boolean blockChanged = !old.is(newBlock); boolean movedByPiston = (flags & 64) != 0; + boolean sideEffects = (flags & 256) == 0; + if (blockChanged && old.hasBlockEntity() && !state.shouldChangedStateKeepBlockEntity(old)) { + if (sideEffects) { + BlockEntity blockEntity = world.blockEntityFor(pos.immutable(), old); + if (blockEntity != null) { + blockEntity.preRemoveSideEffects(pos, old); + } + } + if (world.blockEntities != null) world.blockEntities.remove(pos); + } if ((blockChanged || newBlock instanceof net.minecraft.world.level.block.BaseRailBlock) && ((flags & 1) != 0 || movedByPiston)) { old.affectNeighborsAfterRemoval(world, pos, movedByPiston); } @@ -133,7 +143,10 @@ public final class VanillaBlockUpdateOracle { // one creates it on first use and replaces it when the block changes. Map blockEntities; @Override public BlockEntity getBlockEntity(BlockPos p) { - BlockState state = getBlockState(p); + return blockEntityFor(p, getBlockState(p)); + } + /** The block entity at `p` for `state` (the block there, or the one being replaced). */ + BlockEntity blockEntityFor(BlockPos p, BlockState state) { if (!(state.getBlock() instanceof net.minecraft.world.level.block.EntityBlock entityBlock)) { return null; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 26bb9a745..c9aca25ee 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -138,6 +138,49 @@ public final class VanillaDispenserOracle { throw new IllegalStateException("no slots in " + be); } + /** Put a stack in a slot: the item list of a container, else the one item a block entity holds (jukebox, lectern, decorated pot). */ + static void setSlot(BlockEntity be, int slot, ItemStack stack) 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); + @SuppressWarnings("unchecked") NonNullList list = (NonNullList) fd.get(be); + list.set(slot, stack); + return; + } + } + } + for (Class c = be.getClass(); c != null; c = c.getSuperclass()) { + for (Field fd : c.getDeclaredFields()) { + if (fd.getType() == ItemStack.class && !java.lang.reflect.Modifier.isStatic(fd.getModifiers())) { + fd.setAccessible(true); + fd.set(be, stack); + return; + } + } + } + throw new IllegalStateException("no slots in " + be); + } + + /** The removal a "remove" case runs on the block at its origin. */ + static void remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) { + switch (op.get("op").getAsString()) { + case "set" -> w.setBlock(origin, Block.stateById(op.get("state").getAsInt()), op.get("flags").getAsInt()); + case "destroy" -> w.destroyBlock(origin, op.get("drop").getAsBoolean()); + case "remove" -> w.removeBlock(origin, false); + default -> throw new IllegalStateException(op.toString()); + } + } + + static boolean hasList(Object be) { + 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())) return true; + } + } + return false; + } + static Method dispenseFrom(Class type) throws Exception { for (Class c = type; c != null; c = c.getSuperclass()) { try { @@ -205,7 +248,7 @@ public final class VanillaDispenserOracle { 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())); + setSlot(w.getBlockEntity(at), it.get(3).getAsInt(), stack(it.get(4).getAsString())); } } if (f.has("entities")) { @@ -232,14 +275,18 @@ public final class VanillaDispenserOracle { 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); + if (f.has("remove")) { + remove(w, origin, f.getAsJsonObject("remove")); + } else { + 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)); + List items = w.blockEntities.get(at) instanceof Container c && !hasList(c) ? List.of(c.getItem(0)) : 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))); } diff --git a/tools/test_block_removal_parity.py b/tools/test_block_removal_parity.py new file mode 100755 index 000000000..35b0fdd2b --- /dev/null +++ b/tools/test_block_removal_parity.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Compare what vanilla and Horizon do when a block with a block entity goes away. + +A container, jukebox, lectern, campfire, decorated pot, chiseled bookshelf, +shelf, shulker box or another block entity holder at the origin holds random +contents; the case then replaces it with `Level.setBlock` (another block, the +same block in another state, with or without UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS), +destroys it with `Level.destroyBlock` (with or without drops) or removes it with +`Level.removeBlock`. Vanilla runs over the headless level of the dispenser oracle +(`VanillaDispenserOracle`, "remove" cases), which replays `LevelChunk.setBlockState`'s +`BlockEntity.preRemoveSideEffects`; Horizon runs its game glue in a headless game +(`HORIZON_DISPENSE_FIXTURE`). Both print the block changes, the contents left, +every item entity (position, motion, stack), level events, sounds, game events +and the level random. Motions from an item's own unseeded random ("~") are +compared within their spread. +""" +import json +import os +import random +try: + from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base +except ImportError: + import block_update_harness as h + import lab + import test_dispenser_parity as d + import test_rust_parity as base + + +def plain(item, count=1): + return d.plain(item, count) + + +def named(item, count, name): + return '{id:"minecraft:%s",count:%d,components:{"minecraft:custom_name":"%s"}}' % (item, count, name) + + +STUFF = ['cobblestone', 'diamond', 'stick', 'iron_ingot', 'oak_planks', 'bread', 'arrow', 'redstone', 'ender_pearl', 'torch', + 'iron_sword', 'bow', 'white_wool', 'glass', 'apple'] +BOOKS = ['book', 'enchanted_book', 'writable_book', 'written_book', 'knowledge_book'] +FOOD = ['porkchop', 'beef', 'chicken', 'mutton', 'rabbit', 'cod', 'salmon', 'potato', 'kelp'] +DISCS = ['music_disc_cat', 'music_disc_13', 'music_disc_pigstep', 'music_disc_otherside'] + +# Blocks with a block entity: the slots a case may fill and what goes in them. +HOLDERS = { + 'chest': (27, STUFF), 'trapped_chest': (27, STUFF), 'barrel': (27, STUFF), 'hopper': (5, STUFF), + 'dispenser': (9, STUFF), 'dropper': (9, STUFF), 'crafter': (9, STUFF), 'furnace': (3, STUFF), + 'blast_furnace': (3, STUFF), 'smoker': (3, FOOD), 'brewing_stand': (5, ['potion', 'blaze_powder', 'nether_wart', 'glass_bottle']), + 'shulker_box': (27, STUFF), 'red_shulker_box': (27, STUFF), 'lime_shulker_box': (27, STUFF), + 'copper_chest': (27, STUFF), 'exposed_copper_chest': (27, STUFF), 'weathered_copper_chest': (27, STUFF), + 'oxidized_copper_chest': (27, STUFF), 'waxed_copper_chest': (27, STUFF), 'waxed_oxidized_copper_chest': (27, STUFF), + 'jukebox': (1, DISCS), 'lectern': (1, ['writable_book', 'written_book']), 'campfire': (4, FOOD), 'soul_campfire': (4, FOOD), + 'decorated_pot': (1, STUFF), 'chiseled_bookshelf': (6, BOOKS), 'oak_shelf': (3, STUFF), 'pale_oak_shelf': (3, STUFF), + 'warped_shelf': (3, STUFF), + # Block entities without contents. + 'ender_chest': (0, []), 'enchanting_table': (0, []), 'oak_sign': (0, []), 'white_banner': (0, []), 'beacon': (0, []), + 'bell': (0, []), 'skeleton_skull': (0, []), 'daylight_detector': (0, []), 'comparator': (0, []), 'spawner': (0, []), +} +# Blocks whose block entity Horizon models with its slots, which vanilla lists +# when the block entity survives (the others are only ever replaced). +LISTED = {'chest', 'trapped_chest', 'barrel', 'hopper', 'dispenser', 'dropper', 'crafter', 'furnace', 'blast_furnace', + 'smoker', 'brewing_stand', 'shulker_box', 'red_shulker_box', 'lime_shulker_box', 'copper_chest', 'exposed_copper_chest', + 'weathered_copper_chest', 'oxidized_copper_chest', 'waxed_copper_chest', 'waxed_oxidized_copper_chest', 'jukebox'} +REPLACEMENTS = ['air', 'stone', 'glass', 'water', 'oak_planks', 'barrel', 'chest', 'hopper', 'blue_shulker_box', 'dirt', 'tnt', + 'copper_chest', 'oxidized_copper_chest', 'lectern', 'jukebox'] +FLAGS = [3, 3, 3, 2, 18, 2 | 256, 816, 3 | 64, 1] + + +def contents(rng, name, slots, pool): + """Slot items for the holder (books where books go, discs in jukeboxes, ...).""" + items = [] + if not slots: + return items + fill = rng.choice([0, 1, 1, 2, 3, slots]) if slots > 1 else rng.choice([0, 1, 1]) + for slot in rng.sample(range(slots), min(fill, slots)): + item = rng.choice(pool) + count = 1 if name in ('jukebox', 'lectern', 'chiseled_bookshelf') or item in ('iron_sword', 'bow', 'potion', + 'writable_book', 'written_book') else rng.randrange(1, 65) + if item == 'potion': + stack = d.potion('potion', rng.choice(['water', 'healing', 'swiftness'])) + elif rng.random() < 0.1 and count > 0: + stack = named(item, count, 'Kept') + else: + stack = plain(item, count) + items.append([0, 0, 0, slot, stack]) + return items + + +def holder_state(states, rng, name, items): + """The block's state, with its book, record or slots shown where the state shows them.""" + if name == 'lectern': + # A lectern shows a book exactly when it holds one. + return states.get(name, has_book='true' if items else 'false', facing=rng.choice(['north', 'south', 'east', 'west'])) + if name == 'jukebox': + return states.get(name, has_record='true' if items else 'false') + if name == 'chiseled_bookshelf': + filled = {i[3] for i in items} + return states.get(name, **{f'slot_{i}_occupied': 'true' if i in filled else 'false' for i in range(6)}) + if name in ('chest', 'trapped_chest'): + return states.get(name, type='single', facing=rng.choice(['north', 'south', 'east', 'west'])) + return states.any(rng, name) if rng.random() < 0.3 else states.get(name) + + +def other_state(states, rng, name, current): + """Another state of the same block, when it has one.""" + choices = [i for i in states.facts.by_block['minecraft:' + name] if i != current] + return rng.choice(choices) if choices else None + + +def cases(facts, count, seed, only): + rng = random.Random(seed) + states = d.States(facts) + names = list(HOLDERS) + for n in range(count): + name = names[n % len(names)] if rng.random() < 0.7 else rng.choice(names) + if only and only not in name: + continue + slots, pool = HOLDERS[name] + items = contents(rng, name, slots, pool) + state = holder_state(states, rng, name, items) + cells = [[0, 0, 0, state]] + # A few neighbours: supports, comparators reading the container, fluids. + for _ in range(rng.randrange(0, 4)): + at = (rng.randrange(-1, 2), rng.randrange(-1, 2), rng.randrange(-1, 2)) + if at != (0, 0, 0): + h.put(cells, at, states.get(rng.choice(['stone', 'dirt', 'glass', 'oak_planks', 'water', 'comparator', 'redstone_wire']))) + roll = rng.random() + if roll < 0.45: + if name in LISTED and rng.random() < 0.15: + target = other_state(states, rng, name, state) + target = target if target is not None else states.get(rng.choice(REPLACEMENTS)) + else: + target = states.get(rng.choice(REPLACEMENTS)) + op = {'op': 'set', 'state': target, 'flags': rng.choice(FLAGS)} + elif roll < 0.75: + op = {'op': 'destroy', 'drop': True} + elif roll < 0.85: + op = {'op': 'destroy', 'drop': False} + else: + op = {'op': 'remove'} + case = {**h.environment(rng), 'mode': 'remove', 'pos': [0, 0, 0], 'cells': cells, 'items': items, 'remove': op} + case.pop('raining', None) + case.pop('thundering', None) + yield case + + +def describe(case, facts): + cells = ' '.join(f'{c[0]},{c[1]},{c[2]}={facts.describe(c[3])}' for c in case['cells']) + op = dict(case['remove']) + if 'state' in op: + op['state'] = facts.describe(op['state']) + return f'{cells} items={json.dumps(case["items"])} remove={json.dumps(op)} seed={case["seed"]}' + + +def main(): + parser = h.argument_parser(__doc__) + args = parser.parse_args() + if args.count == 40000: + args.count = 4000 + lock, jars, libraries = base.verify_artifacts() + facts = h.load_facts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + work = lab.LOCAL / 'block-removal-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' + d.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')]) + d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', + str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) + d.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')}) + d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + # Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared. + ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) + native = h.split_cases((work / 'native.txt').read_text(), ignore) + rust = h.split_cases((work / 'rust.txt').read_text(), ignore) + assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) + groups, errors = {}, {} + 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 not d.same(a, b): + block = facts.states[case['cells'][0][3]][0].split(':')[1] + groups.setdefault(f'{block} {case["remove"]["op"]}', []).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)') + (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 + skipped) + + +if __name__ == '__main__': + main()