From ca5404e52dcdf4c2cfcff16876e84946fba5bf79 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:11:32 +0200 Subject: [PATCH] Beacon on the menu engine; LAN guests use beacons BeaconMenu now runs on horizon_client::menu (Kind::Beacon): the payment slot (beacon_payment_items, one item), quickMoveStack and updateEffects with BeaconBlockEntity.validateEffects, verified against the vanilla class by test_menu_click_parity with a new SET_BEACON op (valid and invalid powers for each pyramid level). ServerboundSetBeaconPacket is now in the protocol. The LAN host opens minecraft:beacon for guests with the block entity's levels and powers as data slots (kept current while the menu is open), applies a guest's powers to the block entity (power_select while the beam is up) and drops the payment when the menu closes, as BeaconMenu.removed does. Guests show the server's levels and powers and their Done button sends the packet. Single player's beacon clicks go through the engine too. Part of #868. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/menu_fixture.rs | 22 ++++ crates/horizon-client/src/game.rs | 6 ++ crates/horizon-client/src/game/beacon.rs | 22 ++-- crates/horizon-client/src/game/lan_actions.rs | 1 + .../horizon-client/src/game/lan_stations.rs | 95 +++++++++++++++- crates/horizon-client/src/game/remote.rs | 10 +- .../src/game/remote_stations.rs | 11 ++ crates/horizon-client/src/game/stations.rs | 25 ++--- crates/horizon-client/src/lan/hub.rs | 5 + crates/horizon-client/src/menu.rs | 102 +++++++++++++++++- crates/horizon-protocol/src/packets/play.rs | 13 +++ .../horizonlab/parity/VanillaMenuOracle.java | 15 +++ tools/lan_e2e.py | 44 +++++++- tools/test_menu_click_parity.py | 28 ++++- 14 files changed, 370 insertions(+), 29 deletions(-) diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 984f024c1..20d79e168 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -11,6 +11,7 @@ use horizon_client::{ items::Items, menu::{Env, Input, Kind, Menu}, }; +use horizon_protocol::registry::Ids; use serde_json::Value; use std::{fs, path::Path}; @@ -57,6 +58,13 @@ fn main() -> horizon_client::Result<()> { names: &names, trade: None, }; + // The mob effects' network ids (BeaconMenu.encodeEffect). + let builtin = horizon_protocol::registry::Builtin::find(root) + .and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok()); + let effects = builtin + .as_ref() + .and_then(|b| b.get("minecraft:mob_effect")) + .cloned(); let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; @@ -113,6 +121,20 @@ fn main() -> horizon_client::Result<()> { out += &format!("{}\n", state(&menu)); continue; } + // ServerboundSetBeaconPacket: BeaconMenu.updateEffects. + "SET_BEACON" => { + fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> { + let name = v.as_str()?; + Some((ids?.id(name)?, name)) + } + let (primary, secondary) = ( + power(effects.as_ref(), &op[3]), + power(effects.as_ref(), &op[4]), + ); + menu.beacon_update(&env, primary, secondary); + out += &format!("{}\n", state(&menu)); + continue; + } // ServerboundContainerSlotStateChangedPacket. "SLOT_STATE" => { if (0..9).contains(&slot) { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dec8588eb..d858aeaef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5439,6 +5439,7 @@ impl Game<'_> { 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 beacon_open = station_kind == Some(stations::Kind::Beacon); 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]; @@ -5484,6 +5485,11 @@ impl Game<'_> { 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 beacon_open { + // BeaconMenu: the payment, then the inventory. + let mut v = vec![Some(stations::INPUT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Beacon, v) } else if anvil_open || smithing_open { // ItemCombinerMenu: the inputs, the result, then the inventory. let inputs = if anvil_open { 2 } else { 3 }; diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 79cf14541..c8a0bcba6 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -15,6 +15,7 @@ use horizon_client::{ mesher::Vertex, mobs::render::{DYE, DYE_NAMES}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; /// The beacon screen is 54 px wider than the 176-px menus it shares an origin with. pub(super) const SHIFT: f32 = -27.0; @@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [ "minecraft:diamond", "minecraft:netherite_ingot", ]; -pub(super) fn is_payment(item: &str) -> bool { - PAYMENT.contains(&item) -} /// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin. pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> { Some(match i { @@ -171,7 +169,7 @@ impl Game<'_> { } } } - fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { + pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { let at = [ f64::from(p[0]) + 0.5, f64::from(p[1]) + 0.5, @@ -255,9 +253,13 @@ impl Game<'_> { } } fn beacon_levels(&self) -> i32 { - let Some(pos) = self.station.as_ref().map(|s| s.pos) else { + let Some(s) = self.station.as_ref() else { return 0; }; + if let Some(levels) = s.beacon_levels { + return levels; + } + let pos = s.pos; match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { Some(BlockEntity::Beacon(b)) => b.levels, _ => 0, @@ -346,8 +348,16 @@ impl Game<'_> { self.screen = super::Screen::Playing; self.capture(true); } - /// `BeaconMenu.updateEffects`: spend the payment and set the powers. + /// `BeaconMenu.updateEffects`: spend the payment and set the powers. On + /// a server, `BeaconScreen`'s confirm button sends them + /// (`ServerboundSetBeaconPacket`) and the server's menu does it. fn confirm_beacon(&mut self, sel: [Option; 2]) { + if self.remote.is_some() { + let id = |e: Option| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0)); + let (primary, secondary) = (id(sel[0]), id(sel[1])); + self.send(S::SetBeacon(play::SetBeacon { primary, secondary })); + return; + } let Some(s) = self.station.as_mut() else { return; }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 655a11cbd..2ebe7a90b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -921,6 +921,7 @@ impl Game<'_> { self.lan_station_button(host, conn, p.container, p.button); } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary), S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 5dfb79752..0d04dfe11 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -11,6 +11,7 @@ use super::{ stations::{Kind as StationKind, Station}, }; use horizon_client::{ + containers::BlockEntity, items::ItemStack, menu::{Kind, Menu}, }; @@ -40,6 +41,7 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:anvil", Kind::Anvil, 0..2), StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), + StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1), _ => return None, }) } @@ -74,6 +76,9 @@ impl Game<'_> { } menu.data[3] = g.xp_seed; } + if kind == Kind::Beacon { + menu.data = self.beacon_data(host, station.pos).to_vec(); + } host.play.entry(conn).or_default().station = Some(GuestStation { window, state: 0, @@ -329,13 +334,92 @@ impl Game<'_> { }; // AbstractContainerMenu.removed: the carried stack first, then the inputs. let mut back: Vec = host.hub.guests[gi].carried.take().into_iter().collect(); - back.extend(station_inputs(&gs)); + let inputs = station_inputs(&gs); + if gs.kind == StationKind::Beacon { + // BeaconMenu.removed drops the payment (player.drop). + if !back.is_empty() { + self.lan_place_back(host, gi, std::mem::take(&mut back)); + } + self.drop_guest_items(host, gi, inputs); + } else { + back.extend(inputs); + } if !back.is_empty() { self.lan_place_back(host, gi, back); } true } + /// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers + /// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none). + fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] { + let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return [0; 3]; + }; + let encode = |e: &Option| { + e.as_deref() + .and_then(|n| host.hub.registry_id("minecraft:mob_effect", n)) + .map_or(0, |id| id + 1) + }; + [b.levels, encode(&b.primary), encode(&b.secondary)] + } + + /// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's + /// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they + /// become the block entity's (`dataAccess.set`: the power_select sound + /// while the beam is up). + pub(super) fn lan_station_beacon( + &mut self, + host: &mut LanHost, + conn: u32, + primary: Option, + secondary: Option, + ) { + let Some(pos) = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .filter(|s| s.kind == StationKind::Beacon) + .map(|s| s.pos) + else { + return; + }; + // An id the registry doesn't have fails the packet's codec. + let mut powers: [Option<(i32, String)>; 2] = [None, None]; + for (k, id) in [primary, secondary].into_iter().enumerate() { + if let Some(id) = id { + let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else { + return; + }; + powers[k] = Some((id, name.to_owned())); + } + } + let data = self.beacon_data(host, pos); + let mut updated = false; + self.lan_station_op(host, conn, None, |menu, env| { + menu.data.copy_from_slice(&data); + let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str())); + updated = menu.beacon_update(env, power(0), power(1)); + }); + if !updated { + return; + } + let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n)); + let mut select_sound = false; + if let Some(BlockEntity::Beacon(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.primary = primary; + b.secondary = secondary; + select_sound = !b.sections.is_empty(); + } + if select_sound { + self.beacon_sound(pos, "minecraft:block.beacon.power_select"); + } + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + } + /// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its /// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`). pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) { @@ -375,6 +459,15 @@ impl Game<'_> { conn, &C::ContainerClose(play::ContainerClose { container: window }), ); + } else if gs.kind == StationKind::Beacon { + // The beacon's data slots follow its block entity. + let data = self.beacon_data(host, gs.pos); + if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) + && gs.menu.data[..] != data[..] + { + gs.menu.data.copy_from_slice(&data); + self.lan_send_station(host, conn); + } } } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ed900ebf9..a8ebffdf8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -446,8 +446,15 @@ impl Game<'_> { .unwrap_or("minecraft:air"), ) } + /// The server's network id of a mob effect (`brewing::EFFECTS` id). + pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option { + let r = self.remote.as_ref()?; + r.builtin + .get("minecraft:mob_effect")? + .id(&format!("minecraft:{effect}")) + } /// A mob effect's network id as the effect (`brewing::EFFECTS` id). - fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { + pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { let r = self.remote.as_ref()?; let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?; horizon_client::brewing::effect(name).map(|d| d.id) @@ -1269,6 +1276,7 @@ impl Game<'_> { "minecraft:anvil" => Kind::Anvil, "minecraft:smithing" => Kind::Smithing, "minecraft:enchantment" => Kind::Enchanting, + "minecraft:beacon" => Kind::Beacon, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index 52e60ed76..c6b61a76f 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -97,6 +97,17 @@ impl Game<'_> { *level = value.max(0) as u32; } } + // BeaconMenu: the levels, then the powers (BeaconScreen's + // dataChanged shows the menu's). + (Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)), + (Kind::Beacon, 1 | 2) => { + let effect = self.remote_effect_id(i32::from(value) - 1); + let index = + effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e)); + if let Some(s) = self.station.as_mut() { + s.beacon[id - 1] = index; + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 7820bd88b..d0d1e10bb 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -152,6 +152,8 @@ pub(super) struct Station { pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// A server's beacon menu: the pyramid's levels (its data slot 0). + pub(super) beacon_levels: Option, /// The loom's patterns, selection and scroller (game/loom.rs). pub(super) loom: super::loom::LoomState, } @@ -175,6 +177,7 @@ impl Station { last_sound: 0, merchant: None, beacon: [None; 2], + beacon_levels: None, loom: Default::default(), } } @@ -531,7 +534,6 @@ impl Game<'_> { } let i = slot - INPUT; match s.kind { - 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), Kind::Cartography => ( @@ -667,7 +669,6 @@ impl Game<'_> { return false; }; let start = stack.count; - let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none(); // The other half of the inventory: main rows to the hotbar and back. let halves: Vec = if slot < 9 { (9..36).collect() @@ -675,20 +676,10 @@ impl Game<'_> { (0..9).collect() }; if slot >= INPUT { - // An input slot: into the inventory, the hotbar's last slot first - // where vanilla moves in reverse. - let reverse = kind == Kind::Beacon; - self.move_to(&mut stack, &Self::player_slots(), reverse); + // An input slot: into the inventory. + self.move_to(&mut stack, &Self::player_slots(), false); } else { match kind { - Kind::Beacon => { - if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1 - { - self.move_to(&mut stack, &[INPUT], 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); @@ -708,7 +699,8 @@ impl Game<'_> { | Kind::Grindstone | Kind::Anvil | Kind::Smithing - | Kind::Enchanting => {} + | Kind::Enchanting + | Kind::Beacon => {} } } let moved = stack.count != start; @@ -1062,10 +1054,11 @@ impl Game<'_> { | Kind::Anvil | Kind::Smithing | Kind::Enchanting + | Kind::Beacon ) }) { // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu, AnvilMenu, - // SmithingMenu and the brewing stand's + // SmithingMenu, EnchantmentMenu, BeaconMenu 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/hub.rs b/crates/horizon-client/src/lan/hub.rs index 9c65e9292..2ff89809a 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -311,6 +311,11 @@ impl Hub { self.sync.id(registry, name) } + /// The name of a network id in a built-in registry. + pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> { + self.sync.builtin.get(registry)?.name(id) + } + pub fn item_id(&mut self, item: &Arc) -> i32 { if let Some(id) = self.item_ids.get(item) { return *id; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index c4354b184..b72b74762 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -89,6 +89,9 @@ pub enum Kind { /// `EnchantmentMenu`: the item, the lapis, then the inventory; its data /// slots are the three costs, the seed and the clues. Enchanting, + /// `BeaconMenu`: the payment slot, then the inventory; its data slots are + /// the pyramid's levels and the two powers (`encodeEffect`: id + 1). + Beacon, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -119,6 +122,7 @@ impl Kind { "anvil" => Self::Anvil, "smithing" => Self::Smithing, "enchanting" => Self::Enchanting, + "beacon" => Self::Beacon, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -170,6 +174,8 @@ enum Role { EnchantItem, /// The enchanting table's lapis slot. Lapis, + /// `BeaconMenu.PaymentSlot`: one beacon payment item. + BeaconPay, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -182,6 +188,26 @@ struct Slot { role: Role, } +/// `BeaconBlockEntity.BEACON_EFFECTS`: the powers of each pyramid level. +pub const BEACON_EFFECTS: [&[&str]; 4] = [ + &["minecraft:speed", "minecraft:haste"], + &["minecraft:resistance", "minecraft:jump_boost"], + &["minecraft:strength"], + &["minecraft:regeneration"], +]; + +/// `BeaconBlockEntity.getRequiredLevelsFor`: 0 for no power, `i32::MAX` +/// for one no level gives. +pub fn beacon_required_levels(effect: Option<&str>) -> i32 { + let Some(effect) = effect else { + return 0; + }; + BEACON_EFFECTS + .iter() + .position(|tier| tier.contains(&effect)) + .map_or(i32::MAX, |i| i as i32 + 1) +} + /// The containers a menu spans. const PLAYER: usize = 0; const MAIN: usize = 1; @@ -466,6 +492,13 @@ impl Menu { // costs[3], enchantmentSeed, enchantClue[3], levelClue[3]. data = 10; } + Kind::Beacon => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::BeaconPay)); + player(&mut slots); + // levels, primary, secondary. + data = 3; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -827,6 +860,38 @@ impl Menu { /// `AnvilMenu.setItemName` (`ServerboundRenameItemPacket`): false when /// the name is refused or unchanged. + /// `BeaconMenu.updateEffects` (`ServerboundSetBeaconPacket`): with a + /// payment, powers `BeaconBlockEntity.validateEffects` allows for the + /// pyramid's levels (data 0) become data 1 and 2 and the payment is used. + /// Each power is its `mob_effect` id and name. False when refused. + pub fn beacon_update( + &mut self, + env: &Env, + primary: Option<(i32, &str)>, + secondary: Option<(i32, &str)>, + ) -> bool { + if self.kind != Kind::Beacon || self.containers[MAIN][0].is_none() { + return false; + } + let levels = self.data[0]; + let (p, s) = ( + beacon_required_levels(primary.map(|e| e.1)), + beacon_required_levels(secondary.map(|e| e.1)), + ); + let valid = !(secondary.is_some() && levels < 4) + && p <= levels + && s <= levels + && p < 4 + && !(s != 0 && s < 4 && primary.map(|e| e.0) != secondary.map(|e| e.0)); + if !valid { + return false; + } + self.data[1] = primary.map_or(0, |e| e.0 + 1); + self.data[2] = secondary.map_or(0, |e| e.0 + 1); + self.remove(env, 0, 1); + true + } + pub fn rename(&mut self, env: &Env, name: &str) -> bool { // StringUtil.filterText, then validateName's length limit. let name: String = name @@ -973,6 +1038,11 @@ impl Menu { Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), Role::EnchantItem => true, Role::Lapis => &*stack.item == "minecraft:lapis_lazuli", + Role::BeaconPay => env + .items + .item_tags + .get("minecraft:beacon_payment_items") + .is_some_and(|t| t.contains(&*stack.item)), Role::LoomResult | Role::MerchantResult | Role::StoneResult @@ -1017,7 +1087,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 | Role::EnchantItem => 1, + Role::Armor(_) | Role::Potion | Role::EnchantItem | Role::BeaconPay => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -1034,6 +1104,10 @@ impl Menu { && let Some(st) = stack.as_mut() { st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st))); + // The beacon's container holds one item (getMaxStackSize 1). + if self.kind == Kind::Beacon { + st.count = st.count.min(1); + } } // CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it. if self.kind == Kind::CrafterBlock @@ -1712,6 +1786,32 @@ impl Menu { return None; } } + Kind::Beacon => { + // BeaconMenu.quickMoveStack. + after_take = true; + if index == 0 { + if !self.move_to(env, &mut stack, 1, 37, true) { + return None; + } + } else if self.containers[MAIN][0].is_none() + && self.may_place(env, 0, &stack) + && stack.count == 1 + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (1..28).contains(&index) { + if !self.move_to(env, &mut stack, 28, 37, false) { + return None; + } + } else if (28..37).contains(&index) { + if !self.move_to(env, &mut stack, 1, 28, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 1, 37, false) { + return None; + } + } Kind::Enchanting => { after_take = true; if index < 2 { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 11166408a..36bca7bbc 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1719,6 +1719,11 @@ packet!( /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. RenameItem { name: String => Str } ); +packet!( + /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an + /// optional `mob_effect` id. + SetBeacon { primary: Option => Opt, secondary: Option => Opt } +); packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); packet!( /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. @@ -1805,6 +1810,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, SelectTrade(SelectTrade) = SELECT_TRADE, + SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, UseItem(UseItem) = USE_ITEM, @@ -2384,6 +2390,13 @@ mod tests { }); assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']); round_trip(rename, Serverbound::encode, Serverbound::decode); + // Two optional mob effect ids: a presence byte, then the VarInt. + let beacon = Serverbound::SetBeacon(SetBeacon { + primary: Some(2), + secondary: None, + }); + assert_eq!(&beacon.encode()[1..], &[1, 2, 0]); + round_trip(beacon, Serverbound::encode, Serverbound::decode); } #[test] 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 5a3db5977..1491c5a28 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -183,10 +183,19 @@ public final class VanillaMenuOracle { case "anvil" -> new AnvilMenu(0, inv); case "smithing" -> new SmithingMenu(0, inv); case "enchanting" -> new EnchantmentMenu(0, inv); + case "beacon" -> new BeaconMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } + /** A SET_BEACON power: a mob effect's name, or null for none. */ + static Optional> effect(JsonElement name) { + if (name.isJsonNull()) return Optional.empty(); + return net.minecraft.core.registries.BuiltInRegistries.MOB_EFFECT + .get(net.minecraft.resources.Identifier.parse(name.getAsString())) + .map(h -> (net.minecraft.core.Holder) h); + } + static String state(AbstractContainerMenu menu, Inventory inv) throws Exception { StringBuilder out = new StringBuilder(); for (int i = 0; i < menu.slots.size(); i++) { @@ -267,6 +276,12 @@ public final class VanillaMenuOracle { out.println(clickState(menu, inv)); continue; } + if (kind.equals("SET_BEACON")) { + // ServerGamePacketListenerImpl.handleSetBeaconPacket: BeaconMenu.updateEffects + if (menu instanceof BeaconMenu beacon) beacon.updateEffects(effect(op.get(3)), effect(op.get(4))); + out.println(clickState(menu, inv)); + continue; + } if (kind.equals("SLOT_STATE")) { // handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 958b80b4d..a7168fb2c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -147,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', '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'] +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', 'beacon', '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: @@ -1141,6 +1141,47 @@ def check_enchanting(host, guest, out): return seen +def check_beacon(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='effect clear @s') + guest('command', command='give @s minecraft:iron_ingot') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + # A one-level pyramid under the beacon; its levels come with the first base check (80 ticks). + guest('command', command=f'fill {x - 1} {y - 1} {z + 1} {x + 1} {y - 1} {z + 3} minecraft:iron_block') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:beacon') + guest.wait(100) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'station', '--timeout', 10) + guest.wait(10) + # BeaconMenu.quickMoveStack: the ingot to the payment slot. + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:iron_ingot'), 'shift') + guest.wait(10) + paid = station_slots(guest).get(600) + # BeaconScreen (54 px wider, 27 to the left): Haste, the first level's second power, then Done, + # which sends ServerboundSetBeaconPacket and closes the menu. + guest.raw('click-gui', 77 - 27 + 11, 22 + 11) + guest.wait(5) + guest.shot(out, 'beacon') + guest.raw('click-gui', 164 - 27 + 11, 107 + 11) + guest.wait(10) + screen = guest('state').get('screen') + effects = [] + # BeaconBlockEntity.applyEffects runs every 80 ticks. + for _ in range(12): + guest.wait(20) + effects = effect_ids(guest) + if 'haste' in effects: + break + seen = {'paid': paid, 'haste': 'haste' in effects, 'ingots': server_count(guest, 'iron_ingot'), + 'screen': screen} + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + want = {'paid': ('minecraft:iron_ingot', 1), 'haste': True, 'ingots': 0, 'screen': 'playing'} + assert seen == want, f'the beacon on the guest: {seen} ({effects})' + 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']: @@ -2338,6 +2379,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'anvil': check_anvil, 'smithing': check_smithing, 'enchanting': check_enchanting, + 'beacon': check_beacon, '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 41561fbb9..ce97183b4 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -14,7 +14,9 @@ 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), the smithing table (upgrades and trims), the -enchanting table (its button checks against the costs, lapis and levels) and the +enchanting table (its button checks against the costs, lapis and levels), the +beacon (its payment slot and ServerboundSetBeaconPacket against the pyramid's +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. @@ -30,9 +32,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, 'enchanting': 38, '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, 'beacon': 37, '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, 'enchanting': 10, + 'stonecutter': 1, 'enchanting': 10, 'beacon': 3, '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'] @@ -50,6 +52,9 @@ CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sand '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'] +# Beacon powers (BEACON_EFFECTS by level, and one no level gives) and payments. +POWERS = ['speed', 'haste', 'resistance', 'jump_boost', 'strength', 'regeneration', 'night_vision'] +PAYMENTS = ['iron_ingot', 'gold_ingot', 'emerald', 'diamond', 'netherite_ingot'] ENCHANTS = ['sharpness', 'unbreaking', 'mending', 'efficiency', 'protection', 'power', 'looting', 'fortune', 'binding_curse', 'vanishing_curse'] @@ -228,6 +233,15 @@ class Gen: # An offer button (clickMenuButton), sometimes out of range. out.append([rng.choice([0, 1, 2, 2, 3, -1]), 0, 'BUTTON']) continue + if menu == 'beacon' and rng.random() < 0.3: + # ServerboundSetBeaconPacket: powers, valid or not, or none. + pick = lambda: 'minecraft:' + rng.choice(POWERS) if rng.random() < 0.8 else None + primary, secondary = pick(), pick() + if primary is None and secondary not in (None, 'minecraft:regeneration', 'minecraft:night_vision'): + # validateEffects compares a null primary (Holder.equals: a NullPointerException). + primary = secondary + out.append([0, 0, 'SET_BEACON', primary, secondary]) + 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 @@ -329,6 +343,11 @@ def main(): 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 == 'beacon': + pay = lambda: snbt('minecraft:' + rng.choice(PAYMENTS), rng.choice([1, 1, 1, 2, 64])) + for i in rng.sample(range(1, size), 8): + slots[i] = pay() + slots[0] = pay() if rng.random() < 0.7 else rng.choice(['-', g.stack()]) if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -356,6 +375,9 @@ 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 == 'beacon': + # the levels, then the powers (encodeEffect: id + 1) + return rng.choice([0, 1, 2, 3, 4, 4]) if i == 0 else rng.choice([0, 0, 2, 4, 11]) 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 \