From b5a92262c8cc69bb5e5d783694ad327878a30f5b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:42:47 +0200 Subject: [PATCH] Enchanting table on the menu engine; LAN guests enchant EnchantmentMenu now runs on horizon_client::menu: the item slot (one item) and the lapis slot, its quickMoveStack, slotsChanged clearing the offers without an enchantable item, and clickMenuButton's checks against the costs, lapis and levels, verified against the vanilla class by test_menu_click_parity (with its ten data slots and the offer buttons; the oracle's player now has a profile for the invalid-button log line). The offers and the enchanting itself, which need a level, stay with the caller. Single player routes the table's clicks, drags and double clicks through the engine. The LAN host opens minecraft:enchantment for guests with their own enchantment seed (saved with their player data), sends the costs, seed and clues as data slots, and on ContainerButtonClick enchants the item, takes the guest's level and lapis and gives a new seed. Guests show the server's offers and send the button the client menu accepts. Part of #868. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 22 ++++ .../horizon-client/src/game/lan_crafting.rs | 2 +- .../horizon-client/src/game/lan_stations.rs | 87 ++++++++++++- crates/horizon-client/src/game/remote.rs | 1 + .../src/game/remote_stations.rs | 18 +++ crates/horizon-client/src/game/stations.rs | 38 +++--- crates/horizon-client/src/lan/guest.rs | 3 + crates/horizon-client/src/lan/playerdata.rs | 2 + crates/horizon-client/src/menu.rs | 116 +++++++++++++++++- .../horizonlab/parity/VanillaMenuOracle.java | 3 + tools/lan_e2e.py | 35 +++++- tools/test_menu_click_parity.py | 23 +++- 12 files changed, 326 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2056e52ed..dec8588eb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5438,6 +5438,7 @@ impl Game<'_> { let grindstone_open = station_kind == Some(stations::Kind::Grindstone); let anvil_open = station_kind == Some(stations::Kind::Anvil); let smithing_open = station_kind == Some(stations::Kind::Smithing); + let enchanting_open = station_kind == Some(stations::Kind::Enchanting); 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]; @@ -5478,6 +5479,11 @@ impl Game<'_> { ]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Grindstone, v) + } else if enchanting_open { + // EnchantmentMenu: the item, the lapis, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Enchanting, v) } else if anvil_open || smithing_open { // ItemCombinerMenu: the inputs, the result, then the inventory. let inputs = if anvil_open { 2 } else { 3 }; @@ -5647,6 +5653,17 @@ impl Game<'_> { menu.stone = state; menu.set_slot(&env, 1, before[1].clone()); } + if kind == Kind::Enchanting + && let Some(s) = self.station.as_ref() + { + // The offers between clicks (what copying the slots in flagged is not a change). + menu.enchant_changed = false; + for i in 0..3 { + menu.data[i] = s.offers.costs[i]; + menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32); + } + menu.data[3] = self.level.xp_seed; + } if let Some((disabled, triggered)) = crafter_data { for (i, d) in disabled.iter().enumerate() { menu.data[i] = i32::from(*d); @@ -5724,6 +5741,11 @@ impl Game<'_> { if kind == Kind::Anvil || kind == Kind::Smithing { self.combiner_session_end(&menu, predicting); } + if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned()) + { + // EnchantmentMenu.slotsChanged: new offers for the item. + self.station_changed(); + } 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 9c0cce1fe..96dc99c14 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -84,7 +84,7 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { } impl Game<'_> { - fn menu_env(&self) -> Env<'_> { + pub(super) fn menu_env(&self) -> Env<'_> { Env { items: self.res.items(), recipes: self.res.recipes(), diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 8d31ba05e..5dfb79752 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -14,6 +14,7 @@ use horizon_client::{ items::ItemStack, menu::{Kind, Menu}, }; +use horizon_core::random::RandomSource; use horizon_protocol::packets::play::{self, Clientbound as C}; /// A guest's open workstation menu. @@ -38,6 +39,7 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:grindstone", Kind::Grindstone, 0..2), StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2), StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), + StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), _ => return None, }) } @@ -62,12 +64,22 @@ impl Game<'_> { let Some(window) = host.hub.open_window(conn, menu_type, title) else { return true; }; + let mut menu = Box::new(Menu::new(kind)); + if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && kind == Kind::Enchanting + { + // Player.enchantmentSeed, made when first needed. + if g.xp_seed == 0 { + g.xp_seed = self.world.random.next_int(); + } + menu.data[3] = g.xp_seed; + } host.play.entry(conn).or_default().station = Some(GuestStation { window, state: 0, kind: station.kind, pos: station.pos, - menu: Box::new(Menu::new(kind)), + menu, sent_data: Vec::new(), last_sound: 0, }); @@ -101,6 +113,12 @@ impl Game<'_> { self.grindstone_taken(gs.pos, amount); } self.lan_station_combined(host, conn, &mut gs); + if let Some(button) = gs.menu.enchant_button.take() { + self.lan_enchant(host, gi, &mut gs, button); + } + if std::mem::take(&mut gs.menu.enchant_changed) { + self.lan_enchant_offers(host, gi, &mut gs); + } } host.play.entry(conn).or_default().station = Some(gs); self.lan_send_station(host, conn); @@ -127,6 +145,73 @@ impl Game<'_> { } } + /// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for + /// the guest's seed and the bookshelves around the table. + fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) { + let seed = host.hub.guests[gi].xp_seed; + let bookcases = self.count_bookshelves(gs.pos); + let offers = horizon_client::stations::enchant_offers( + &self.res.stations().enchantments, + self.res.items(), + seed, + bookcases, + gs.menu.slot(0), + ); + for i in 0..3 { + gs.menu.data[i] = offers.costs[i]; + let clue = offers.clues[i].as_ref(); + gs.menu.data[4 + i] = clue + .and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e)) + .unwrap_or(-1); + gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32); + } + gs.menu.data[3] = seed; + } + + /// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets + /// the offer's enchantments, the guest pays its levels and lapis and + /// gets a new seed, the table sounds, and the offers are made again. + fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) { + let Some(item) = gs.menu.slot(0).cloned() else { + return; + }; + let g = &host.hub.guests[gi]; + let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn); + let Some(enchanted) = horizon_client::stations::apply_enchantment( + &self.res.stations().enchantments, + self.res.items(), + seed, + button, + gs.menu.data[button], + &item, + ) else { + return; + }; + let need = button as i32 + 1; + // Player.onEnchantmentPerformed. + self.as_guest(host, conn, |game| game.give_levels(-need)); + host.hub.guests[gi].xp_seed = self.world.random.next_int(); + let env = self.menu_env(); + let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| { + l.count = l.count.saturating_sub(need as u32); + l + }); + gs.menu.set_slot(&env, 0, Some(enchanted)); + if !creative { + gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0)); + } + gs.menu.enchant_changed = false; + self.lan_enchant_offers(host, gi, gs); + let pitch = self.world.random.next_float() * 0.1 + 0.9; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + self.audio.play( + "minecraft:block.enchantment_table.use", + Some(at), + 1.0, + pitch, + ); + } + /// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil /// takes the name (`AnvilMenu.setItemName`). pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ebd1e2e58..ed900ebf9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1268,6 +1268,7 @@ impl Game<'_> { "minecraft:grindstone" => Kind::Grindstone, "minecraft:anvil" => Kind::Anvil, "minecraft:smithing" => Kind::Smithing, + "minecraft:enchantment" => Kind::Enchanting, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index fd5dc42aa..52e60ed76 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -79,6 +79,24 @@ impl Game<'_> { (Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(), // AnvilMenu.cost. (Kind::Anvil, 0) => s.anvil.cost = i32::from(value), + // EnchantmentMenu: costs, the seed (the screen's glyph names), + // the clues' enchantments and levels. + (Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value), + (Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value), + (Kind::Enchanting, 4..7) => { + let name = self.remote.as_ref().and_then(|r| { + r.registries + .name("minecraft:enchantment", i32::from(value)) + .map(std::sync::Arc::::from) + }); + let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l); + s.offers.clues[id - 4] = name.map(|n| (n, level)); + } + (Kind::Enchanting, 7..10) => { + if let Some((_, level)) = s.offers.clues[id - 7].as_mut() { + *level = value.max(0) as u32; + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index ed114419e..7820bd88b 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -131,7 +131,7 @@ pub(super) struct Station { pub(super) pos: [i32; 3], pub(super) inputs: Vec>, pub(super) result: Option, - offers: EnchantOffers, + pub(super) offers: EnchantOffers, bookcases: i32, pub(super) anvil: AnvilResult, /// Anvil rename box text. @@ -391,7 +391,7 @@ impl Game<'_> { _ => &mut self.scratch_slot, } } - fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { + pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { let tags = &self.res.items().block_tags; let is = |p: [i32; 3], tag: &str| { let name = &self @@ -435,6 +435,16 @@ impl Game<'_> { let data = self.res.stations(); let items = self.res.items(); match s.kind { + // A server's table: its data slots carry the offers, and its + // client menu only clears them without an enchantable item. + Kind::Enchanting if self.remote.is_some() => { + let enchantable = s.inputs[0].as_ref().is_some_and(|i| { + data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty() + }); + if !enchantable { + s.offers = Default::default(); + } + } Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); s.offers = stations::enchant_offers( @@ -521,7 +531,6 @@ impl Game<'_> { } let i = slot - INPUT; match s.kind { - Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), Kind::Loom => (false, 64), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), @@ -532,7 +541,6 @@ impl Game<'_> { ), 64, ), - Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), _ => (true, 64), } } @@ -669,21 +677,10 @@ impl Game<'_> { if slot >= INPUT { // An input slot: into the inventory, the hotbar's last slot first // where vanilla moves in reverse. - let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon); + let reverse = kind == Kind::Beacon; self.move_to(&mut stack, &Self::player_slots(), reverse); } else { match kind { - Kind::Enchanting => { - if &*stack.item == "minecraft:lapis_lazuli" { - self.move_to(&mut stack, &[INPUT + 1], true); - } else if empty(self, 0) { - *self.station_slot_mut(INPUT) = Some(ItemStack { - count: 1, - ..stack.clone() - }); - stack.count -= 1; - } - } Kind::Beacon => { if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1 { @@ -710,7 +707,8 @@ impl Game<'_> { | Kind::Stonecutter | Kind::Grindstone | Kind::Anvil - | Kind::Smithing => {} + | Kind::Smithing + | Kind::Enchanting => {} } } let moved = stack.count != start; @@ -940,6 +938,11 @@ impl Game<'_> { { return; } + if self.remote.is_some() { + // EnchantmentScreen.mouseClicked: the client menu took it, the server enchants. + self.remote_station_button(button as i32); + return; + } let Some(enchanted) = stations::apply_enchantment( &self.res.stations().enchantments, self.res.items(), @@ -1058,6 +1061,7 @@ impl Game<'_> { | Kind::Grindstone | Kind::Anvil | Kind::Smithing + | Kind::Enchanting ) }) { // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu, AnvilMenu, diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 814c7a15d..8440fac6c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -147,6 +147,8 @@ pub struct Guest { pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, + /// `Player.enchantmentSeed` (the enchanting table's offers). + pub xp_seed: i32, /// Active status effects (`LivingEntity.activeEffects`). pub effects: crate::effects::PlayerEffects, /// What the client was told of each effect: id, amplifier, flags, and @@ -273,6 +275,7 @@ impl Guest { xp_level: 0, xp_progress: 0.0, xp_total: 0, + xp_seed: 0, effects: Default::default(), sent_effects: Vec::new(), menu_sent: vec![None; 46], diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index d7dc097dd..8797f25a2 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_level = level.xp_level; guest.xp_progress = level.xp_progress; guest.xp_total = level.xp_total; + guest.xp_seed = level.xp_seed; guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.flying = level.flying; @@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.xp_level = guest.xp_level; level.xp_progress = guest.xp_progress; level.xp_total = guest.xp_total; + level.xp_seed = guest.xp_seed; level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 510a7c7aa..c4354b184 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -86,6 +86,9 @@ pub enum Kind { Anvil, /// `SmithingMenu`: template, base, addition, the result, then the inventory. Smithing, + /// `EnchantmentMenu`: the item, the lapis, then the inventory; its data + /// slots are the three costs, the seed and the clues. + Enchanting, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -115,6 +118,7 @@ impl Kind { "grindstone" => Self::Grindstone, "anvil" => Self::Anvil, "smithing" => Self::Smithing, + "enchanting" => Self::Enchanting, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -162,6 +166,10 @@ enum Role { SmithInput(usize), /// `ItemCombinerMenu`'s result slot (the anvil's and the smithing table's). CombineResult, + /// The enchanting table's item slot (one item). + EnchantItem, + /// The enchanting table's lapis slot. + Lapis, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -227,6 +235,13 @@ pub struct Menu { /// a level) runs the rest of its `onTake` (the anvil's wear and level /// event 1030 or 1029, the smithing table's 1044). pub combined: bool, + /// The enchanting table's item changed to an enchantable one: the caller + /// (with a level) fills the costs and clues (`slotsChanged`'s + /// `access.execute`). + pub enchant_changed: bool, + /// An enchanting button the menu took (`clickMenuButton` passed its + /// checks): the caller (with a level) enchants. + pub enchant_button: Option, } /// `AnvilMenu`'s state besides its slots and `cost`. @@ -435,6 +450,22 @@ impl Menu { // hasRecipeError. data = 1; } + Kind::Enchanting => { + containers[MAIN] = vec![None; 2]; + slots.push(Slot { + container: MAIN, + index: 0, + role: Role::EnchantItem, + }); + slots.push(Slot { + container: MAIN, + index: 1, + role: Role::Lapis, + }); + player(&mut slots); + // costs[3], enchantmentSeed, enchantClue[3], levelClue[3]. + data = 10; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -526,7 +557,18 @@ impl Menu { level_change: 0, anvil: Anvil::default(), combined: false, + enchant_changed: false, + enchant_button: None, } + .with_initial_data() + } + + /// Data slots that do not start at 0: the enchanting table's clues are -1. + fn with_initial_data(mut self) -> Self { + if self.kind == Kind::Enchanting { + self.data[4..].fill(-1); + } + self } pub fn kind(&self) -> Kind { @@ -536,6 +578,9 @@ impl Menu { /// `clickMenuButton`: the loom's pattern buttons and the stonecutter's /// recipes. False when refused. pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind == Kind::Enchanting { + return self.enchant_click(id); + } if self.kind == Kind::Stonecutter { // StonecutterMenu.clickMenuButton: an invalid index is taken too. if self.data[0] == id { @@ -709,6 +754,7 @@ impl Menu { } Kind::CrafterBlock => self.crafter_result(env), Kind::Anvil => self.anvil_result(env), + Kind::Enchanting => self.enchant_changed(env), Kind::Smithing => { self.smith_result(env); self.smith_error(); @@ -717,6 +763,44 @@ impl Menu { } } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and + /// the levels (creative pays nothing). The enchanting itself needs a + /// level and is the caller's (`enchant_button`). + fn enchant_click(&mut self, id: i32) -> bool { + let Some(i) = usize::try_from(id).ok().filter(|&i| i < 3) else { + return false; + }; + let need = id + 1; + let lapis = self.containers[MAIN][1] + .as_ref() + .map_or(0, |l| l.count as i32); + if lapis < need && !self.creative { + return false; + } + if self.data[i] <= 0 + || self.containers[MAIN][0].is_none() + || (self.levels < need || self.levels < self.data[i]) && !self.creative + { + return false; + } + self.enchant_button = Some(i); + true + } + + /// `EnchantmentMenu.slotsChanged`: no costs or clues without an + /// enchantable item; with one, a level fills them (`enchant_changed`). + fn enchant_changed(&mut self, env: &Env) { + let enchantable = self.containers[MAIN][0].as_ref().is_some_and(|s| { + env.enchantments.enchantable(&s.item) > 0 && s.enchantments().is_empty() + }); + if enchantable { + self.enchant_changed = true; + } else { + self.data[..3].fill(0); + self.data[4..].fill(-1); + } + } + /// `AnvilMenu.createResult`. fn anvil_result(&mut self, env: &Env) { let hover = self.containers[MAIN][0] @@ -887,6 +971,8 @@ impl Menu { Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), + Role::EnchantItem => true, + Role::Lapis => &*stack.item == "minecraft:lapis_lazuli", Role::LoomResult | Role::MerchantResult | Role::StoneResult @@ -931,7 +1017,7 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) | Role::Potion => 1, + Role::Armor(_) | Role::Potion | Role::EnchantItem => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -1033,6 +1119,7 @@ impl Menu { | Kind::Grindstone | Kind::Anvil | Kind::Smithing + | Kind::Enchanting ) { self.slot_changed(env, s); @@ -1625,6 +1712,33 @@ impl Menu { return None; } } + Kind::Enchanting => { + after_take = true; + if index < 2 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if &*stack.item == "minecraft:lapis_lazuli" { + if !self.move_to(env, &mut stack, 1, 2, true) { + return None; + } + } else { + // One item into the empty item slot (setByPlayer). + if self.containers[MAIN][0].is_some() { + return None; + } + let single = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + // The source slot keeps the rest while the item slot changes. + let slot = self.slots[index]; + self.containers[slot.container][slot.index] = + (stack.count > 0).then(|| stack.clone()); + self.set_by_player(env, 0, Some(single)); + } + } Kind::Anvil | Kind::Smithing => { // ItemCombinerMenu.quickMoveStack. after_take = true; 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 d55417e7c..5a3db5977 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -182,6 +182,7 @@ public final class VanillaMenuOracle { case "grindstone" -> new GrindstoneMenu(0, inv); case "anvil" -> new AnvilMenu(0, inv); case "smithing" -> new SmithingMenu(0, inv); + case "enchanting" -> new EnchantmentMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } @@ -231,6 +232,8 @@ public final class VanillaMenuOracle { set(player, ServerPlayer.class, "connection", make(Connection.class)); // AnvilMenu.onTake filters a new name; the anvil's result needs the levels. set(player, ServerPlayer.class, "textFilter", net.minecraft.server.network.TextFilter.DUMMY); + // EnchantmentMenu.clickMenuButton names the player on an invalid button. + set(player, Player.class, "gameProfile", new com.mojang.authlib.GameProfile(new java.util.UUID(0, 1), "Oracle")); player.experienceLevel = f.has("levels") ? f.get("levels").getAsInt() : 0; var inv = new Inventory(player, new EntityEquipment()); player.inv = inv; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 10b654adb..958b80b4d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -48,6 +48,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - anvil: an anvil opens on the guest's screen; the guest repairs a sword with iron ingots and renames it (ServerboundRenameItemPacket), takes it for the server's level cost, and the server has the repaired, renamed sword (#868); +- enchanting: an enchanting table opens on the guest's screen with the server's offers for the + sword the guest puts in; the guest clicks the first offer and the server enchants the + sword for a level and a lapis (#868); - smithing: a smithing table opens on the guest's screen; the guest upgrades a diamond sword to netherite and the server has it (#868); - feedback: the guest's command feedback names the guest and shows the numbers; @@ -144,7 +147,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', 'grindstone', 'anvil', 'smithing', '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', 'anvil', 'smithing', 'enchanting', '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: @@ -1109,6 +1112,35 @@ def check_smithing(host, guest, out): return seen +def check_enchanting(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='xp set @s 30 levels') + guest('command', command='give @s minecraft:iron_sword') + guest('command', command='give @s minecraft:lapis_lazuli 3') + at = open_station(guest, 'enchanting_table', out, 'enchanting') + # EnchantmentMenu.quickMoveStack: the sword to the item slot, the lapis to its own. + for item in ('iron_sword', 'lapis_lazuli'): + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + guest.wait(10) + costs = guest.raw('menu')['info']['costs'] + guest.shot(out, 'enchanting-offers') + # EnchantmentScreen's first offer button (clickMenuButton 0). + guest.raw('click-gui', 110, 23) + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}]', 'iron_sword') + levels = server_reply(guest, 'xp query @s levels', 'experience levels') + seen = {'offered': costs[0] > 0, 'enchanted': 'minecraft:enchantments' in sword, + 'left': left.get(601), 'levels': int(re.search(r'has (\d+) experience', levels).group(1)), + 'lapis': server_count(guest, 'lapis_lazuli')} + want = {'offered': True, 'enchanted': True, 'left': ('minecraft:lapis_lazuli', 2), 'levels': 29, 'lapis': 2} + assert seen == want, f'the enchanting table on the guest: {seen} ({costs}, {sword!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']: @@ -2305,6 +2337,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'grindstone': check_grindstone, 'anvil': check_anvil, 'smithing': check_smithing, + 'enchanting': check_enchanting, '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 06ba00dd9..41561fbb9 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -13,7 +13,8 @@ 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), the grindstone (enchanted, damaged and cursed tools and books), the anvil (repairs, enchantment merges and renames, -with the player's levels) and the smithing table (upgrades and trims) and the +with the player's levels), the smithing table (upgrades and trims), the +enchanting table (its button checks against the costs, lapis and levels) 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. @@ -29,9 +30,9 @@ 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, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, '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, + 'stonecutter': 1, 'enchanting': 10, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] @@ -223,6 +224,10 @@ class Gen: result = 2 if menu == 'anvil' else 3 out.append([result, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) continue + if menu == 'enchanting' and rng.random() < 0.25: + # An offer button (clickMenuButton), sometimes out of range. + out.append([rng.choice([0, 1, 2, 2, 3, -1]), 0, 'BUTTON']) + 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 @@ -316,6 +321,14 @@ def main(): for i in range(3): slots[i] = g.smith_stack(i) if rng.random() < 0.75 else '-' slots[3] = '-' if rng.random() < 0.9 else g.smith_stack() + if menu == 'enchanting': + lapis = lambda: snbt('minecraft:lapis_lazuli', rng.choice([1, 2, 3, 5, 64])) + enchantable = lambda: snbt('minecraft:' + rng.choice(['iron_sword', 'book', 'diamond_pickaxe', 'bow', + 'golden_helmet', 'fishing_rod']), 1) + for i in rng.sample(range(2, size), 10): + slots[i] = rng.choice([lapis, enchantable, g.grind_stack])() + slots[0] = rng.choice([enchantable, enchantable, g.grind_stack, g.stack])() if rng.random() < 0.8 else '-' + slots[1] = lapis() if rng.random() < 0.7 else rng.choice(['-', g.stack()]) if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -343,6 +356,10 @@ def main(): return rng.choice([0, 0, 1]) if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) + if menu == 'enchanting': + # costs, the seed, then the clues + return [rng.choice([0, 1, 2, 5, 15, 30]) for _ in range(3)][0] if i < 3 else \ + rng.randrange(-2**15, 2**15) if i == 3 else rng.choice([-1, -1, 0, 3, 12]) return 0 carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack, 'grindstone': g.grind_stack, 'anvil': g.anvil_stack, 'smithing': g.smith_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-'