From f9fcb004a5cc0a56ff6f9c2ae0d3e8981e310a86 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:38:13 +0200 Subject: [PATCH] Dispense chest boats and command block minecarts as vanilla does BoatDispenseItemBehavior spawns the chest boat or chest raft itself: boats now carry ChestBoat's 27-slot chest, drawn with its model, saved with its Items, opened by sneaking, spilt when broken. MinecartDispenseItemBehavior spawns command block minecarts (an empty command). The dispenser harness now draws fronts per item (fire, portal frames, anchors, crops, copper, hives, golem and wither builds), every boat wood, more equipment, spawn eggs, sulfur cube swallowables and leashed targets, over 6000 cases. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 21 +-- crates/horizon-client/src/game/boats.rs | 105 ++++++++++--- crates/horizon-client/src/game/commands.rs | 12 +- .../horizon-client/src/game/commands/data.rs | 3 +- .../src/game/dispense_fixture.rs | 16 ++ crates/horizon-client/src/game/dispenser.rs | 18 +-- crates/horizon-client/src/game/minecarts.rs | 32 +++- crates/horizon-client/src/game/persist.rs | 23 +-- .../parity/VanillaDispenserOracle.java | 20 ++- tools/test_dispenser_parity.py | 148 +++++++++++++++--- 10 files changed, 320 insertions(+), 78 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index b38fb8469..f5f9306db 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1136,22 +1136,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { a.on_ground = flag(tag, "OnGround"); Some(a) } -/// A boat entity (`minecraft:_boat`, `minecraft:bamboo_raft`). +/// A boat entity (`minecraft:_boat`, `minecraft:bamboo_chest_raft`...): +/// chest boats keep their slots in `Items` (`ContainerHelper.saveAllItems`). pub fn boat_to_nbt( - wood: &str, + id: &str, position: Vec3, motion: Vec3, yaw: f32, uuid: [i32; 4], raw: Option<&Tag>, + items: Option<&[Option]>, ) -> Tag { - let id = if wood == "bamboo" { - "minecraft:bamboo_raft".to_owned() - } else { - format!("minecraft:{wood}_boat") - }; - Base { - id: &id, + let mut tag = Base { + id, uuid, position, motion, @@ -1159,7 +1156,11 @@ pub fn boat_to_nbt( on_ground: false, fall_distance: 0.0, } - .tag(raw) + .tag(raw); + if let (Some(items), Tag::Compound(map)) = (items, &mut tag) { + map.insert("Items".into(), crate::save::encode_items(items)); + } + tag } /// A vehicle's base entity tag (boats and minecarts). pub fn vehicle_to_nbt( diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 1bac6b220..a1d0458bf 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -48,7 +48,12 @@ pub(super) struct Boat { /// left, right, up, down pub input: [bool; 4], pub on_ground: bool, + /// `ChestBoat`: a chest with 27 slots in the back seat. + pub chest: bool, + pub items: Vec>, } +/// `ChestBoat.CONTAINER_SIZE`. +pub(super) const CHEST_SLOTS: usize = 27; const WIDTH: f64 = 1.375; const HEIGHT: f64 = 0.5625; /// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment. @@ -76,8 +81,16 @@ impl Boat { paddling: [false; 2], input: [false; 4], on_ground: false, + chest: false, + items: Vec::new(), } } + /// A chest boat or chest raft. + pub fn with_chest(mut self) -> Self { + self.chest = true; + self.items = vec![None; CHEST_SLOTS]; + self + } pub fn bounds(&self) -> Aabb { let (w, p) = (WIDTH / 2.0, self.position); Aabb::new( @@ -96,15 +109,29 @@ impl Boat { } /// Item id -> (boat entity id, wood). impl Boat { - /// The vanilla entity type id (`oak_boat`, `bamboo_raft`). + /// The vanilla entity type id (`oak_boat`, `bamboo_chest_raft`), also + /// the item it drops. pub(super) fn entity_type(&self) -> String { + let chest = if self.chest { "chest_" } else { "" }; if &*self.wood == "bamboo" { - "minecraft:bamboo_raft".to_owned() + format!("minecraft:bamboo_{chest}raft") } else { - format!("minecraft:{}_boat", self.wood) + format!("minecraft:{}_{chest}boat", self.wood) } } } +/// The wood of a boat or chest boat item or entity type, and whether it +/// carries a chest. +pub(super) fn any_boat_wood(item: &str) -> Option<(&str, bool)> { + let name = item.strip_prefix("minecraft:")?; + if let Some(wood) = name + .strip_suffix("_chest_boat") + .or_else(|| name.strip_suffix("_chest_raft")) + { + return Some((wood, true)); + } + boat_wood(item).map(|w| (w, false)) +} pub(super) fn boat_wood(item: &str) -> Option<&str> { let name = item.strip_prefix("minecraft:")?; name.strip_suffix("_boat") @@ -113,10 +140,20 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> { } pub(super) struct BoatModels { pub models: HashMap, + pub chest_models: HashMap, } impl BoatModels { + /// Whether a boat of this wood (with or without a chest) can be drawn. + pub fn has(&self, wood: &str, chest: bool) -> bool { + if chest { + self.chest_models.contains_key(wood) + } else { + self.models.contains_key(wood) + } + } pub fn load(root: &std::path::Path) -> Self { let mut models = HashMap::new(); + let mut chest_models = HashMap::new(); if let Ok(bytes) = std::fs::read(root.join("entity-models.json")) && let Ok(serde_json::Value::Object(all)) = serde_json::from_slice::(&bytes) @@ -129,9 +166,16 @@ impl BoatModels { { models.insert(wood.to_owned(), part); } + if let Some(wood) = key + .strip_prefix("minecraft:chest_boat/") + .and_then(|k| k.strip_suffix("#main")) + && let Some(part) = horizon_client::mobs::load_model(root, key) + { + chest_models.insert(wood.to_owned(), part); + } } } - Self { models } + Self { models, chest_models } } } impl Game<'_> { @@ -467,10 +511,10 @@ impl Game<'_> { } /// `BoatItem.use`: aim at a block or the water surface. pub(super) fn place_boat(&mut self, stack: &ItemStack) -> bool { - let Some(wood) = boat_wood(&stack.item) else { + let Some((wood, chest)) = any_boat_wood(&stack.item) else { return false; }; - if !self.boat_models.models.contains_key(wood) { + if !self.boat_models.has(wood, chest) { return false; } let Some(eye) = self.eye_position() else { @@ -517,12 +561,15 @@ impl Game<'_> { (None, Some(w)) => w.0, (None, None) => return false, }; - let boat = Boat::new( + let mut boat = Boat::new( self.next_entity + 1, Arc::from(wood), Vec3::new(hit[0], hit[1], hit[2]), self.yaw, ); + if chest { + boat = boat.with_chest(); + } let bb = boat.bounds(); let (lo, hi) = (bb.min_position(), bb.max_position()); let e = 1.0e-7; @@ -585,11 +632,23 @@ impl Game<'_> { return false; }; let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); - if !self.before_block(d) - || sneaking - || self.boats[i].out_of_control >= 60.0 - || self.riding.is_some() - { + if !self.before_block(d) { + return false; + } + // ChestBoat.interact: sneaking (or a full seat) opens the chest. + if self.boats[i].chest && (sneaking || self.riding.is_some()) { + let b = &self.boats[i]; + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, b.id as i32); + self.world + .block_entities + .insert(key, horizon_client::containers::BlockEntity::Chest(b.items.clone())); + self.container = Some(key); + self.screen = super::Screen::Inventory; + self.capture(false); + self.right = false; + return true; + } + if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() { return false; } self.riding = Some(self.boats[i].id); @@ -611,13 +670,13 @@ impl Game<'_> { let destroyed = self.creative || b.damage > 40.0; if destroyed { let b = self.boats.remove(i); + let at = [b.position.x, b.position.y, b.position.z]; if !self.creative && self.ui.rules.bool("entity_drops") { - let item = if &*b.wood == "bamboo" { - "minecraft:bamboo_raft".to_owned() - } else { - format!("minecraft:{}_boat", b.wood) - }; - let at = [b.position.x, b.position.y, b.position.z]; + // ChestBoat.destroy: chestVehicleDestroyed spills the contents. + for stack in b.items.iter().flatten() { + self.spawn_item(stack.clone(), at, super::dispenser::new_item_motion(), 10); + } + let item = b.entity_type(); self.spawn_item( ItemStack { item: Arc::from(item.as_str()), @@ -638,14 +697,20 @@ impl Game<'_> { pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; for b in &self.boats { - let Some(model) = self.boat_models.models.get(&*b.wood) else { + let models = if b.chest { + &self.boat_models.chest_models + } else { + &self.boat_models.models + }; + let Some(model) = models.get(&*b.wood) else { continue; }; + let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self .res .atlas .sprites - .get(&format!("entity/boat/{}", b.wood)) + .get(&format!("entity/{folder}/{}", b.wood)) .map(|r| [r.u0, r.v0, r.u1, r.v1]) else { continue; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 9dfed52ea..2f0a7acc9 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -266,13 +266,11 @@ impl Game<'_> { } } Target::Painting(_) => "minecraft:painting".into(), - Target::Boat(id) => self.boats.iter().find(|b| b.id == id).map_or_else( - || "minecraft:oak_boat".into(), - |b| { - let kind = if &*b.wood == "bamboo" { "raft" } else { "boat" }; - format!("minecraft:{}_{kind}", b.wood) - }, - ), + Target::Boat(id) => self + .boats + .iter() + .find(|b| b.id == id) + .map_or_else(|| "minecraft:oak_boat".into(), |b| b.entity_type()), Target::Cart(id) => self .carts .iter() diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index d7436a628..85d298f8f 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -73,12 +73,13 @@ impl Game<'_> { let uuid = self.uuid_for(id); let b = self.boats.iter().find(|b| b.id == id)?; entity_nbt::boat_to_nbt( - &b.wood, + &b.entity_type(), b.position, b.velocity, b.yaw, uuid, self.persist.raw.get(&id), + b.chest.then_some(&b.items[..]), ) } Target::Cart(id) => { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 011523f52..33bbdb279 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -168,6 +168,19 @@ impl Game<'_> { for e in case["entities"].as_array().into_iter().flatten() { targets.push(self.fixture_target(e)?); } + // Leashable.setLeashedTo: a lead from a target to an earlier one. + for (e, t) in case["entities"].as_array().into_iter().flatten().zip(&targets) { + let (Some(holder), Target::Mob(id)) = (e["leash"].as_u64(), t) else { + continue; + }; + let holder = match targets.get(holder as usize) { + Some(Target::Mob(h)) => horizon_client::mobs::leash::Holder::Mob(*h), + _ => continue, + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id) { + m.extra.leash = Some(holder); + } + } // Creating the targets must not move the stream the dispenser draws from. self.world.random = LegacyRandom::new(seed); self.world.block_log = Some(Vec::new()); @@ -365,6 +378,9 @@ impl Game<'_> { if x.chested && matches!(s, Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama) { line.push_str(" chest"); } + if x.leash.is_some() { + line.push_str(" leashed"); + } } } line diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 5b4819ef0..26f5e0b50 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -603,12 +603,7 @@ impl Game<'_> { "minecraft:honeycomb" => self.dispense_honeycomb(pos, facing, stack)?, "minecraft:potion" => self.dispense_potion(pos, facing, stack)?, _ if item.ends_with("shulker_box") => self.dispense_shulker_box(pos, facing, stack)?, - _ if super::boats::boat_wood(&item).is_some() => self.dispense_boat(pos, facing, stack), - // 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::boats::any_boat_wood(&item).is_some() => self.dispense_boat(pos, facing, stack), _ if super::minecarts::CartKind::from_id(&item).is_some() => { self.dispense_minecart(pos, facing, stack) } @@ -1004,7 +999,9 @@ impl Game<'_> { } /// `BoatDispenseItemBehavior`. fn dispense_boat(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { - let Some(wood) = super::boats::boat_wood(&stack.item).map(str::to_owned) else { + let Some((wood, chest)) = + super::boats::any_boat_wood(&stack.item).map(|(w, c)| (w.to_owned(), c)) + else { return (self.dispense_default(pos, facing, stack), CLICK); }; let front = offset(pos, facing); @@ -1025,16 +1022,19 @@ impl Game<'_> { } else { return (self.dispense_default(pos, facing, stack), CLICK); }; - if !self.boat_models.models.contains_key(&wood) { + if !self.boat_models.has(&wood, chest) { return (self.dispense_default(pos, facing, stack), CLICK); } self.next_entity += 1; - let boat = super::boats::Boat::new( + let mut boat = super::boats::Boat::new( self.next_entity, wood.as_str().into(), Vec3::new(x, y + y_offset, z), y_rot(facing), ); + if chest { + boat = boat.with_chest(); + } self.world.modified.insert((front.0 >> 4, front.2 >> 4)); self.boats.push(boat); (shrink(stack), CLICK) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 967bef7e4..c9baac7d9 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -28,6 +28,9 @@ pub(super) enum CartKind { Hopper, Furnace, Tnt, + /// `MinecartCommandBlock`; its command block holds no command, so an + /// activator rail runs nothing. + CommandBlock, } impl CartKind { pub fn from_id(id: &str) -> Option { @@ -37,6 +40,7 @@ impl CartKind { "hopper_minecart" => Self::Hopper, "furnace_minecart" => Self::Furnace, "tnt_minecart" => Self::Tnt, + "command_block_minecart" => Self::CommandBlock, _ => return None, }) } @@ -47,6 +51,7 @@ impl CartKind { Self::Hopper => "minecraft:hopper_minecart", Self::Furnace => "minecraft:furnace_minecart", Self::Tnt => "minecraft:tnt_minecart", + Self::CommandBlock => "minecraft:command_block_minecart", } } fn slots(self) -> usize { @@ -192,6 +197,7 @@ impl CartModels { CartKind::Hopper, CartKind::Furnace, CartKind::Tnt, + CartKind::CommandBlock, ]; let models = kinds .into_iter() @@ -981,6 +987,8 @@ impl Game<'_> { self.prime_cart(&mut c); self.carts[i] = c; } + // BaseCommandBlock.usedBy: only an operator in creative opens it. + CartKind::CommandBlock => return false, } self.swing_arm(); true @@ -990,9 +998,10 @@ impl Game<'_> { let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else { return; }; - if let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) - && let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) - { + let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else { + return; + }; + if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) { c.items = items; let at = [c.position.x, c.position.y, c.position.z]; if c.kind == CartKind::Chest { @@ -1000,15 +1009,24 @@ impl Game<'_> { self.audio .play("minecraft:block.chest.close", Some(at), 0.5, pitch); } + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) { + b.items = items; } } /// The open cart's kind when a cart container is shown. pub(super) fn open_cart_kind(&self) -> Option { let key = self.container.filter(|k| k.1 == CART_KEY_Y)?; + // A chest boat's chest shows like a chest minecart's. self.carts .iter() .find(|c| c.id as i32 == key.2) .map(|c| c.kind) + .or_else(|| { + self.boats + .iter() + .any(|b| b.chest && b.id as i32 == key.2) + .then_some(CartKind::Chest) + }) } /// `VehicleEntity.hurtServer` from the player's attack. pub(super) fn attack_cart(&mut self, damage: f32) -> bool { @@ -1121,6 +1139,7 @@ impl Game<'_> { ], ), CartKind::Tnt => registry.default_state("minecraft:tnt"), + CartKind::CommandBlock => registry.default_state("minecraft:command_block"), } } /// `AbstractMinecartRenderer` (old render): on the rail between the @@ -1283,6 +1302,13 @@ impl Minecart { put("Fuel", Tag::Short(self.fuel as i16)); } CartKind::Tnt => put("fuse", Tag::Int(self.fuse)), + // BaseCommandBlock.save of an empty command block. + CartKind::CommandBlock => { + put("Command", Tag::String(JavaString::from(""))); + put("SuccessCount", Tag::Int(0)); + put("TrackOutput", Tag::Byte(1)); + put("UpdateLastExecution", Tag::Byte(1)); + } CartKind::Rideable => {} } } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 2aa368383..957ede43a 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -198,18 +198,22 @@ impl Game<'_> { }); } } - k if super::boats::boat_wood(k).is_some() - && self - .boat_models - .models - .contains_key(super::boats::boat_wood(k).unwrap_or("")) => + k if super::boats::any_boat_wood(k) + .is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) => { if let Some((position, velocity, yaw)) = entity_nbt::boat_from_nbt(&tag) { self.next_entity += 1; let id = self.next_entity; - let wood = - std::sync::Arc::from(super::boats::boat_wood(k).unwrap_or("oak")); - let mut b = super::boats::Boat::new(id, wood, position, yaw); + let (wood, chest) = super::boats::any_boat_wood(k).unwrap_or(("oak", false)); + let mut b = + super::boats::Boat::new(id, std::sync::Arc::from(wood), position, yaw); + if chest { + b = b.with_chest(); + b.items = horizon_client::save::decode_items( + tag.get("Items"), + super::boats::CHEST_SLOTS, + ); + } b.velocity = velocity; self.remember(id, uuid, tag); self.boats.push(b); @@ -536,12 +540,13 @@ impl Game<'_> { .copied() .unwrap_or_else(random_uuid); let tag = entity_nbt::boat_to_nbt( - &b.wood, + &b.entity_type(), b.position, b.velocity, b.yaw, uuid, self.persist.raw.get(&b.id), + b.chest.then_some(&b.items[..]), ); out.entry(chunk_of(b.position)).or_default().push(tag); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 69ea13997..0aba1dce4 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -150,6 +150,11 @@ public final class VanillaDispenserOracle { public net.minecraft.world.level.chunk.ChunkGenerator getGenerator() { return generator; } + + /** Leads send entity link packets; nobody is tracking. */ + @Override + public void sendToTrackingPlayers(final Entity entity, final net.minecraft.network.protocol.Packet packet) { + } } static Method dispenseFrom(Class type) throws Exception { @@ -225,7 +230,19 @@ public final class VanillaDispenserOracle { } } if (f.has("entities")) { - for (var e : f.getAsJsonArray("entities")) w.entities.add(target(w, e.getAsJsonObject())); + List created = new ArrayList<>(); + for (var e : f.getAsJsonArray("entities")) { + Entity ent = target(w, e.getAsJsonObject()); + created.add(ent); + w.entities.add(ent); + } + var list = f.getAsJsonArray("entities"); + for (int i = 0; i < list.size(); i++) { + var e = list.get(i).getAsJsonObject(); + if (e.has("leash") && created.get(i) instanceof Leashable leashable) { + leashable.setLeashedTo(created.get(e.get("leash").getAsInt()), true); + } + } } // Creating the targets must not move the stream the dispenser draws from. w.rng = new LegacyRandomSource(f.get("seed").getAsLong()); @@ -286,6 +303,7 @@ public final class VanillaDispenserOracle { || e instanceof net.minecraft.world.entity.monster.skeleton.Bogged || e instanceof net.minecraft.world.entity.animal.golem.SnowGolem; if (listed && e instanceof Shearable shearable) line.append(shearable.readyForShearing() ? " ready" : " unready"); if (e instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested && chested.hasChest()) line.append(" chest"); + if (e instanceof Leashable leashable && leashable.isLeashed()) line.append(" leashed"); return line.toString(); } } diff --git a/tools/test_dispenser_parity.py b/tools/test_dispenser_parity.py index 59c434eaf..33792488d 100644 --- a/tools/test_dispenser_parity.py +++ b/tools/test_dispenser_parity.py @@ -34,9 +34,15 @@ 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. +WOODS = ['oak', 'spruce', 'birch', 'jungle', 'acacia', 'cherry', 'dark_oak', 'mangrove', 'pale_oak', 'poplar'] + +# Items with the blocks and entities in front that exercise their behaviour: +# one entry per DispenseItemBehavior.bootStrap registration family, plus the +# defaults of DispenserBlock.getDefaultDispenseMethod (equippables, sulfur +# cube swallowables, spawn eggs, a plain drop). ITEMS = { - 'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2)], + 'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2), plain('lead'), + plain('wheat_seeds', 7)], 'projectile': [plain('arrow', 3), potion('tipped_arrow', 'poison'), plain('spectral_arrow'), plain('egg', 2), plain('blue_egg'), plain('brown_egg'), plain('snowball', 4), plain('experience_bottle'), potion('splash_potion', 'healing'), potion('lingering_potion', 'swiftness'), plain('firework_rocket', 2), plain('fire_charge', 2), plain('wind_charge', 3)], @@ -45,13 +51,22 @@ ITEMS = { 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')], + plain('red_shulker_box'), plain('lime_shulker_box'), plain('carved_pumpkin'), plain('wither_skeleton_skull'), + plain('shears'), plain('brush')], + 'vehicle': [plain('oak_boat'), plain('bamboo_raft'), plain('bamboo_chest_raft'), plain('minecart'), plain('chest_minecart'), + plain('furnace_minecart'), plain('tnt_minecart'), plain('hopper_minecart'), plain('command_block_minecart'), + plain('armor_stand', 2), 'BOAT', 'CHEST_BOAT'], + 'spawn': [plain('pig_spawn_egg'), plain('sheep_spawn_egg', 2), plain('zombie_spawn_egg'), plain('cow_spawn_egg'), + plain('chicken_spawn_egg'), plain('skeleton_spawn_egg'), plain('creeper_spawn_egg'), plain('villager_spawn_egg'), + plain('wolf_spawn_egg'), plain('horse_spawn_egg'), plain('squid_spawn_egg'), plain('slime_spawn_egg')], 'equipment': [plain('iron_helmet'), plain('diamond_chestplate'), plain('leather_leggings'), plain('golden_boots'), - plain('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')], + plain('chainmail_helmet'), plain('netherite_boots'), plain('turtle_helmet'), plain('saddle'), + plain('iron_horse_armor'), plain('diamond_horse_armor'), plain('leather_horse_armor'), plain('white_carpet'), + plain('red_carpet'), plain('chest'), plain('carved_pumpkin'), plain('elytra'), plain('wolf_armor'), plain('shears'), + plain('brush'), plain('player_head'), plain('zombie_head'), plain('white_harness')], + 'swallow': [plain('slime_block'), plain('oak_planks', 3), plain('packed_ice'), plain('soul_sand'), plain('magma_block'), + plain('white_wool'), plain('mud', 2), plain('andesite'), plain('iron_block'), plain('mushroom_stem'), + plain('honeycomb_block'), plain('tube_coral_block'), plain('tnt'), plain('stone')], } FRONT = { @@ -65,29 +80,74 @@ FRONT = { 'vehicle': ['air', 'air', 'water', 'rail', 'powered_rail', 'activator_rail', 'stone', 'detector_rail'], 'spawn': ['air', 'air', 'water', 'stone', 'grass_block'], 'equipment': ['air'], + 'swallow': ['air'], } +# The blocks a behaviour reacts to, drawn for that item most of the time. +FRONT_FOR = { + 'flint_and_steel': ['air', 'air', 'air', 'campfire', 'soul_campfire', 'candle', 'blue_candle', 'candle_cake', + 'red_candle_cake', 'tnt', 'stone', 'obsidian', 'netherrack', 'water'], + 'glowstone': ['respawn_anchor', 'respawn_anchor', 'respawn_anchor', 'air', 'stone', 'glowstone'], + 'bone_meal': ['grass_block', 'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling', + 'cherry_sapling', 'mangrove_propagule', 'moss_block', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo', + 'pumpkin_stem', 'melon_stem', 'torchflower_crop', 'pitcher_crop', 'rooted_dirt', 'glow_lichen', 'small_dripleaf', + 'big_dripleaf', 'crimson_nylium', 'warped_fungus', 'brown_mushroom', 'kelp', 'sea_pickle', 'seagrass', 'water', + 'short_grass', 'fern', 'dandelion', 'pink_petals', 'cave_vines', 'twisting_vines', 'weeping_vines', 'azalea', + 'pale_moss_block', 'stone', 'air'], + 'honeycomb': ['copper_block', 'exposed_copper', 'weathered_cut_copper', 'oxidized_cut_copper_slab', 'copper_door', + 'exposed_copper_trapdoor', 'copper_bulb', 'lightning_rod', 'waxed_copper_block', 'copper_grate', 'stone', 'air'], + 'glass_bottle': ['beehive', 'beehive', 'bee_nest', 'bee_nest', 'water', 'water', 'air', 'stone', 'seagrass'], + 'potion': ['dirt', 'coarse_dirt', 'rooted_dirt', 'dirt', 'stone', 'air', 'mud', 'water'], + 'shears': ['beehive', 'bee_nest', 'beehive', 'air', 'air', 'stone', 'pumpkin'], + 'brush': ['air', 'air', 'suspicious_sand', 'stone'], + 'tnt': ['air', 'air', 'stone', 'water', 'tnt'], + 'shulker_box': ['air', 'air', 'stone', 'water', 'short_grass', 'snow'], + 'carved_pumpkin': ['air', 'air', 'stone', 'snow'], + 'wither_skeleton_skull': ['air', 'air', 'stone'], + 'armor_stand': ['air', 'air', 'stone', 'water', 'short_grass'], +} +# Structures a behaviour completes (golems, the wither, a nether portal). +SCENES = {'carved_pumpkin': ['snow_golem', 'iron_golem'], 'wither_skeleton_skull': ['wither'], 'flint_and_steel': ['portal']} BELOW = ['air', 'stone', 'water', 'rail', 'grass_block', 'soul_sand', 'dirt', 'farmland', 'netherrack'] TARGETS = { 'iron_helmet': ['zombie', 'skeleton', 'armor_stand', 'pig'], + 'chainmail_helmet': ['zombie', 'armor_stand', 'villager'], 'diamond_chestplate': ['zombie', 'armor_stand'], 'leather_leggings': ['skeleton', 'armor_stand'], 'golden_boots': ['zombie', 'armor_stand'], + 'netherite_boots': ['zombie', 'piglin', 'armor_stand'], 'turtle_helmet': ['armor_stand', 'zombie'], - 'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama'], + 'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama', 'mule', 'skeleton_horse', 'nautilus'], 'iron_horse_armor': ['horse', 'donkey'], + 'diamond_horse_armor': ['horse', 'zombie_horse'], + 'leather_horse_armor': ['horse'], 'white_carpet': ['llama', 'horse', 'trader_llama'], - 'chest': ['donkey', 'mule', 'llama', 'horse'], + 'red_carpet': ['llama', 'trader_llama'], + 'chest': ['donkey', 'mule', 'llama', 'horse', 'trader_llama'], 'carved_pumpkin': ['zombie', 'armor_stand', 'snow_golem'], 'elytra': ['armor_stand', 'zombie'], 'wolf_armor': ['wolf'], - 'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem'], + 'white_harness': ['happy_ghast'], + 'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem', 'sulfur_cube', 'pig', 'cow'], 'brush': ['armadillo'], 'tnt': ['sulfur_cube'], 'flint_and_steel': ['sulfur_cube'], - 'stone': ['sulfur_cube'], 'player_head': ['armor_stand', 'zombie'], + 'zombie_head': ['armor_stand', 'skeleton'], } +for _block in ('stone', 'slime_block', 'oak_planks', 'packed_ice', 'soul_sand', 'magma_block', 'white_wool', 'mud', 'andesite', + 'iron_block', 'mushroom_stem', 'honeycomb_block', 'tube_coral_block'): + TARGETS[_block] = ['sulfur_cube'] +SWALLOWED = ['tnt', 'stone', 'slime_block', 'magma_block', 'white_wool', 'iron_block'] + + +def item_choice(rng, kind): + item = rng.choice(ITEMS[kind]) + if item == 'BOAT': + return plain(rng.choice(WOODS) + '_boat') + if item == 'CHEST_BOAT': + return plain(rng.choice(WOODS) + '_chest_boat') + return item class States: @@ -110,6 +170,47 @@ class States: return rng.choice(self.facts.by_block[name]) +def build_scene(cells, states, rng, scene, front, facing): + """Put the rest of a structure the behaviour's block completes around the front.""" + x, y, z = front + across = rng.choice([(1, 0, 0), (0, 0, 1)]) + + def put(at, name, **props): + if at != (0, 0, 0) and at != front: + h.put(cells, at, states.get(name, **props)) + + def side(at, k): + return (at[0] + across[0] * k, at[1], at[2] + across[2] * k) + if scene == 'snow_golem': + put((x, y - 1, z), 'snow_block') + put((x, y - 2, z), 'snow_block') + elif scene == 'iron_golem': + put((x, y - 1, z), 'iron_block') + put((x, y - 2, z), 'iron_block') + put(side((x, y - 1, z), -1), 'iron_block') + put(side((x, y - 1, z), 1), 'iron_block') + elif scene == 'wither': + put((x, y - 1, z), 'soul_sand') + put((x, y - 2, z), 'soul_sand') + put(side((x, y - 1, z), -1), rng.choice(['soul_sand', 'soul_soil'])) + put(side((x, y - 1, z), 1), 'soul_sand') + put(side((x, y, z), -1), 'wither_skeleton_skull') + put(side((x, y, z), 1), rng.choice(['wither_skeleton_skull', 'wither_skeleton_skull', 'skeleton_skull'])) + elif scene == 'portal': + # An obsidian frame around a 2x3 inside that holds the front block. + width, height = rng.choice([(2, 3), (2, 3), (3, 4)]) + left, low = rng.randrange(width), rng.randrange(height) + for i in range(-1, width + 1): + for j in range(-1, height + 1): + at = side((x, y + j - low, z), i - left) + edge = i in (-1, width) or j in (-1, height) + if edge and not (i in (-1, width) and j in (-1, height)): + put(at, 'obsidian') + elif not edge: + if at not in ((0, 0, 0), front): + h.put(cells, at, states.get('air')) + + def 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', @@ -124,28 +225,33 @@ def cases(facts, count, seed, only): kinds = list(ITEMS) for n in range(count): kind = kinds[n % len(kinds)] - item = rng.choice(ITEMS[kind]) + item = item_choice(rng, kind) if only and only not in item: continue + bare = item.split('"')[1].split(':')[1] facing = rng.choice(DIRECTIONS) block = 'dropper' if rng.random() < 0.12 else 'dispenser' cells = [[0, 0, 0, states.get(block, facing=facing, triggered='false')]] dx, dy, dz = STEP[facing] front = (dx, dy, dz) below = (dx, dy - 1, dz) - front_name = rng.choice(FRONT[kind]) + palette = FRONT_FOR[bare] if bare in FRONT_FOR and rng.random() < 0.8 else FRONT[kind] + front_name = rng.choice(palette) if front_name != 'air': h.put(cells, front, front_state(states, rng, front_name)) if below != (0, 0, 0) and rng.random() < 0.8: name = rng.choice(BELOW) if name != 'air': h.put(cells, below, front_state(states, rng, name)) + scene = rng.choice(SCENES[bare]) if bare in SCENES and rng.random() < 0.45 else None # A few random blocks around (portal frames, fire supports, neighbours). for _ in range(rng.randrange(0, 6)): at = (rng.randrange(-2, 3), rng.randrange(-2, 3), rng.randrange(-2, 3)) if at in ((0, 0, 0), front): continue h.put(cells, at, states.get(rng.choice(['stone', 'obsidian', 'dirt', 'water', 'soul_sand', 'grass_block', 'oak_planks']))) + if scene: + build_scene(cells, states, rng, scene, front, facing) items = [] slots = rng.sample(range(9), rng.choice([1, 1, 1, 2, 3, 9])) for i, slot in enumerate(slots): @@ -155,8 +261,7 @@ def cases(facts, count, seed, only): 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): + if kind in ('equipment', 'swallow') or (bare in TARGETS and rng.random() < 0.5): entities = [] for _ in range(rng.choice([1, 1, 1, 2])): target = {'type': 'minecraft:' + rng.choice(TARGETS.get(bare, ['zombie'])), @@ -165,8 +270,15 @@ def cases(facts, count, seed, only): 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']))} + target['equip'] = {'body': plain(rng.choice(SWALLOWED))} + # Leads: tied to an earlier target, or that target holds this one's. + if entities and rng.random() < 0.3: + target['leash'] = rng.randrange(len(entities)) entities.append(target) + if bare == 'shears' and len(entities) == 1 and rng.random() < 0.3: + # A holder out of the dispenser's reach whose lead runs to the target. + entities.append({'type': 'minecraft:' + rng.choice(['cow', 'wolf']), 'pos': [dx + 3.5, dy, dz + 3.5], 'yaw': 0.0}) + entities[0]['leash'] = 1 case['entities'] = entities if block == 'dropper' and rng.random() < 0.5: h.put(cells, front, states.get(rng.choice(['chest', 'hopper', 'barrel', 'dispenser']))) @@ -233,7 +345,7 @@ def main(): parser = h.argument_parser(__doc__) args = parser.parse_args() if args.count == 40000: - args.count = 3000 + args.count = 6000 lock, jars, libraries = base.verify_artifacts() facts = h.load_facts() resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']