diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4b7c45141..30b537f08 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -28,6 +28,7 @@ mod creaking; mod creatures; mod crossbow; mod debug_keys; +mod decorated_pot; mod dedicated; mod dispense_fixture; mod dispenser; @@ -422,6 +423,8 @@ struct GameLevel<'w> { seed: i64, behaviours: &'w Behaviours, items: &'w Items, + /// Container loot tables (`unpackLootTable`). + loot: Option>, registry: &'static horizon_world::registry::BlockRegistry, rules: horizon_world::level::GameRules, /// Block loot random sequences (`ServerLevel.getRandomSequence`). @@ -1619,6 +1622,7 @@ impl Game<'_> { seed: self.level.seed, behaviours: &self.res.behaviours, items: &self.res.items, + loot: horizon_client::structure_blocks::loot_data(&self.options.resources), registry: self.res.assets.registry, rules, rand_sequences: &mut self.rand_sequences, @@ -2371,6 +2375,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_decorated_pot(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(true); + } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 446b56b55..c83b493ed 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -12,6 +12,7 @@ use horizon_client::{ save::number, }; use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::nbt::Tag; use std::collections::HashMap; /// The handle of the local player among a bell's gathered entities. @@ -340,8 +341,15 @@ impl Game<'_> { /// The End gateway at `pos` as its chunk was loaded: `Age` from the saved /// block entity (`getUpdateTag`), or a new gateway. fn gateway_loaded(&self, pos: [i32; 3]) -> EndGateway { - let age = self - .world + let age = self.saved_tag(pos).and_then(|t| number(t.get("Age"))); + EndGateway { + age: age.unwrap_or(0), + teleport_cooldown: 0, + } + } + /// The block entity at `pos` Horizon keeps as loaded, if any. + fn saved_tag(&self, pos: [i32; 3]) -> Option<&Tag> { + self.world .chunks .get(&(pos[0] >> 4, pos[2] >> 4)) .and_then(|c| c.saved.as_deref()) @@ -352,16 +360,26 @@ impl Game<'_> { .eq(&pos.map(|v| Some(i64::from(v)))) }) }) - .and_then(|t| number(t.get("Age"))); - EndGateway { - age: age.unwrap_or(0), - teleport_cooldown: 0, - } } - /// The renderer's view of the block entity at `pos`. + /// The renderer's view of the block entity at `pos`, with a decorated + /// pot's saved `sherds` (back, left, right, front). pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { + let state = self.world.block(pos[0], pos[1], pos[2]); + let sherds = if &*self.res.facts.get(state).name == "minecraft:decorated_pot" { + let sherds = self.saved_tag(pos).and_then(|t| t.get("sherds")); + ["back", "left", "right", "front"].map(|side| match sherds.and_then(|s| s.get(side)) { + // An item id, or the item stack the processed templates hold. + Some(Tag::String(id)) => Some(id.to_string_lossy()), + Some(stack) => { + horizon_client::save::item_from_nbt(stack).map(|s| s.item.to_string()) + } + None => None, + }) + } else { + Default::default() + }; self.be_anims - .block_anim(pos, self.world.game_time, partial, Default::default()) + .block_anim(pos, self.world.game_time, partial, sherds) } /// `ChestLidController.getOpenness(partial)` at `pos`. pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 { diff --git a/crates/horizon-client/src/game/decorated_pot.rs b/crates/horizon-client/src/game/decorated_pot.rs new file mode 100644 index 000000000..3ac43566a --- /dev/null +++ b/crates/horizon-client/src/game/decorated_pot.rs @@ -0,0 +1,152 @@ +//! Decorated pots, which Horizon keeps as loaded (the chunk's saved block +//! entities): the loot table a trial chamber pot holds, rolled into its item +//! the first time the item is read (`RandomizableContainer.unpackLootTable`), +//! and `DecoratedPotBlock.useItemOn` / `useWithoutItem`. +use super::{Game, spill}; +use horizon_client::{ + first_person::Hand, + items::ItemStack, + mobs::Who, + particles::{ParticleOptions, ParticleType}, + random_sequences::RandomSequences, + save, +}; +use horizon_core::random::LegacyRandom; +use horizon_world::{loot::LootData, nbt::Tag}; + +/// `DecoratedPotBlockEntity.WobbleStyle` ordinals. +const WOBBLE_POSITIVE: i32 = 0; +const WOBBLE_NEGATIVE: i32 = 1; + +/// `RandomizableContainer.unpackLootTable(null)` on a pot's saved tag: the +/// loot table, if any, is removed and `LootTable.fill` puts its roll in +/// `item`. The roll draws from `LootTableSeed`, else the table's random +/// sequence, else the level random (`LootContext.Builder.create`). +pub(super) fn unpack_loot( + tag: &mut Tag, + loot: Option<&LootData>, + random: &mut LegacyRandom, + sequences: &mut RandomSequences, + world_seed: i64, +) { + let Tag::Compound(map) = tag else { + return; + }; + let Some(Tag::String(table)) = map.remove(&"LootTable".into()) else { + return; + }; + let seed = match map.remove(&"LootTableSeed".into()) { + Some(Tag::Long(seed)) => seed, + _ => 0, + }; + map.remove(&"item".into()); + let Some(loot) = loot else { + return; + }; + let table = table.to_string_lossy(); + // No origin biome: the pot tables have no location checks. + let slots = if seed != 0 { + loot.fill(&table, seed, 1, None) + } else if let Some(sequence) = loot.random_sequence(&table) { + loot.fill_with(&table, sequences.get(sequence, world_seed), 1, None) + } else { + loot.fill_with(&table, random, 1, None) + }; + if let Some(stack) = slots.into_iter().next().flatten() { + let item = horizon_client::structure_blocks::loot_item_with_components(&stack); + map.insert("item".into(), save::item_to_nbt(&item)); + } +} + +impl Game<'_> { + /// The pot's saved tag at `pos` with its loot unpacked (a new one for a + /// pot without), or None when no pot is there. + fn pot_tag(&mut self, pos: [i32; 3]) -> Option { + let state = self.world.block(pos[0], pos[1], pos[2]); + if &*self.res.facts.get(state).name != "minecraft:decorated_pot" { + return None; + } + let mut tag = spill::saved_entity(&self.world, pos).unwrap_or_else(|| { + Tag::compound([ + ("id", Tag::String("minecraft:decorated_pot".into())), + ("x", Tag::Int(pos[0])), + ("y", Tag::Int(pos[1])), + ("z", Tag::Int(pos[2])), + ]) + }); + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + unpack_loot( + &mut tag, + loot.as_deref(), + &mut self.world.random, + &mut self.rand_sequences, + self.level.seed, + ); + Some(tag) + } + /// `DecoratedPotBlock.useItemOn` with `held`, then `useWithoutItem` on the + /// main hand's turn: true when the pot took the click. + pub(super) fn use_decorated_pot(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + let Some(mut tag) = self.pot_tag(pos) else { + return false; + }; + let mut pot_item = tag.get("item").and_then(save::item_from_nbt); + let insertable = held.filter(|stack| match &pot_item { + None => true, + Some(p) => p.same_item_same_components(stack) && p.count < self.max_stack(p), + }); + let center = pos.map(|v| f64::from(v) + 0.5); + let Some(stack) = insertable else { + spill::put_saved_entity(&mut self.world, pos, tag); + // TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem. + if self.hand != Hand::Main { + return false; + } + self.audio.play( + "minecraft:block.decorated_pot.insert_fail", + Some(center), + 1.0, + 1.0, + ); + self.block_entity_event(pos, 1, WOBBLE_NEGATIVE); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + return true; + }; + let stack = stack.clone(); + self.block_entity_event(pos, 1, WOBBLE_POSITIVE); + self.stats.add("used", &stack.item, 1); + // consumeAndReturn(1): one item goes in (a creative player keeps theirs). + let inserted = match &mut pot_item { + Some(p) => { + p.count += 1; + p + } + None => pot_item.insert(ItemStack { + count: 1, + ..stack.clone() + }), + }; + let pitch_bend = inserted.count as f32 / self.max_stack(inserted) as f32; + if let (Tag::Compound(map), Some(item)) = (&mut tag, &pot_item) { + map.insert("item".into(), save::item_to_nbt(item)); + } + spill::put_saved_entity(&mut self.world, pos, tag); + self.consume_held(); + self.audio.play( + "minecraft:block.decorated_pot.insert", + Some(center), + 1.0, + 0.7 + 0.5 * pitch_bend, + ); + self.particles.send_particles( + &ParticleOptions::simple(ParticleType::DustPlume), + [center[0], f64::from(pos[1]) + 1.2, center[2]], + [0.0; 3], + 0.0, + 7, + ); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + true + } +} diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index 9e4ccdf76..ac508dfb8 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -191,6 +191,30 @@ pub(super) fn saved_entity( .cloned() } +/// Keep `tag` as the block entity at its position Horizon does not model, +/// replacing the one there. +pub(super) fn put_saved_entity( + world: &mut horizon_client::world::World, + pos: [i32; 3], + tag: horizon_world::nbt::Tag, +) { + use horizon_world::nbt::Tag; + let Some(chunk) = world.chunks.get_mut(&(pos[0] >> 4, pos[2] >> 4)) else { + return; + }; + let chunk = std::sync::Arc::make_mut(chunk); + let saved = std::sync::Arc::make_mut(chunk.saved.get_or_insert_default()); + let at = |t: &Tag| { + t.get("x") == Some(&Tag::Int(pos[0])) + && t.get("y") == Some(&Tag::Int(pos[1])) + && t.get("z") == Some(&Tag::Int(pos[2])) + }; + match saved.block_entities.iter_mut().find(|t| at(t)) { + Some(old) => *old = tag, + None => saved.block_entities.push(tag), + } +} + 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) { @@ -454,6 +478,15 @@ impl GameLevel<'_> { let name = self.facts.get(old).name.clone(); let items = match removal::pre_remove(&name) { PreRemove::Contents { slots, .. } if &*name == "minecraft:decorated_pot" => { + // Containers.dropContents reads getTheItem, which unpacks the loot table. + let mut tag = tag; + super::decorated_pot::unpack_loot( + &mut tag, + self.loot.as_deref(), + &mut self.world.random, + self.rand_sequences, + self.seed, + ); let mut items = vec![None; slots]; items[0] = tag .get("item") diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 8f5a15db4..fc18e8404 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -421,6 +421,38 @@ impl ChunkGenerator for VanillaTerrain { }; let mut out = self.column(&chunk); out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + // The block entities Horizon does not model (decorated pots with their + // sherds and loot table, brushable blocks) stay as placed, like a + // loaded chunk's. + let unmodelled: Vec = chunk + .block_entities + .iter() + .filter(|(pos, _)| { + !out.block_entities + .iter() + .any(|(p, _)| *p == (pos[0], pos[1], pos[2])) + }) + .filter_map(|(pos, nbt)| { + let id = crate::lan::chunks::block_entity_type( + chunk.block_name(pos[0], pos[1], pos[2]), + )?; + let mut nbt = nbt.clone(); + nbt.insert("id".into(), Tag::String(id.into())); + for (key, v) in ["x", "y", "z"].into_iter().zip(pos) { + nbt.insert(key.into(), Tag::Int(*v)); + } + Some(Tag::Compound(nbt)) + }) + .collect(); + if !unmodelled.is_empty() { + let mut extras = out + .saved + .take() + .map(Arc::unwrap_or_clone) + .unwrap_or_default(); + extras.block_entities = unmodelled; + out.saved = Some(Arc::new(extras)); + } out.structure_refs = chunk .structures() .into_iter() diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index cc896e06e..be6eea7bb 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -601,6 +601,17 @@ impl LootData { seed: i64, slots: usize, biome: Option<&str>, + ) -> Vec> { + self.fill_with(table, &mut LegacyRandom::new(seed), slots, biome) + } + /// LootTable.fill drawing from `random` (a seeded random or the table's + /// random sequence), which is advanced. + pub fn fill_with( + &self, + table: &str, + random: &mut R, + slots: usize, + biome: Option<&str>, ) -> Vec> { let mut out = vec![None; slots]; let Some(json) = self.tables.get(table) else { @@ -608,7 +619,7 @@ impl LootData { }; let mut c = Context { data: self, - random: LegacyRandom::new(seed), + random: random.clone(), biome, visited: Vec::new(), luck: 0.0, @@ -617,7 +628,7 @@ impl LootData { }; let mut items = Vec::new(); c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); - let random = &mut c.random; + *random = c.random; let mut available: Vec = (0..slots).collect(); shuffle(&mut available, random); shuffle_and_split(&mut items, available.len(), random); @@ -653,7 +664,7 @@ fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> i32 { } } /// LootTable.shuffleAndSplitItems. -fn shuffle_and_split(result: &mut Vec, slots: usize, random: &mut LegacyRandom) { +fn shuffle_and_split(result: &mut Vec, slots: usize, random: &mut impl RandomSource) { let mut splittable = Vec::new(); result.retain(|s| { if s.is_empty() {