From e4741b7793211787741f520d9667cebfd9aaeca8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:34:24 +0200 Subject: [PATCH] Decode the server's command tree and complete commands with it The window dropped ClientboundCommandsPacket ("argument nodes are not decoded"), so on a server, single player's server thread included, the chat was a bare input line without completion, colouring or usage. - horizon-protocol decodes argument nodes: the 26.3 `command_argument_type` ids and every parser's properties (ArgumentTypeInfo.deserializeFromNetwork), plus the custom suggestion provider. - command::network turns the tree into a Dispatcher. A node at a path the client's vanilla tree also has takes that node's argument type and suggestion provider; any other node takes the type its parser and properties describe. - On a server the chat is ChatScreen over that tree, so Tab completes, arguments are coloured, usage and errors show, and Enter sends the command to the server. Player-name suggestions come from the server's player list. The old bare input line is gone. - The screen state reports the chat input (`chat_input`). lan_e2e.py gains a `commands` check: the guest completes `/gamem` to `/gamemode` and `/gamemode cr` to `/gamemode creative` with Tab, and the command runs. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/command/mod.rs | 1 + crates/horizon-client/src/command/network.rs | 404 +++++++++++++++++++ crates/horizon-client/src/game.rs | 9 +- crates/horizon-client/src/game/agent.rs | 3 + crates/horizon-client/src/game/chat.rs | 33 +- crates/horizon-client/src/game/control.rs | 12 - crates/horizon-client/src/game/debug_keys.rs | 3 +- crates/horizon-client/src/game/pad.rs | 7 - crates/horizon-client/src/game/pad_menu.rs | 18 +- crates/horizon-client/src/game/remote.rs | 131 ++---- crates/horizon-client/src/game/scoreboard.rs | 2 - crates/horizon-protocol/src/buf.rs | 4 + crates/horizon-protocol/src/packets/play.rs | 182 ++++++++- tools/lan_e2e.py | 47 ++- 14 files changed, 696 insertions(+), 160 deletions(-) create mode 100644 crates/horizon-client/src/command/network.rs diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 52e76100a..8fcb30830 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -8,6 +8,7 @@ pub mod block; pub mod codec; pub mod component; pub mod item; +pub mod network; pub mod packrat; pub mod selector; pub mod snbt; diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-client/src/command/network.rs new file mode 100644 index 000000000..32f446f5c --- /dev/null +++ b/crates/horizon-client/src/command/network.rs @@ -0,0 +1,404 @@ +//! The command tree a server sends (ClientboundCommandsPacket) as a +//! dispatcher the chat parses, colours and completes with +//! (ClientPacketListener.handleCommands). +//! +//! The packet holds each argument's parser and its network properties. A +//! node the client's own vanilla tree has at the same path takes that node's +//! argument type and suggestion provider (the parsers' suggestion lists and +//! the custom providers are the same code on both sides); any other node +//! (another server's or a mod's) gets the type its parser and properties +//! describe. +use super::{ArgType, Dispatcher, Node, NodeKind, Suggests}; +use horizon_protocol::packets::play::{ARGUMENT_TYPES, ArgumentProperties, Commands}; +use std::{ + collections::{HashSet, VecDeque}, + sync::{Mutex, OnceLock}, +}; + +/// The command id of every executable node of a server's tree: the chat +/// sends the command, the server runs it. +pub const SERVER_COMMAND: &str = "server"; + +/// The dispatcher for a server's tree. `local` is the client's own tree +/// (vanilla's), whose matching nodes lend their types and providers. +pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher { + let count = packet.nodes.len(); + let root = usize::try_from(packet.root) + .ok() + .filter(|&r| r < count) + .unwrap_or(0); + // The packet's root becomes node 0, the others follow in packet order. + let index = |i: usize| -> usize { + if i == root { + 0 + } else if i < root { + i + 1 + } else { + i + } + }; + let valid = |c: &i32| usize::try_from(*c).ok().filter(|&c| c < count); + // The local node at the same path, found breadth first from the roots + // along children (redirects are not paths of their own). + let mut matched: Vec> = vec![None; count]; + matched[root] = Some(0); + let mut queue = VecDeque::from([root]); + let mut seen = HashSet::from([root]); + while let Some(n) = queue.pop_front() { + for c in packet.nodes[n].children.iter().filter_map(valid) { + if !seen.insert(c) { + continue; + } + let node = &packet.nodes[c]; + matched[c] = matched[n].and_then(|l| { + local.nodes[l].children.iter().copied().find(|&lc| { + let ln = &local.nodes[lc]; + ln.name() == node.name + && matches!( + (&ln.kind, node.kind), + (NodeKind::Literal(_), 1) | (NodeKind::Argument { .. }, 2) + ) + }) + }); + queue.push_back(c); + } + } + let mut nodes = vec![None; count]; + for (i, node) in packet.nodes.iter().enumerate() { + let local_node = matched[i].map(|l| &local.nodes[l]); + let kind = match node.kind { + 1 => NodeKind::Literal(node.name.clone()), + 2 => { + let ty = match local_node.map(|l| &l.kind) { + Some(NodeKind::Argument { ty, .. }) => ty.clone(), + _ => node + .parser + .as_ref() + .map_or(ArgType::Word, |(id, props)| argument_type(*id, props)), + }; + NodeKind::Argument { + name: node.name.clone(), + ty, + } + } + _ => NodeKind::Root, + }; + let suggests = match local_node { + Some(l) => l.suggests.clone(), + None => node.suggestions.as_deref().and_then(provider), + }; + nodes[index(i)] = Some(Node { + kind: if i == root { NodeKind::Root } else { kind }, + children: node.children.iter().filter_map(valid).map(index).collect(), + command: node.executable.then_some(SERVER_COMMAND), + redirect: node.redirect.as_ref().and_then(valid).map(index), + // The server sent only what the player may use. + permission: 0, + suggests, + }); + } + let mut d = Dispatcher::new(); + if count > 0 { + d.nodes = nodes.into_iter().flatten().collect(); + } + d +} + +/// SuggestionProviders by id (`ask_server` asks the server; the client's +/// own argument suggestions stand in for it). +fn provider(id: &str) -> Option { + match id { + "minecraft:summonable_entities" => Some(Suggests::SummonableEntities), + _ => None, + } +} + +/// A registry name kept for the life of the game (argument types hold +/// `&'static str`): each distinct name is stored once. +fn intern(name: &str) -> &'static str { + static NAMES: OnceLock>> = OnceLock::new(); + let mut names = NAMES + .get_or_init(Default::default) + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some(&n) = names.get(name) { + return n; + } + let n: &'static str = Box::leak(name.to_owned().into_boxed_str()); + names.insert(n); + n +} + +/// The argument type a parser and its properties describe +/// (ArgumentTypeInfo.Template.instantiate). +pub fn argument_type(id: i32, props: &[u8]) -> ArgType { + let Some(name) = usize::try_from(id).ok().and_then(|i| ARGUMENT_TYPES.get(i)) else { + return ArgType::Word; + }; + let p = ArgumentProperties::decode(id, props).unwrap_or(ArgumentProperties::None); + let registry = || match &p { + ArgumentProperties::Registry(r) => intern(r), + _ => "", + }; + match *name { + "brigadier:bool" => ArgType::Bool, + "brigadier:integer" => match p { + ArgumentProperties::Integer { min, max } => ArgType::Integer { + min: min.unwrap_or(i32::MIN), + max: max.unwrap_or(i32::MAX), + }, + _ => ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }, + }, + // No long type of its own: a double over the same bounds reads + // the same digits. + "brigadier:long" => match p { + ArgumentProperties::Long { min, max } => ArgType::Double { + min: min.map_or(f64::MIN, |v| v as f64), + max: max.map_or(f64::MAX, |v| v as f64), + }, + _ => ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + }, + "brigadier:float" => match p { + ArgumentProperties::Float { min, max } => ArgType::Float { + min: min.unwrap_or(f32::MIN), + max: max.unwrap_or(f32::MAX), + }, + _ => ArgType::Float { + min: f32::MIN, + max: f32::MAX, + }, + }, + "brigadier:double" => match p { + ArgumentProperties::Double { min, max } => ArgType::Double { + min: min.unwrap_or(f64::MIN), + max: max.unwrap_or(f64::MAX), + }, + _ => ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + }, + "brigadier:string" => match p { + ArgumentProperties::String(1) => ArgType::Str, + ArgumentProperties::String(2) => ArgType::Greedy, + _ => ArgType::Word, + }, + "minecraft:entity" => match p { + ArgumentProperties::Entity { + single, + players_only, + } => ArgType::Entity { + single, + players: players_only, + }, + _ => ArgType::Entity { + single: false, + players: false, + }, + }, + "minecraft:game_profile" => ArgType::GameProfile, + "minecraft:block_pos" => ArgType::BlockPos, + "minecraft:column_pos" => ArgType::ColumnPos, + "minecraft:vec3" => ArgType::Vec3 { center: true }, + "minecraft:vec2" => ArgType::Vec2, + "minecraft:block_state" => ArgType::BlockState, + "minecraft:block_predicate" => ArgType::BlockPredicate, + "minecraft:item_stack" => ArgType::Item, + "minecraft:item_predicate" => ArgType::ItemPredicate, + "minecraft:team_color" => ArgType::TeamColor, + "minecraft:hex_color" => ArgType::HexColor, + "minecraft:component" => ArgType::Component, + "minecraft:style" => ArgType::Style, + "minecraft:message" => ArgType::Message, + "minecraft:nbt_compound_tag" => ArgType::Nbt, + "minecraft:nbt_tag" => ArgType::NbtTag, + "minecraft:nbt_path" => ArgType::NbtPath, + "minecraft:objective" => ArgType::Objective, + "minecraft:objective_criteria" => ArgType::Criteria, + "minecraft:operation" => ArgType::Operation, + "minecraft:particle" => ArgType::Particle, + "minecraft:angle" => ArgType::Angle, + "minecraft:rotation" => ArgType::Rotation, + "minecraft:scoreboard_slot" => ArgType::ScoreboardSlot, + "minecraft:score_holder" => ArgType::ScoreHolder { + multiple: matches!(p, ArgumentProperties::ScoreHolder { multiple: true }), + }, + "minecraft:swizzle" => ArgType::Swizzle, + "minecraft:team" => ArgType::Team, + "minecraft:item_slot" => ArgType::Slot, + "minecraft:item_slots" => ArgType::Slots, + "minecraft:resource_location" => ArgType::Id("none"), + "minecraft:function" => ArgType::Function, + "minecraft:entity_anchor" => ArgType::Anchor, + "minecraft:int_range" => ArgType::IntRange, + "minecraft:float_range" => ArgType::FloatRange, + "minecraft:dimension" => ArgType::Dimension, + "minecraft:gamemode" => ArgType::GameMode, + "minecraft:time" => ArgType::Time { + min: match p { + ArgumentProperties::Time { min } => min, + _ => 0, + }, + }, + "minecraft:resource_or_tag" => ArgType::ResOrTag(registry()), + "minecraft:resource_or_tag_key" => ArgType::ResOrTagKey(registry()), + "minecraft:resource" => ArgType::Res(registry()), + "minecraft:resource_key" => ArgType::ResKey(registry()), + "minecraft:resource_selector" => ArgType::ResourceSelector(registry()), + "minecraft:template_mirror" => ArgType::Enum(&["none", "front_back", "left_right"]), + "minecraft:template_rotation" => { + ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"]) + } + "minecraft:heightmap" => ArgType::Enum(&[ + "world_surface", + "motion_blocking", + "motion_blocking_no_leaves", + "ocean_floor", + ]), + "minecraft:swing_animation" => ArgType::Enum(&["none", "whack", "stab"]), + "minecraft:loot_table" => ArgType::ResourceOrId("minecraft:loot_table"), + "minecraft:loot_predicate" => ArgType::ResourceOrId("minecraft:predicate"), + "minecraft:loot_modifier" => ArgType::ResourceOrId("minecraft:item_modifier"), + "minecraft:context_float_provider" => { + ArgType::ResourceOrId("minecraft:context_float_provider") + } + "minecraft:context_int_provider" => ArgType::ResourceOrId("minecraft:context_int_provider"), + "minecraft:slot_source" => ArgType::SlotSource, + "minecraft:dialog" => ArgType::ResourceOrId("minecraft:dialog"), + "minecraft:feature" => ArgType::ResourceOrId("minecraft:worldgen/feature"), + "minecraft:uuid" => ArgType::Uuid, + _ => ArgType::Word, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::play::CommandNode, + }; + + fn literal(name: &str, children: Vec, executable: bool) -> CommandNode { + CommandNode { + kind: 1, + executable, + restricted: false, + children, + redirect: None, + name: name.into(), + parser: None, + suggestions: None, + } + } + + fn argument(name: &str, parser: &str, props: Vec, executable: bool) -> CommandNode { + let id = ARGUMENT_TYPES.iter().position(|p| *p == parser).unwrap() as i32; + CommandNode { + kind: 2, + executable, + restricted: false, + children: Vec::new(), + redirect: None, + name: name.into(), + parser: Some((id, props)), + suggestions: Some("minecraft:ask_server".into()), + } + } + + /// A tree with the root last (as vanilla's numbering need not put it + /// first), a vanilla command and one the client does not know. + fn packet() -> Commands { + let mut range = Writer::new(); + range.u8(3); + range.i32(1); + range.i32(64); + Commands { + nodes: vec![ + literal("give", vec![2], false), + literal("warp", vec![3], false), + argument("targets", "minecraft:entity", vec![2], false), + argument("count", "brigadier:integer", range.data, true), + CommandNode { + kind: 0, + executable: false, + restricted: false, + children: vec![0, 1], + redirect: None, + name: String::new(), + parser: None, + suggestions: None, + }, + ], + root: 4, + } + } + + #[test] + fn argument_nodes_round_trip() { + let p = packet(); + let mut w = Writer::new(); + Commands::write(&p, &mut w); + let back = Commands::read(&mut Reader::new(&w.data)).unwrap(); + assert_eq!(back, p); + } + + #[test] + fn server_tree_becomes_a_dispatcher() { + let local = super::super::vanilla::dispatcher(); + let d = from_packet(&packet(), local); + assert!(matches!(d.nodes[0].kind, NodeKind::Root)); + let warp = d.find("warp").expect("warp"); + let count = d.nodes[warp].children[0]; + match &d.nodes[count].kind { + NodeKind::Argument { + ty: ArgType::Integer { min, max }, + .. + } => assert_eq!((*min, *max), (1, 64)), + other => panic!("count is {other:?}"), + } + assert_eq!(d.nodes[count].command, Some(SERVER_COMMAND)); + // `give ` is vanilla's: it keeps the client's type. + let give = d.find("give").expect("give"); + let targets = d.nodes[give].children[0]; + assert!(matches!( + d.nodes[targets].kind, + NodeKind::Argument { + ty: ArgType::Entity { + single: false, + players: true + }, + .. + } + )); + } + + #[test] + fn every_argument_type_decodes() { + for (id, name) in ARGUMENT_TYPES.iter().enumerate() { + let mut w = Writer::new(); + match *name { + "brigadier:integer" | "brigadier:long" | "brigadier:float" | "brigadier:double" => { + w.u8(0) + } + "brigadier:string" => w.varint(2), + "minecraft:entity" | "minecraft:score_holder" => w.u8(1), + "minecraft:time" => w.i32(0), + n if n.starts_with("minecraft:resource") && n != "minecraft:resource_location" => { + w.string("minecraft:item") + } + _ => {} + } + let mut r = Reader::new(&w.data); + ArgumentProperties::read(&mut r, id as i32).unwrap(); + assert_eq!(r.remaining(), 0, "{name}"); + let _ = argument_type(id as i32, &w.data); + } + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 150ee7aa9..29c9b26de 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3702,10 +3702,7 @@ impl Game<'_> { /// LevelLoadingScreen.onClose -> Gui.setScreen(null) -> grabMouse. fn capture_loaded_world(&mut self) { // Loading may finish after focus was lost or another screen opened. - if self.title.is_none() - && self.screen == Screen::Playing - && !self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) - { + if self.title.is_none() && self.screen == Screen::Playing { self.capture(true); } } @@ -9645,9 +9642,6 @@ impl ApplicationHandler for Game<'_> { self.station_text(event.text.as_deref(), backspace); } } - WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => { - self.remote_chat_key(&event) - } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::WorldOptions && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => @@ -9754,7 +9748,6 @@ impl ApplicationHandler for Game<'_> { && self.title.is_none() && self.sign_edit.is_none() && self.book.is_none() - && !self.remote_chat_open() { let turn = |k| f32::from(u8::from(self.keys.contains(&k))); let secs = elapsed.as_secs_f32().min(0.1); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 48b24bbb3..1d0160e4c 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -613,6 +613,9 @@ impl Game<'_> { "screen": self.screen_label(), "buttons": buttons, }); + if let Some(chat) = &self.ui.chat_screen { + v["chat_input"] = json!(chat.input.value); + } if self.title.is_some() { v["menu"] = self.title_value(); } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index bcf6426e1..b19cd9d01 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -10,6 +10,18 @@ use horizon_client::{ text::{ClickEvent, Style, Text}, }; use std::collections::BTreeMap; + +/// The tree the chat parses and completes with: a server's, once it has +/// sent one (ClientPacketListener.commands), else the game's own. +fn chat_tree<'a>( + remote: &'a Option, + mods: &'a super::mods::ModsState, +) -> &'a horizon_client::command::Dispatcher { + match remote.as_ref().and_then(|r| r.commands.as_ref()) { + Some(tree) => tree, + None => mods.dispatcher(), + } +} use winit::{ event::KeyEvent, keyboard::{KeyCode, PhysicalKey}, @@ -378,6 +390,10 @@ impl Game<'_> { /// The block the player is looking at, for coordinate suggestions. fn refresh_dynamic_registries(&mut self) { self.ui.registries.target_block = self.pick().map(|h| h.pos); + // ClientPacketListener.getOnlinePlayerNames on a server. + if let Some(names) = self.remote_online_names() { + self.ui.registries.players = names; + } } pub(super) fn open_chat(&mut self, initial: &str) { if self.player.is_none() { @@ -391,7 +407,7 @@ impl Game<'_> { let b = HudBatch::new(size); let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; let mut screen = ChatScreen::new( @@ -449,7 +465,7 @@ impl Game<'_> { if let Some(shortcut) = self.edit_shortcut(event) { let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -495,7 +511,7 @@ impl Game<'_> { }; let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) { @@ -521,7 +537,7 @@ impl Game<'_> { pub(super) fn chat_type(&mut self, text: &str) { let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -531,6 +547,11 @@ impl Game<'_> { /// ChatScreen.handleChatInput: history, then a command or a chat line. pub(super) fn handle_chat_input(&mut self, message: &str) { self.ui.chat.add_recent(message); + // On a server (single player's own included) the server runs it. + if self.remote.is_some() { + self.send_chat(message); + return; + } if let Some(command) = message.strip_prefix('/') { self.run_command(command); } else { @@ -572,7 +593,7 @@ impl Game<'_> { }); let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -617,7 +638,7 @@ impl Game<'_> { }; let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; screen.resize(&m, &c, batch.width as i32, batch.height as i32); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index cf7510065..94592e69c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -606,18 +606,6 @@ impl Game<'_> { fn control_key_down(&mut self, key: KeyCode) -> Result<()> { self.physical_keys.insert(key); - // A server's chat input takes the keys first, as remote_chat_key does. - if self.remote_chat_open() { - use winit::keyboard::NamedKey; - let named = match key { - KeyCode::Escape => Some(NamedKey::Escape), - KeyCode::Enter | KeyCode::NumpadEnter => Some(NamedKey::Enter), - KeyCode::Backspace => Some(NamedKey::Backspace), - _ => None, - }; - self.remote_chat_input(named, None); - return Ok(()); - } if self.screen == Screen::Chat { self.chat_key_code(key, None); return Ok(()); diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 36761a85e..1de6669e7 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -88,8 +88,7 @@ impl Game<'_> { || self.book.is_some() || (self.screen == Screen::Creative && self.creative_screen.tab().search) || self.recipe_search_focused() - || self.station_typing() - || self.remote_chat_open(); + || self.station_typing(); // Container screens use Escape, the inventory key and the hotbar and // drop keys first; any other screen closes on Escape. let screen_key = match self.screen { diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index 62d481b11..0c988c3b7 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -365,13 +365,6 @@ impl Game<'_> { self.close_book(); return Ok(()); } - if let Some(remote) = self.remote.as_mut() - && remote.chat_input.is_some() - { - remote.chat_input = None; - self.capture(true); - return Ok(()); - } self.key_pressed(KeyCode::Escape) } diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index 8f34d2b3a..5c623202b 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -31,7 +31,7 @@ use winit::{ dpi::PhysicalPosition, event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent}, event_loop::ActiveEventLoop, - keyboard::{KeyCode, NamedKey}, + keyboard::KeyCode, }; /// D-pad auto-repeat: the first step at once, the next after a pause. @@ -859,7 +859,6 @@ impl Game<'_> { || (self.screen == Screen::Creative && self.creative_screen.tab().search) || self.recipe_search_focused() || self.station_typing() - || self.remote_chat_open() } /// Open the on-screen keyboard over the focused field: Horizon's, or @@ -890,7 +889,7 @@ impl Game<'_> { && self.pad.in_use && menu.open_polls >= 3 && self.pad_focus_mode() - && (self.screen == Screen::Chat || self.sign_edit.is_some() || self.remote_chat_open()) + && (self.screen == Screen::Chat || self.sign_edit.is_some()) { self.pad.menu.osk_dismissed = true; self.pad_open_keyboard(); @@ -901,10 +900,10 @@ impl Game<'_> { /// the field that has focus. fn pad_osk_output(&mut self, out: osk::Output) { use osk::Output; - let (key, named, text) = match &out { - Output::Text(t) => (None, None, Some(t.as_str())), - Output::Backspace => (Some(KeyCode::Backspace), Some(NamedKey::Backspace), None), - Output::Enter => (Some(KeyCode::Enter), Some(NamedKey::Enter), None), + let (key, text) = match &out { + Output::Text(t) => (None, Some(t.as_str())), + Output::Backspace => (Some(KeyCode::Backspace), None), + Output::Enter => (Some(KeyCode::Enter), None), Output::Close => { self.pad.menu.osk = None; self.pad.menu.osk_dismissed = true; @@ -933,8 +932,6 @@ impl Game<'_> { if key != Some(KeyCode::Enter) { self.station_text(text, backspace); } - } else if self.remote_chat_open() { - self.remote_chat_input(named, text); } else if self.screen == Screen::WorldOptions { if key != Some(KeyCode::Enter) { self.world_options_text(text); @@ -985,8 +982,7 @@ impl Game<'_> { .menu .focus .is_some_and(|f| f.center().1 > batch.height / 2.0) - || self.screen == Screen::Chat - || self.remote_chat_open(); + || self.screen == Screen::Chat; let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); keyboard.draw(&mut ui, at_top, self.ui.options.pad_style); ui.finish(); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..4ad96970d 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -107,7 +107,8 @@ pub(super) struct Remote { health: (f32, i32, f32), game_mode: i32, pub chat: Vec<(String, Instant)>, - pub chat_input: Option, + /// The server's command tree (ClientboundCommandsPacket). + pub commands: Option, action_bar: Option<(String, Instant)>, players: HashMap, /// `ClientPacketListener.playerInfoMap` as player-list entries, and @@ -292,7 +293,7 @@ impl Game<'_> { health: (20.0, 20, 5.0), game_mode: 0, chat: Vec::new(), - chat_input: None, + commands: None, action_bar: None, players: HashMap::new(), tab_players: HashMap::new(), @@ -470,6 +471,13 @@ impl Game<'_> { } } + /// The names in the server's player list, sorted. + pub(super) fn remote_online_names(&self) -> Option> { + let r = self.remote.as_ref()?; + let mut names: Vec = r.players.values().cloned().collect(); + names.sort(); + Some(names) + } /// The server's last `n` chat lines, newest first. pub(super) fn remote_chat(&self, n: usize) -> Option> { let r = self.remote.as_ref()?; @@ -1525,6 +1533,15 @@ impl Game<'_> { self.capture(true); } } + C::Commands(p) => { + let tree = horizon_client::command::network::from_packet( + &p, + horizon_client::command::vanilla::dispatcher(), + ); + if let Some(r) = self.remote.as_mut() { + r.commands = Some(tree); + } + } C::SystemChat(p) => { let text = plain( &p.content, @@ -2147,8 +2164,7 @@ impl Game<'_> { let Some(player) = self.player.as_mut() else { return Ok(()); }; - let chatting = self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()); - let playing = self.screen == Screen::Playing && !chatting; + let playing = self.screen == Screen::Playing; let held = |k| playing && self.keys.contains(&k); let keys = Keys { forward: held(KeyCode::KeyW), @@ -2418,8 +2434,7 @@ impl Game<'_> { if r.destroy_delay > 0 { r.destroy_delay -= 1; } - let chatting = r.chat_input.is_some(); - if !self.left || self.screen != Screen::Playing || chatting { + if !self.left || self.screen != Screen::Playing { self.stop_remote_mining(); self.mining = None; return; @@ -2648,7 +2663,7 @@ impl Game<'_> { } /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { - if self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) { + if self.screen == Screen::Chat { return Ok(()); } match button { @@ -2707,14 +2722,8 @@ impl Game<'_> { } match key { KeyCode::KeyT | KeyCode::Slash | KeyCode::Enter => { - let text = if key == KeyCode::Slash { "/" } else { "" }; - if let Some(r) = self.remote.as_mut() { - r.chat_input = Some(text.to_owned()); - } - self.keys.clear(); - self.left = false; - self.right = false; - self.capture(false); + // ChatScreen, over the server's command tree. + self.open_chat(if key == KeyCode::Slash { "/" } else { "" }); Ok(true) } KeyCode::KeyQ => { @@ -2751,84 +2760,6 @@ impl Game<'_> { _ => Ok(false), } } - pub(super) fn remote_chat_open(&self) -> bool { - self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) - } - /// ChatScreen: typing, Enter to send, Escape to cancel. - pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) { - use winit::keyboard::Key; - if event.state != winit::event::ElementState::Pressed { - return; - } - let shortcut = self.edit_shortcut(event); - let Some(r) = self.remote.as_mut() else { - return; - }; - let Some(input) = r.chat_input.as_mut() else { - return; - }; - // ChatScreen's input: an EditBox of 256. - const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0); - if let Some(shortcut) = shortcut { - Self::append_shortcut( - &mut self.text_selection, - &mut self.clipboard, - INPUT, - input, - shortcut, - 256, - ); - return; - } - // Logical keys: the text, not the scancode, decides (layouts, virtual keyboards). - let named = match &event.logical_key { - Key::Named(n) => Some(*n), - _ => None, - }; - self.remote_chat_input(named, event.text.as_deref()); - } - /// A named key or typed text in the chat input (the keyboard, or a - /// controller's on-screen keyboard). - pub(super) fn remote_chat_input( - &mut self, - named: Option, - text: Option<&str>, - ) { - use winit::keyboard::NamedKey; - const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0); - let Some(r) = self.remote.as_mut() else { - return; - }; - let Some(input) = r.chat_input.as_mut() else { - return; - }; - match named { - Some(NamedKey::Escape) => { - r.chat_input = None; - self.capture(true); - } - Some(NamedKey::Backspace) => { - if !self.text_selection.take(INPUT, input) { - input.pop(); - } - } - Some(NamedKey::Enter) => { - let message = r.chat_input.take().unwrap_or_default(); - self.send_chat(&message); - self.capture(true); - } - _ => { - if let Some(text) = text { - self.text_selection.take(INPUT, input); - for c in text.chars().filter(|c| !c.is_control()) { - if input.chars().count() < 256 { - input.push(c); - } - } - } - } - } - } /// ClientPacketListener.sendChat / sendCommand (unsigned). pub(super) fn send_chat(&mut self, message: &str) { let message = message.trim(); @@ -3171,11 +3102,11 @@ impl Game<'_> { let Some(r) = &self.remote else { return }; let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); - let open = r.chat_input.is_some(); + let open = self.screen == Screen::Chat; let now = Instant::now(); let mut y = h - 48.0; // Container screens cover the chat (vanilla draws them over the HUD). - let shown = if matches!(self.screen, Screen::Playing | Screen::Dead) { + let shown = if matches!(self.screen, Screen::Playing | Screen::Dead | Screen::Chat) { if open { 20 } else { 10 } } else { 0 @@ -3203,16 +3134,6 @@ impl Game<'_> { batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true); y -= 9.0; } - if let Some(input) = &r.chat_input { - batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, 128)); - let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2); - let shown = if blink { - format!("{input}_") - } else { - input.clone() - }; - batch.text(atlas, &shown, 4.0, h - 12.0, rgba(224, 224, 224, 255), true); - } if let Some((text, at)) = &r.action_bar && now.duration_since(*at) < Duration::from_secs(3) { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 60894a14e..2e7e1df07 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -600,9 +600,7 @@ impl Game<'_> { /// objective. pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) { use horizon_client::tab_list::{self, TabInputs}; - let chatting = self.remote.is_some() && self.remote_chat_open(); let key = self.screen == super::Screen::Playing - && !chatting && self.keys.contains(&winit::keyboard::KeyCode::Tab); let (players, online_mode, upside_down) = match self.remote_tab_players() { Some(remote) => remote, diff --git a/crates/horizon-protocol/src/buf.rs b/crates/horizon-protocol/src/buf.rs index d937ff8b9..e761aec3f 100644 --- a/crates/horizon-protocol/src/buf.rs +++ b/crates/horizon-protocol/src/buf.rs @@ -23,6 +23,10 @@ impl<'a> Reader<'a> { pub fn position(&self) -> usize { self.pos } + /// The bytes read since `start` (a `position()`). + pub fn since(&self, start: usize) -> &'a [u8] { + &self.data[start.min(self.pos)..self.pos] + } pub fn rest(&mut self) -> &'a [u8] { let rest = &self.data[self.pos..]; self.pos = self.data.len(); diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index f14f8f817..20b6dfa14 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -901,6 +901,177 @@ pub struct CommandNode { /// Custom suggestion provider (`minecraft:ask_server`). pub suggestions: Option, } +/// The `minecraft:command_argument_type` registry of 26.3 in id order +/// (ArgumentTypeInfos.bootstrap). +pub const ARGUMENT_TYPES: &[&str] = &[ + "brigadier:bool", + "brigadier:float", + "brigadier:double", + "brigadier:integer", + "brigadier:long", + "brigadier:string", + "minecraft:entity", + "minecraft:game_profile", + "minecraft:block_pos", + "minecraft:column_pos", + "minecraft:vec3", + "minecraft:vec2", + "minecraft:block_state", + "minecraft:block_predicate", + "minecraft:item_stack", + "minecraft:item_predicate", + "minecraft:team_color", + "minecraft:hex_color", + "minecraft:component", + "minecraft:style", + "minecraft:message", + "minecraft:nbt_compound_tag", + "minecraft:nbt_tag", + "minecraft:nbt_path", + "minecraft:objective", + "minecraft:objective_criteria", + "minecraft:operation", + "minecraft:particle", + "minecraft:angle", + "minecraft:rotation", + "minecraft:scoreboard_slot", + "minecraft:score_holder", + "minecraft:swizzle", + "minecraft:team", + "minecraft:item_slot", + "minecraft:item_slots", + "minecraft:resource_location", + "minecraft:function", + "minecraft:entity_anchor", + "minecraft:int_range", + "minecraft:float_range", + "minecraft:dimension", + "minecraft:gamemode", + "minecraft:time", + "minecraft:resource_or_tag", + "minecraft:resource_or_tag_key", + "minecraft:resource", + "minecraft:resource_key", + "minecraft:resource_selector", + "minecraft:template_mirror", + "minecraft:template_rotation", + "minecraft:heightmap", + "minecraft:loot_table", + "minecraft:loot_predicate", + "minecraft:loot_modifier", + "minecraft:context_float_provider", + "minecraft:context_int_provider", + "minecraft:slot_source", + "minecraft:dialog", + "minecraft:feature", + "minecraft:swing_animation", + "minecraft:uuid", +]; + +/// The properties of an argument parser (`ArgumentTypeInfo.Template`) as +/// one of the 26.3 parsers decoded from the network. +#[derive(Clone, Debug, PartialEq)] +pub enum ArgumentProperties { + None, + Integer { + min: Option, + max: Option, + }, + Long { + min: Option, + max: Option, + }, + Float { + min: Option, + max: Option, + }, + Double { + min: Option, + max: Option, + }, + /// StringArgumentType.StringType: 0 word, 1 phrase, 2 greedy. + String(i32), + Entity { + single: bool, + players_only: bool, + }, + ScoreHolder { + multiple: bool, + }, + Time { + min: i32, + }, + /// The resource arguments' registry. + Registry(String), +} + +impl ArgumentProperties { + /// ArgumentTypeInfo.deserializeFromNetwork for parser `id`. + pub fn read(r: &mut Reader, id: i32) -> Result { + let name = usize::try_from(id) + .ok() + .and_then(|i| ARGUMENT_TYPES.get(i)) + .ok_or_else(|| crate::Error::new(format!("unknown argument type {id}")))?; + let flagged = |r: &mut Reader| -> Result<(bool, bool)> { + let f = r.u8()?; + Ok((f & 1 != 0, f & 2 != 0)) + }; + Ok(match *name { + "brigadier:integer" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.i32()?) } else { None }; + let max = if max { Some(r.i32()?) } else { None }; + Self::Integer { min, max } + } + "brigadier:long" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.i64()?) } else { None }; + let max = if max { Some(r.i64()?) } else { None }; + Self::Long { min, max } + } + "brigadier:float" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.f32()?) } else { None }; + let max = if max { Some(r.f32()?) } else { None }; + Self::Float { min, max } + } + "brigadier:double" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.f64()?) } else { None }; + let max = if max { Some(r.f64()?) } else { None }; + Self::Double { min, max } + } + "brigadier:string" => Self::String(r.varint()?), + "minecraft:entity" => { + let f = r.u8()?; + Self::Entity { + single: f & 1 != 0, + players_only: f & 2 != 0, + } + } + "minecraft:score_holder" => Self::ScoreHolder { + multiple: r.u8()? & 1 != 0, + }, + "minecraft:time" => Self::Time { min: r.i32()? }, + "minecraft:resource" + | "minecraft:resource_key" + | "minecraft:resource_or_tag" + | "minecraft:resource_or_tag_key" + | "minecraft:resource_selector" => Self::Registry(r.string(32767)?), + _ => Self::None, + }) + } + /// Decodes a node's raw `parser` bytes. + pub fn decode(id: i32, bytes: &[u8]) -> Result { + Self::read(&mut Reader::new(bytes), id) + } +} + +/// Reads past an argument node's parser properties. +fn read_argument_properties(r: &mut Reader, id: i32) -> Result<()> { + ArgumentProperties::read(r, id).map(|_| ()) +} + /// The command tree: nodes and the index of the root. #[derive(Clone, Debug, PartialEq)] pub struct Commands { @@ -926,11 +1097,14 @@ impl Codec for Commands { name = r.string(32767)?; } if kind == 2 { - // Properties are parser specific; only the property-less parsers - // can be skipped without a table, so keep the rest of the packet. - return Err(crate::Error::new("argument nodes are not decoded")); + let id = r.varint()?; + let start = r.position(); + read_argument_properties(r, id)?; + parser = Some((id, r.since(start).to_vec())); + if flags & 16 != 0 { + suggestions = Some(r.string(32767)?); + } } - let _ = (&mut parser, &mut suggestions); nodes.push(CommandNode { kind, executable: flags & 4 != 0, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..0329ae6ef 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -19,7 +19,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing; - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; -- feedback: the guest's command feedback names the guest and shows the numbers. +- feedback: the guest's command feedback names the guest and shows the numbers; +- commands: the guest's chat completes commands and their arguments over the server's command + tree (Tab), and runs what it completed. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -48,7 +50,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'trials'] class Game: @@ -475,6 +477,44 @@ def check_feedback(host, guest, out): return chat +def chat_input(game): + return game('screen').get('chat_input') + + +def complete(guest, text): + """Opens the chat on `/`, types `text` and presses Tab: the input after it.""" + guest.raw('key', 'slash', 'tap') + guest.wait(3) + guest.raw('type', text) + guest.wait(2) + guest.raw('key', 'tab', 'tap') + guest.wait(2) + return chat_input(guest) + + +def check_commands(host, guest, out): + literal = complete(guest, 'gamem') + # The first Escape hides the suggestions, the next closes the chat. + for _ in range(3): + if guest('screen').get('screen') != 'chat': + break + guest.raw('key', 'esc', 'tap') + guest.wait(3) + argument = complete(guest, 'gamemode cr') + guest.shot(out, 'commands') + guest.raw('key', 'enter', 'tap') + guest.wait(20) + mode = guest('state').get('gamemode') + screen = guest('state').get('screen') + guest('command', command='gamemode survival') + guest.wait(10) + assert literal == '/gamemode', f'Tab after /gamem: {literal!r}' + assert argument == '/gamemode creative', f'Tab after /gamemode cr: {argument!r}' + assert mode == 'creative', f'the completed command did not run: {mode}' + assert screen in (None, 'playing'), f'the chat did not close: {screen}' + return {'literal': literal, 'argument': argument, 'mode': mode} + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -625,7 +665,8 @@ def check_trials(host, guest, out): CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, - 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, + 'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands, + 'trials': check_trials, 'walls': check_walls}