From 4fecf43d28c4ff4a85699db7cee93af00c7fdd39 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:31:00 +0200 Subject: [PATCH] Grindstone on the menu engine; LAN guests use grindstones GrindstoneMenu now runs on horizon_client::menu (Kind::Grindstone): its input filter, computeResult, the result's onTake (both inputs cleared, the experience sum handed to the caller) and quickMoveStack, verified against the vanilla class by test_menu_click_parity with enchanted, damaged and cursed tools and books. Single player routes the grindstone's clicks, drags and double clicks through the engine and rolls the orbs and level event 1042 (now playing block.grindstone.use) where the result is taken. The LAN host opens minecraft:grindstone for guests on the same engine and awards the orbs at the block; guests read enchantments, stored enchantments, repair cost and custom names from the server's stacks, and the host now sends repair cost. Part of #868. Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 2 + .../horizon-client/examples/menu_fixture.rs | 2 + .../examples/place_recipe_fixture.rs | 2 + .../examples/trading_fixture.rs | 1 + crates/horizon-client/src/enchant.rs | 1 + crates/horizon-client/src/game.rs | 33 ++++++-- .../horizon-client/src/game/lan_crafting.rs | 1 + .../horizon-client/src/game/lan_stations.rs | 4 + crates/horizon-client/src/game/lan_trading.rs | 1 + crates/horizon-client/src/game/recipe_book.rs | 1 + crates/horizon-client/src/game/remote.rs | 29 +++++++ .../src/game/remote_stations.rs | 2 +- crates/horizon-client/src/game/stations.rs | 58 +++++-------- crates/horizon-client/src/lan/guest.rs | 6 ++ crates/horizon-client/src/menu.rs | 84 ++++++++++++++++++- crates/horizon-client/src/stations.rs | 22 +++-- .../horizonlab/parity/VanillaMenuOracle.java | 1 + tools/lan_e2e.py | 51 ++++++++++- tools/test_menu_click_parity.py | 51 ++++++++++- 19 files changed, 297 insertions(+), 55 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index c25badfd2..8093079cc 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -83,12 +83,14 @@ fn main() -> horizon_client::Result<()> { // The inventory menu never reads banner patterns. let banners = horizon_client::banner::Banners::default(); let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index bc43a59f1..ee5629498 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -45,12 +45,14 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); let station_recipes = horizon_client::stations::StationRecipes::load(root, &items); + let enchantments = horizon_client::enchant::Enchantments::load(root); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index b1a49e688..7d05a4cd3 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -39,12 +39,14 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::default(); let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs index b7eeb442c..a2dd8f461 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -380,6 +380,7 @@ fn main() -> horizon_client::Result<()> { brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: Some(&env_trade), }; trade(&mut out, name, &kv, &mut world, &env, origin)?; diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index a988eeb55..039ea658f 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -60,6 +60,7 @@ pub struct ItemProps { /// `minecraft:brewing_fuel` present. pub brewing_fuel: bool, } +#[derive(Default)] pub struct Enchantments { pub list: Vec, index: HashMap, usize>, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2aaf231f4..f3593b29c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2549,14 +2549,18 @@ impl Game<'_> { 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), + 1042 => Some(("minecraft:block.grindstone.use", 1.0)), _ => None, }; if let Some((name, volume)) = sound { - let pitch = if id == 1009 { - 2.6 + (self.world.random.next_float() - self.world.random.next_float()) - * 0.8 - } else { - 1.0 + let pitch = match id { + 1009 => { + 2.6 + (self.world.random.next_float() + - self.world.random.next_float()) + * 0.8 + } + 1042 => self.world.random.next_float() * 0.1 + 0.9, + _ => 1.0, }; self.audio.play(name, c, volume, pitch); } @@ -5429,6 +5433,10 @@ impl Game<'_> { .station .as_ref() .is_some_and(|s| s.kind == stations::Kind::Stonecutter); + let grindstone_open = self + .station + .as_ref() + .is_some_and(|s| s.kind == stations::Kind::Grindstone); let (kind, game_of): (Kind, Vec>) = if self.creative_tab_open() { // ItemPickerMenu: the display slots (clicked by the screen), then the hotbar. let mut v = vec![None; 45]; @@ -5460,6 +5468,15 @@ impl Game<'_> { let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Stonecutter, v) + } else if grindstone_open { + // GrindstoneMenu: the two inputs, the result, then the inventory. + let mut v = vec![ + Some(stations::INPUT), + Some(stations::INPUT + 1), + Some(stations::RESULT), + ]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Grindstone, v) } else { let (kind, map) = if self.container.is_some() { let size = self.container_size(); @@ -5578,6 +5595,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, trade: Some(&trade_env), }; menu.creative = creative; @@ -5676,6 +5694,11 @@ impl Game<'_> { self.station_sound(sound); } } + if let Some(amount) = menu.ground.take().filter(|_| !predicting) + && let Some(pos) = self.station.as_ref().map(|s| s.pos) + { + self.grindstone_taken(pos, amount); + } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self .container diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index bf71af641..54bf872ae 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -90,6 +90,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, trade: None, } } diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index b2b0c21aa..5cae6d6e9 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -35,6 +35,7 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:loom", Kind::Loom, 0..3), StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1), + StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2), _ => return None, }) } @@ -94,6 +95,9 @@ impl Game<'_> { { self.guest_menu_op(host, gi, &mut gs.menu, op); self.lan_station_sounds(&mut gs); + if let Some(amount) = gs.menu.ground.take() { + self.grindstone_taken(gs.pos, amount); + } } host.play.entry(conn).or_default().station = Some(gs); self.lan_send_station(host, conn); diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 7036b60eb..a3a33c019 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -256,6 +256,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, trade: Some(&trade_env), }; let mut menu = Menu::new(Kind::Merchant); diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index f7c00c998..4000fa64c 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -280,6 +280,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, trade: None, }; for i in 0..36 { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 686e59430..5c6ebb86f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -493,6 +493,34 @@ impl Game<'_> { if let Some(Component::Int(id)) = s.component(component::MAP_ID) { out.data_mut().map_id = Some(*id); } + if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) { + out.data_mut().repair_cost = (*cost).max(0) as u32; + } + if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + out.data_mut().custom_name = Some(plain(name, &lang)); + } + // The enchantments by the server's registry ids. + let levels = |list: &[(i32, i32)]| -> Vec<(Arc, u32)> { + let names = self.remote.as_ref().map(|r| &r.registries); + list.iter() + .filter_map(|(id, level)| { + let name = names?.name("minecraft:enchantment", *id)?; + Some((Arc::from(name), (*level).max(0) as u32)) + }) + .collect() + }; + if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) { + out.data_mut().enchantments = levels(list); + } + if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) { + out.data_mut().stored_enchantments = levels(list); + } + out.tidy(); Some(out) } fn to_network(&self, s: &Option) -> Option { @@ -1237,6 +1265,7 @@ impl Game<'_> { Some(match menu { "minecraft:loom" => Kind::Loom, "minecraft:stonecutter" => Kind::Stonecutter, + "minecraft:grindstone" => Kind::Grindstone, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index 62a0238dd..643df30db 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -51,7 +51,7 @@ impl Game<'_> { if !self .station .as_ref() - .is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter)) + .is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter | Kind::Grindstone)) { return; } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 30280d034..04104c9b3 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -531,7 +531,6 @@ impl Game<'_> { 64, ), Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64), Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), _ => (true, 64), } @@ -692,13 +691,6 @@ impl Game<'_> { self.move_to(&mut stack, &halves, false); } } - Kind::Grindstone => { - if empty(self, 0) || empty(self, 1) { - self.move_to(&mut stack, &[INPUT, INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } - } Kind::Cartography => { if super::maps::map_id(&stack).is_some() { self.move_to(&mut stack, &[INPUT], false); @@ -724,7 +716,7 @@ impl Game<'_> { self.move_to(&mut stack, targets, false); } // Their clicks run on the menu engine. - Kind::Merchant | Kind::Loom | Kind::Stonecutter => {} + Kind::Merchant | Kind::Loom | Kind::Stonecutter | Kind::Grindstone => {} } } let moved = stack.count != start; @@ -733,6 +725,17 @@ impl Game<'_> { } moved } + /// The grindstone result's `onTake` with a level (`amount`: the menu's + /// `getExperienceAmount` sum): the orbs at the block's centre + /// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound + /// for everyone around. + pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) { + let xp = stations::grindstone_xp_roll(amount, &mut self.world.random); + if xp > 0 { + self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp); + } + self.level_event_at(1042, pos, 0); + } fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) { let at = [ f64::from(pos[0]) + 0.5, @@ -826,28 +829,6 @@ impl Game<'_> { self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); } } - Kind::Grindstone => { - let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); - let mut random = LegacyRandom::new(self.world.random.next_long()); - let xp = stations::grindstone_experience( - &self.res.stations().enchantments, - &mut random, - a.as_ref(), - b.as_ref(), - ); - if xp > 0 { - self.spawn_orbs( - [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ], - xp, - ); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch); - } Kind::Smithing => { for slot in s.inputs.iter_mut() { if let Some(x) = slot.as_mut() { @@ -860,7 +841,7 @@ impl Game<'_> { let pitch = self.world.random.next_float() * 0.1 + 0.9; self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch); } - Kind::Merchant | Kind::Stonecutter => {} + Kind::Merchant | Kind::Stonecutter | Kind::Grindstone => {} Kind::Beacon => {} Kind::Cartography => { for slot in &mut s.inputs { @@ -1066,12 +1047,13 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; - if self - .station - .as_ref() - .is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter)) - { - // LoomMenu, MerchantMenu, StonecutterMenu and the brewing stand's + if self.station.as_ref().is_none_or(|s| { + matches!( + s.kind, + Kind::Loom | Kind::Merchant | Kind::Stonecutter | Kind::Grindstone + ) + }) { + // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu and the brewing stand's // BrewingStandMenu clicks run on the verified menu engine. let input = if shift { horizon_client::menu::Input::QuickMove diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index f46e37abc..814c7a15d 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -418,6 +418,12 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(id), )); } + if d.repair_cost > 0 { + stack.added.push(( + horizon_protocol::item::component::REPAIR_COST, + horizon_protocol::item::Component::Int(d.repair_cost as i32), + )); + } } if let Some(name) = s.custom_name() { stack.added.push(( diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 6c2250f0b..0e85d92dd 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -26,6 +26,8 @@ pub struct Env<'a> { pub banners: &'a Banners, /// The stonecutter's recipes. pub station_recipes: &'a crate::stations::StationRecipes, + /// The grindstone's curse and cost rules. + pub enchantments: &'a crate::enchant::Enchantments, /// What a merchant menu needs for offers made while it is open (level-ups). pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, } @@ -75,6 +77,8 @@ pub enum Kind { Loom, /// `StonecutterMenu`: the input, the result, then the inventory. Stonecutter, + /// `GrindstoneMenu`: two inputs, the result, then the inventory. + Grindstone, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -101,6 +105,7 @@ impl Kind { "crafter_be" => Self::CrafterBlock, "loom" => Self::Loom, "stonecutter" => Self::Stonecutter, + "grindstone" => Self::Grindstone, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -140,6 +145,10 @@ enum Role { MerchantResult, /// The stonecutter's result slot (`onTake` uses up one input). StoneResult, + /// The grindstone's inputs: damageable or enchanted items. + GrindInput, + /// The grindstone's result slot (`onTake` clears both inputs). + GrindResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -191,6 +200,10 @@ pub struct Menu { pub merchant: Option>, /// The stonecutter's recipe list (`recipesForInput`). pub stone: Stonecutter, + /// The grindstone result's `getExperienceAmount` sum before its roll, + /// set when the result was taken: the caller (with a level) awards the + /// orbs and plays level event 1042. + pub ground: Option, } /// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`. @@ -350,6 +363,16 @@ impl Menu { // selectedRecipeIndex: DataSlot.standalone() starts at 0. data = 1; } + Kind::Grindstone => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::GrindInput)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::GrindResult, + }); + player(&mut slots); + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -436,6 +459,7 @@ impl Menu { equipped: Vec::new(), merchant: None, stone: Stonecutter::default(), + ground: None, } } @@ -603,6 +627,15 @@ impl Menu { match self.kind { Kind::Loom => self.loom_changed(env), Kind::Stonecutter => self.stone_changed(env), + // GrindstoneMenu.createResult. + Kind::Grindstone => { + self.containers[RESULT][0] = crate::stations::grindstone_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ); + } Kind::CrafterBlock => self.crafter_result(env), _ => {} } @@ -714,7 +747,10 @@ impl Menu { Role::LoomBanner => Self::is_banner(stack), Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), - Role::LoomResult | Role::MerchantResult | Role::StoneResult => false, + Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), + Role::LoomResult | Role::MerchantResult | Role::StoneResult | Role::GrindResult => { + false + } } } @@ -843,7 +879,12 @@ impl Menu { } // SimpleContainer.removeItem calls setChanged when it took something; // MerchantContainer.removeItem updates the result after a payment slot. - if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter) { + if out.is_some() + && matches!( + self.kind, + Kind::Loom | Kind::Merchant | Kind::Stonecutter | Kind::Grindstone + ) + { self.slot_changed(env, s); } out @@ -880,6 +921,18 @@ impl Menu { self.sounds.push("minecraft:ui.stonecutter.take_result"); return; } + if self.slots[s].role == Role::GrindResult { + // GrindstoneMenu's result onTake: the experience (from the inputs + // before they go), then both inputs cleared. + self.ground = Some(crate::stations::grindstone_xp_base( + env.enchantments, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + )); + self.put(env, 0, None); + self.put(env, 1, None); + return; + } if self.slots[s].role == Role::LoomResult { // LoomMenu's result onTake: one banner and one dye are used up. self.remove(env, 0, 1); @@ -1352,6 +1405,31 @@ impl Menu { return None; } } + Kind::Grindstone => { + after_take = true; + let full = self.containers[MAIN].iter().all(Option::is_some); + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if full { + if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 2, false) { + return None; + } + } Kind::Merchant => { after_take = true; if index == 2 { @@ -2148,12 +2226,14 @@ pub(crate) mod tests { let brewing = Brewing::load(&root, &items); let banners = Banners::load(&root); let station_recipes = crate::stations::StationRecipes::load(&root, &items); + let enchantments = crate::enchant::Enchantments::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: None, }; let mut menu = Menu::new(kind); diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 2fdeeb860..eb0a20a02 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -401,13 +401,13 @@ pub fn grindstone_result( (None, None) => None, } } -/// Experience from the grindstone result slot's `getExperienceAmount`. -pub fn grindstone_experience( +/// The grindstone result slot's `getExperienceAmount` before its roll: the +/// minimum costs of the inputs' non-curse enchantments. +pub fn grindstone_xp_base( e: &Enchantments, - random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>, -) -> u32 { +) -> i32 { let from = |s: Option<&ItemStack>| -> i32 { s.map_or(0, |s| { s.crafting_enchantments() @@ -417,7 +417,10 @@ pub fn grindstone_experience( .sum() }) }; - let amount = from(input) + from(additional); + from(input) + from(additional) +} +/// `getExperienceAmount`'s roll of the sum: `half + nextInt(half)`. +pub fn grindstone_xp_roll(amount: i32, random: &mut LegacyRandom) -> u32 { if amount > 0 { let half = (f64::from(amount) / 2.0).ceil() as i32; (half + random.next_int_bound(half).unwrap_or(0)) as u32 @@ -425,6 +428,15 @@ pub fn grindstone_experience( 0 } } +/// Experience from the grindstone result slot's `getExperienceAmount`. +pub fn grindstone_experience( + e: &Enchantments, + random: &mut LegacyRandom, + input: Option<&ItemStack>, + additional: Option<&ItemStack>, +) -> u32 { + grindstone_xp_roll(grindstone_xp_base(e, input, additional), random) +} // ---------------------------------------------------------------- smithing & stonecutting diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index aaa6a0677..c05f92322 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -179,6 +179,7 @@ public final class VanillaMenuOracle { } case "loom" -> new LoomMenu(0, inv); case "stonecutter" -> new StonecutterMenu(0, inv); + case "grindstone" -> new GrindstoneMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 20e5062bb..fd899e6c6 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -42,6 +42,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - stonecutter: a stonecutter opens on the guest's screen with the recipes of the stone the guest puts in; the guest picks the slab and shift-clicks the result, and the server has cut every stone into slabs (#868); +- grindstone: a grindstone opens on the guest's screen; the enchanted sword the guest shift-clicks in + shows the server's result, and the guest takes it with only its curse left and the + experience orbs the server awards (#868); - feedback: the guest's command feedback names the guest and shows the numbers; - chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the server thread the host window's too; @@ -136,7 +139,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -993,6 +996,51 @@ def check_stonecutter(host, guest, out): return seen +def server_reply(guest, command, *needles): + """The first chat line holding every needle after the guest runs `command`.""" + since = guest.raw('events')['last'] + guest('command', command=command) + for _ in range(0, 65): + reply = guest.raw('events', '--since', since) + for e in reply['events']: + line = e.get('text', '') + if e.get('event') == 'chat' and all(n in line for n in needles): + return line + guest.wait(2) + raise Failed(f'no answer to {command}') + + +def check_grindstone(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='xp set @s 0 levels') + guest('command', command='xp set @s 0 points') + guest('command', command='give @s minecraft:iron_sword[minecraft:enchantments={"minecraft:sharpness":3,' + '"minecraft:vanishing_curse":1},minecraft:damage=100]') + at = open_station(guest, 'grindstone', out, 'grindstone') + # GrindstoneMenu.quickMoveStack: with both inputs empty, into the first. + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:iron_sword'), 'shift') + guest.wait(10) + loaded = station_slots(guest) + guest.shot(out, 'grindstone-result') + guest.raw('click-slot', 650, 'shift') + # The orbs (sharpness III: 12 to 23 points) fly to the guest. + guest.wait(60) + left = station_slots(guest) + close_station(guest, at) + sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components', + 'minecraft:damage') + xp = server_reply(guest, 'xp query @s points', 'experience points') + seen = {'loaded': loaded, 'left': left, 'curse kept': 'vanishing_curse' in sword, + 'sharpness gone': 'sharpness' not in sword, + 'damage': re.search(r'minecraft:damage"?: 100\b', sword) is not None, + 'xp': int(re.search(r'has (\d+) experience', xp).group(1)) > 0} + want = {'loaded': {600: ('minecraft:iron_sword', 1), 650: ('minecraft:iron_sword', 1)}, 'left': {}, + 'curse kept': True, 'sharpness gone': True, 'damage': True, 'xp': True} + assert seen == want, f'the grindstone on the guest: {seen} ({sword!r}, {xp!r})' + return seen + + def slot_point(game, slot): """The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N).""" for w in game.raw('ui')['widgets']: @@ -2186,6 +2234,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'brewing': check_brewing, 'loom': check_loom, 'stonecutter': check_stonecutter, + 'grindstone': check_grindstone, 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index d4b7e86be..357ad94da 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -11,7 +11,8 @@ item the first click moved) over the player inventory, crafting table, chests, hopper, dispenser, shulker box, the furnaces, the brewing stand, the crafter (the client's menu, and the server's over the block entity with slot state packets), the loom (with its pattern buttons), the -stonecutter (with its recipe buttons) and the +stonecutter (with its recipe buttons), the grindstone (enchanted, damaged and +cursed tools and books) and the server's furnace menus over their block entities (`*_be`: a new input restarts cooking, other clicks keep its progress). After every click the slots, carried stack, data slots and drops are compared. @@ -27,7 +28,7 @@ except ImportError: MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, - 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, 'stonecutter': 1, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} @@ -45,6 +46,10 @@ COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_i # Stonecutter inputs (several recipes each), and a block it doesn't cut. CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sandstone', 'quartz_block', 'deepslate', 'stone_bricks', 'oak_planks'] +# Grindstone inputs: tools and armor, books, and their enchantments (curses too). +GRINDABLE = ['iron_sword', 'diamond_pickaxe', 'bow', 'iron_helmet', 'elytra', 'shield', 'fishing_rod', 'trident'] +ENCHANTS = ['sharpness', 'unbreaking', 'mending', 'efficiency', 'protection', 'power', 'looting', 'fortune', + 'binding_curse', 'vanishing_curse'] def quote(text): @@ -109,6 +114,33 @@ class Gen: return snbt('minecraft:' + rng.choice(CUTTABLE), rng.choice([1, 1, 2, 3, 10, 63, 64])) return self.stack() + def grind_stack(self): + """Mostly an enchanted or damaged tool or an enchanted book, sometimes anything.""" + rng = self.rng + roll = rng.random() + if roll > 0.8: + return self.stack() + levels = ','.join('"minecraft:%s":%d' % (e, rng.randrange(1, 4)) + for e in rng.sample(ENCHANTS, rng.choice([0, 1, 1, 2, 3]))) + comps = [] + if roll < 0.25: + item = 'minecraft:' + rng.choice(['enchanted_book', 'enchanted_book', 'book']) + if levels: + comps.append('"minecraft:stored_enchantments":{%s}' % levels) + count = 1 if rng.random() < 0.85 else 2 + else: + item = 'minecraft:' + rng.choice(GRINDABLE) + info = self.items.get(item, {}) + if levels: + comps.append('"minecraft:enchantments":{%s}' % levels) + if info.get('minecraft:max_damage') and rng.random() < 0.6: + comps.append('"minecraft:damage":%d' % rng.randrange(0, info['minecraft:max_damage'])) + count = 1 + if rng.random() < 0.2: + comps.append('"minecraft:repair_cost":%d' % rng.choice([1, 3, 7])) + body = ',components:{%s}' % ','.join(comps) if comps else '' + return '{id:%s,count:%d%s}' % (quote(item), count, body) + def recipe(self, slots, width, start=1): """Fills the crafting grid (slots `start`..) with a small known recipe.""" rng = self.rng @@ -142,6 +174,9 @@ class Gen: if menu == 'stonecutter' and rng.random() < 0.2: out.append([1, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) continue + if menu == 'grindstone' and rng.random() < 0.2: + out.append([2, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) + continue if menu == 'crafter_be' and rng.random() < 0.2: out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE']) continue @@ -208,6 +243,16 @@ def main(): slots[0] = g.cut_stack() if rng.random() < 0.8 else '-' # The result follows the input and the selected recipe; a fixture stack there is rare. slots[1] = '-' if rng.random() < 0.9 else g.cut_stack() + if menu == 'grindstone': + for i in rng.sample(range(3, size), 10): + slots[i] = g.grind_stack() + slots[0] = g.grind_stack() if rng.random() < 0.7 else '-' + slots[1] = g.grind_stack() if rng.random() < 0.6 else '-' + # Two of the same tool, so mergeItems runs. + if slots[0] != '-' and rng.random() < 0.3: + slots[1] = slots[0] if rng.random() < 0.4 else g.grind_stack() + # The result follows the inputs; a fixture stack there is rare. + slots[2] = '-' if rng.random() < 0.9 else g.grind_stack() if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -236,7 +281,7 @@ def main(): if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) return 0 - carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' + carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack, 'grindstone': g.grind_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' if carried_food is not None: carried = carried_food cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,