From 0410a222ea95c686855e8179683d1ba31c3838ad Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:24:03 +0200 Subject: [PATCH 01/18] WIP: unfinished hud parity work, stopped for the night Uncommitted changes the agent had in progress when it was stopped; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/bossbar.rs | 4 +- crates/horizon-client/src/command/args.rs | 64 +- crates/horizon-client/src/fastutil_order.rs | 148 ++++ crates/horizon-client/src/game.rs | 16 +- crates/horizon-client/src/game/chat.rs | 11 +- .../src/game/command_harness.rs | 123 +++ crates/horizon-client/src/game/commands.rs | 77 +- .../src/game/commands/execute.rs | 6 + .../horizon-client/src/game/commands/extra.rs | 834 ++++++++++++++++++ crates/horizon-client/src/game/game_mode.rs | 5 + crates/horizon-client/src/game/lan.rs | 14 +- crates/horizon-client/src/game/lan_actions.rs | 7 +- crates/horizon-client/src/game/lan_screen.rs | 2 +- crates/horizon-client/src/lang.rs | 32 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/scoreboard.rs | 35 +- crates/horizon-client/src/scoreboard_cmd.rs | 5 +- crates/horizon-client/src/worldborder.rs | 4 +- .../parity/VanillaCommandExecOracle.java | 367 ++++++++ tools/command_exec_corpus.py | 339 +++++++ tools/prepare_native_client.py | 18 + tools/test_command_exec_parity.py | 158 ++++ 22 files changed, 2237 insertions(+), 33 deletions(-) create mode 100644 crates/horizon-client/src/fastutil_order.rs create mode 100644 crates/horizon-client/src/game/command_harness.rs create mode 100644 crates/horizon-client/src/game/commands/extra.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java create mode 100644 tools/command_exec_corpus.py create mode 100644 tools/test_command_exec_parity.py diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index 9df17431c..a976258f9 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -57,7 +57,9 @@ impl BossBar { hover: Some(Box::new(Text::literal(self.id.clone()))), ..Style::default() }; - bracketed(comp_text(&self.name).with_style(&style)) + // ComponentUtils.wrapInSquareBrackets(name).withStyle(...): the + // brackets take the colour too. + bracketed(comp_text(&self.name)).with_style(&style) } /// The filled fraction of the bar (`BossEvent.getProgress`). pub fn progress(&self) -> f32 { diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 1f24bfbf6..32208fa20 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -83,6 +83,67 @@ pub struct RegistryIds { } const EMPTY: &[String] = &[]; impl Registries { + /// Fill what the game did not build itself from vanilla's exported + /// registries (`command-registries.json`, written by + /// `VanillaCommandParseOracle registries`): built-in registries such as + /// mob effects, data component types and dialogs, block entities and tag + /// members. Registries that data packs reload stay with the game. + pub fn fill_from_export(&mut self, r: &serde_json::Value) { + fn strings(v: &serde_json::Value) -> Vec { + v.as_array() + .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()) + .unwrap_or_default() + } + let fill = |field: &mut Vec, key: &str| { + if field.is_empty() { + *field = strings(&r[key]); + } + }; + fill(&mut self.effects, "effects"); + fill(&mut self.enchantments, "enchantments"); + fill(&mut self.attributes, "attributes"); + fill(&mut self.damage_types, "damage_types"); + fill(&mut self.templates, "templates"); + fill(&mut self.persistent_components, "persistent_components"); + fill(&mut self.learnable_recipes, "learnable_recipes"); + const RELOADED: [&str; 5] = [ + "minecraft:advancement", + "minecraft:recipe", + "minecraft:loot_table", + "minecraft:predicate", + "minecraft:item_modifier", + ]; + for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { + if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { + continue; + } + self.by_registry.insert( + name.clone(), + RegistryIds { + ids: strings(&entry["ids"]), + tags: strings(&entry["tags"]), + }, + ); + } + if self.block_entities.is_empty() { + self.block_entities = strings(&r["block_entities"]).into_iter().collect(); + } + if self.block_tag_members.is_empty() { + for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { + self.block_tag_members.insert(tag.clone(), strings(members)); + } + } + if self.clock_time_markers.is_empty() { + for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { + self.clock_time_markers.insert(clock.clone(), strings(markers)); + } + } + if self.advancement_criteria.is_empty() { + for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { + self.advancement_criteria.insert(id.clone(), strings(criteria)); + } + } + } /// The element ids of a registry (sorted). pub fn ids(&self, registry: &str) -> &[String] { if let Some(r) = self.by_registry.get(registry) { @@ -1539,7 +1600,8 @@ impl ArgType { if block { parse_coord_int(reader) } else { - parse_coord_double(reader, false) + // Vec2Argument.vec2(): integers are centred on the block. + parse_coord_double(reader, true) } }; let x = one(reader)?; diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client/src/fastutil_order.rs new file mode 100644 index 000000000..d833d44dd --- /dev/null +++ b/crates/horizon-client/src/fastutil_order.rs @@ -0,0 +1,148 @@ +//! Iteration order of fastutil's `Object2ObjectOpenHashMap` (open +//! addressing with linear probing, backward-shift deletion and rehashing at +//! the load factor), for the vanilla collections whose order commands show: +//! the scoreboard's objectives and teams. + +/// The keys of an open hash map in their table slots. +#[derive(Clone, Debug, PartialEq)] +pub struct OpenOrder { + keys: Vec>, + size: usize, + min_n: usize, + load: f32, +} +impl Default for OpenOrder { + /// `new Object2ObjectOpenHashMap<>()`: 16 expected entries, load 0.75. + fn default() -> Self { + Self::new(16, 0.75) + } +} +/// `String.hashCode`. +fn java_hash(s: &str) -> i32 { + s.encode_utf16() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))) +} +/// `HashCommon.mix`. +fn mix(x: i32) -> usize { + let h = (x as u32).wrapping_mul(0x9E37_79B9); + (h ^ (h >> 16)) as usize +} +/// `HashCommon.arraySize`. +fn array_size(expected: usize, f: f32) -> usize { + let wanted = (expected as f64 / f64::from(f)).ceil() as usize; + wanted.max(2).next_power_of_two() +} +impl OpenOrder { + pub fn new(expected: usize, load: f32) -> Self { + let n = array_size(expected, load); + Self { + keys: vec![None; n], + size: 0, + min_n: n, + load, + } + } + fn max_fill(&self) -> usize { + ((self.keys.len() as f64 * f64::from(self.load)).ceil() as usize).min(self.keys.len() - 1) + } + fn slot(&self, key: &str) -> usize { + mix(java_hash(key)) & (self.keys.len() - 1) + } + pub fn insert(&mut self, key: &str) { + let mask = self.keys.len() - 1; + let mut pos = self.slot(key); + while let Some(k) = &self.keys[pos] { + if k == key { + return; + } + pos = (pos + 1) & mask; + } + self.keys[pos] = Some(key.to_owned()); + self.size += 1; + if self.size >= self.max_fill() { + self.rehash(array_size(self.size + 1, self.load)); + } + } + pub fn remove(&mut self, key: &str) { + let mask = self.keys.len() - 1; + let mut pos = self.slot(key); + loop { + match &self.keys[pos] { + None => return, + Some(k) if k == key => break, + Some(_) => pos = (pos + 1) & mask, + } + } + self.size -= 1; + self.shift_keys(pos); + let n = self.keys.len(); + if n > self.min_n && self.size < self.max_fill() / 4 && n > 16 { + self.rehash(n / 2); + } + } + fn shift_keys(&mut self, mut pos: usize) { + let mask = self.keys.len() - 1; + loop { + let last = pos; + pos = (last + 1) & mask; + loop { + let Some(curr) = self.keys[pos].clone() else { + self.keys[last] = None; + return; + }; + let slot = self.slot(&curr); + let stop = if last <= pos { + last >= slot || slot > pos + } else { + last >= slot && slot > pos + }; + if stop { + self.keys[last] = Some(curr); + break; + } + pos = (pos + 1) & mask; + } + } + } + fn rehash(&mut self, new_n: usize) { + let old = std::mem::replace(&mut self.keys, vec![None; new_n]); + let mask = new_n - 1; + for key in old.into_iter().rev().flatten() { + let mut pos = mix(java_hash(&key)) & mask; + while self.keys[pos].is_some() { + pos = (pos + 1) & mask; + } + self.keys[pos] = Some(key); + } + } + /// The iteration order (`keySet().iterator()`: from the last slot down). + pub fn keys(&self) -> impl Iterator { + self.keys.iter().rev().flatten().map(String::as_str) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hash_and_order() { + assert_eq!(java_hash("harness"), "harness".chars().fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))); + let mut o = OpenOrder::new(16, 0.5); + for k in ["harness", "harness_h"] { + o.insert(k); + } + let keys: Vec<&str> = o.keys().collect(); + assert_eq!(keys.len(), 2); + o.remove("harness"); + assert_eq!(o.keys().collect::>(), vec!["harness_h"]); + for i in 0..40 { + o.insert(&format!("k{i}")); + } + assert_eq!(o.keys().count(), 41); + for i in 0..40 { + o.remove(&format!("k{i}")); + } + assert_eq!(o.keys().collect::>(), vec!["harness_h"]); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..7ff2ae3ef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -14,6 +14,7 @@ mod breezes; mod cartography; mod chat; mod combat; +mod command_harness; mod commands; mod control; mod creaking; @@ -733,7 +734,9 @@ struct Game<'a> { lan_events: Vec<(i32, [i32; 3], i32, Option)>, lan_acting: Option, /// Command feedback to forward to a guest. - chat_capture: Option>, + chat_capture: Option>, + /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. + cmds: commands::extra::CommandExtras, /// Allow Cheats: whether guests may be given commands. cheats: bool, ui: chat::UiState, @@ -2470,6 +2473,8 @@ impl Game<'_> { } self.apply_totem(); self.update_totem_ready(); + self.tick_command_extras(); + let camera_eye = self.camera_eye_height(); if self.riding.is_some() && self.player.is_some() { let playing = self.screen == Screen::Playing; let held = |k| playing && self.keys.contains(&k); @@ -2560,7 +2565,7 @@ impl Game<'_> { } let feet = [player.position.x, player.position.y, player.position.z]; self.previous_eye = self.eye; - self.eye += (player.dimensions.eye_height - self.eye) * 0.5; + self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.record_combat(&events); for event in events { @@ -8611,6 +8616,7 @@ pub fn run() -> Result<()> { lan_events: Vec::new(), lan_acting: None, chat_capture: None, + cmds: Default::default(), cheats: true, ui: Default::default(), combat: Default::default(), @@ -8655,6 +8661,12 @@ pub fn run() -> Result<()> { } None => game.title = Some(Title::new(std::env::current_dir()?.join("saves"))), } + if let (Some(script), Some(output)) = ( + std::env::var_os("HORIZON_COMMAND_SCRIPT"), + std::env::var_os("HORIZON_COMMAND_OUTPUT"), + ) { + return game.run_command_harness(script.as_ref(), output.as_ref()); + } EventLoop::new()?.run_app(&mut game)?; if let Some(path) = &game.options.report { let report = serde_json::json!({ diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 812ac6118..816c8831f 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -324,6 +324,15 @@ impl Game<'_> { ); } } + // Vanilla's built-in registries (mob effects, components, dialogs...). + for dir in [&self.options.resources, &self.ui.vanilla_root] { + if let Ok(bytes) = std::fs::read(dir.join("command-registries.json")) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + self.ui.registries.fill_from_export(&v); + break; + } + } let reg = &mut self.ui.registries; reg.timelines = self.ui.timelines.keys().cloned().collect(); reg.time_markers = self @@ -368,7 +377,7 @@ impl Game<'_> { /// A chat message from the game (ChatComponent.addServerSystemMessage). pub(super) fn system_message(&mut self, text: Text) { if let Some(capture) = self.chat_capture.as_mut() { - capture.push(text.plain()); + capture.push(text); return; } let focused = self.screen == Screen::Chat; diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs new file mode 100644 index 000000000..ce18149f4 --- /dev/null +++ b/crates/horizon-client/src/game/command_harness.rs @@ -0,0 +1,123 @@ +//! Headless command runner for `tools/test_command_exec_parity.py`: with +//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world +//! runs without a window. Each script line is a JSON operation: `cmd` runs a +//! command as the player (Commands.performPrefixedCommand) and records every +//! system message it produced, as styled spans, with the results reported to +//! the player's `CommandResultCallback`; `tick` advances the game; `settle` +//! waits until the terrain around the player is loaded. +use super::Game; +use horizon_client::{Result, text::Text}; +use serde_json::{Value, json}; +use std::{ + path::Path, + time::{Duration, Instant}, +}; + +/// A message as `[text, style]` runs with adjacent equal styles merged; the +/// style lists colour, bold, italic, underlined, strikethrough, obfuscated +/// and the suggested command. +pub(super) fn spans(text: &Text) -> Value { + let mut out: Vec<(String, Value)> = Vec::new(); + for span in &text.spans { + if span.text.is_empty() { + continue; + } + let s = &span.style; + let style = json!([ + s.color, + s.bold == Some(true), + s.italic == Some(true), + s.underlined == Some(true), + s.strikethrough == Some(true), + s.obfuscated == Some(true), + ]); + match out.last_mut() { + Some((t, last)) if *last == style => t.push_str(&span.text), + _ => out.push((span.text.clone(), style)), + } + } + Value::Array(out.into_iter().map(|(t, s)| json!([t, s])).collect()) +} + +impl Game<'_> { + /// Load terrain until the player stands in lit chunks. + fn harness_settle(&mut self, deadline: Instant) -> Result<()> { + loop { + self.update_world(); + self.spawn_player()?; + if let Some(p) = &self.player { + let (cx, cz) = ( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + ); + if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return Ok(()); + } + } + if std::env::var_os("HORIZON_HARNESS_DEBUG").is_some() && self.ticks % 1 == 0 { + eprintln!( + "settle: player {:?} center {:?} chunks {} pending {}", + self.player.as_ref().map(|p| p.position), + self.streaming.center, + self.world.chunks.len(), + self.streaming.pending() + ); + } + if Instant::now() > deadline { + return Err("command harness: terrain did not load".into()); + } + std::thread::sleep(Duration::from_millis(2)); + } + } + pub(super) fn run_command_harness(&mut self, script: &Path, output: &Path) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(std::env::var("HORIZON_HARNESS_TIMEOUT").ok().and_then(|v| v.parse().ok()).unwrap_or(600)); + self.harness_settle(deadline)?; + let mut out = String::new(); + for line in std::fs::read_to_string(script)?.lines() { + if line.trim().is_empty() { + continue; + } + let op: Value = serde_json::from_str(line)?; + match op["op"].as_str().unwrap_or("") { + "cmd" => { + let command = op["cmd"].as_str().unwrap_or(""); + self.chat_capture = Some(Vec::new()); + self.cmds.results = Some(Vec::new()); + self.run_command(command.strip_prefix('/').unwrap_or(command)); + let messages = self.chat_capture.take().unwrap_or_default(); + let results = self.cmds.results.take().unwrap_or_default(); + if op["record"].as_bool() != Some(false) { + let record = json!({ + "cmd": command, + "messages": messages.iter().map(spans).collect::>(), + "results": results.iter().map(|(s, v)| json!([s, v])).collect::>(), + }); + out.push_str(&record.to_string()); + out.push('\n'); + } + } + "tick" => { + self.chat_capture = Some(Vec::new()); + for _ in 0..op["n"].as_u64().unwrap_or(1) { + self.update_world(); + self.tick()?; + } + let messages = self.chat_capture.take().unwrap_or_default(); + if op["record"].as_bool() == Some(true) { + let record = json!({ + "cmd": "#tick", + "messages": messages.iter().map(spans).collect::>(), + "results": [], + }); + out.push_str(&record.to_string()); + out.push('\n'); + } + } + "settle" => self.harness_settle(deadline)?, + other => return Err(format!("command harness: unknown op {other}").into()), + } + } + std::fs::write(output, out)?; + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 9dfed52ea..0d91e0984 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -3,6 +3,7 @@ mod data; mod effects; pub(super) mod execute; +pub(super) mod extra; mod items; mod misc; mod place; @@ -283,7 +284,11 @@ impl Game<'_> { /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { - Target::Player => Text::literal(PLAYER_NAME), + Target::Player => match self.score.board.players_team(PLAYER_NAME) { + // PlayerTeam.formatNameForTeam. + Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)), + None => Text::literal(PLAYER_NAME), + }, Target::Item(id) => { let item = self .dropped @@ -537,6 +542,17 @@ impl Game<'_> { "clear" => self.cmd_clear(ctx), "item" => self.cmd_item(ctx), "item.modify" => self.cmd_item_modify(ctx), + "spectate" => self.cmd_spectate(ctx), + id if id.starts_with("waypoint.") => self.cmd_waypoint(id, ctx), + id if id.starts_with("dialog.") => self.cmd_dialog(id, ctx), + id if id.starts_with("posteffect.") => self.cmd_posteffect(id, ctx), + "kick" => self.cmd_kick(ctx), + "fetchprofile" => self.cmd_fetchprofile(ctx), + "publish" => self.cmd_publish(ctx), + "unpublish" => self.cmd_unpublish(), + "debug" => self.cmd_debug(ctx), + "jfr" => self.cmd_jfr(ctx), + "version" => self.cmd_version(), "place" => self.cmd_place(ctx), "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), @@ -583,7 +599,7 @@ impl Game<'_> { "commands.list.nameAndId", &[ Text::literal(PLAYER_NAME), - Text::literal("00000000-0000-0000-0000-000000000000"), + Text::literal(self.player_uuid_string()), ], ) } else { @@ -655,16 +671,23 @@ impl Game<'_> { } count += 1; let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); - if ctx.get("target").is_none() { + // GameModeCommand.logGamemodeChange: the source's own entity. + let own = match self.command_source { + None => true, + Some(s) => s.entity == Some(t), + }; + if own { self.feedback(Text::translate( "commands.gamemode.success.self", &[mode_name], )); } else { - self.system_message(Text::translate( - "gameMode.changed", - std::slice::from_ref(&mode_name), - )); + if self.ui.rules.bool("send_command_feedback") { + self.system_message(Text::translate( + "gameMode.changed", + std::slice::from_ref(&mode_name), + )); + } self.feedback(Text::translate( "commands.gamemode.success.other", &[Text::literal(PLAYER_NAME), mode_name], @@ -687,6 +710,15 @@ impl Game<'_> { .append("]") .with_color(color) } + /// ItemStack.getDisplayName of a renamed stack: the name in italics. + pub(super) fn item_display_name_custom(&self, item: &str, custom: &str) -> Text { + let color = self.item_display_name(item).spans.first().and_then(|s| s.style.color); + let mut t = Text::translate("chat.square_brackets", &[Text::literal(custom).italic()]); + if let Some(c) = color { + t = t.with_color(c); + } + t + } fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -757,7 +789,10 @@ impl Game<'_> { } } } - let name = self.item_display_name(&id); + let name = match extra.as_ref().and_then(|e| e.custom_name.clone()) { + Some(custom) => self.item_display_name_custom(&id, &custom), + None => self.item_display_name(&id), + }; let message = if targets.len() == 1 { Text::translate( "commands.give.success.single", @@ -1119,7 +1154,7 @@ impl Game<'_> { w.raining = raining; w.thundering = thundering; self.feedback(Text::translate(key, &[])); - Ok(duration.unwrap_or(0)) + Ok(duration.unwrap_or(-1)) } fn kill_target(&mut self, t: Target) { match t { @@ -1499,21 +1534,29 @@ impl Game<'_> { dest[2] + z - min[2], ], s, + self.world.block_entities.get(&(x, y, z)).cloned(), )); } } } if moving { - for (from, _, _) in &copies { + for (from, _, _, _) in &copies { self.place_state(*from, air, true)?; } } let strict = ctx.has("strict"); + // CloneCommands.clone sets every destination to a barrier first, so + // each copied state but a barrier counts as placed. + let barrier = self.res.assets.registry.default_state("minecraft:barrier"); let mut count = 0; - for (_, to, s) in copies { - if self.place_state(to, s, strict)? { + for (_, to, s, entity) in copies { + self.place_state(to, s, strict)?; + if Some(s) != barrier { count += 1; } + if let Some(e) = entity { + self.world.block_entities.insert((to[0], to[1], to[2]), e); + } } if count == 0 { return Err(err("commands.clone.failed", &[])); @@ -1760,7 +1803,7 @@ impl Game<'_> { if self.ui.difficulty == i { return Err(CommandError::new(Text::translate( "commands.difficulty.failure", - &[Text::literal(DIFFICULTIES[i as usize])], + &[name(i)], ))); } self.ui.difficulty = i; @@ -1810,7 +1853,7 @@ impl Game<'_> { dim, ]; let key = if targets.len() == 1 { - args.push(Text::literal(PLAYER_NAME)); + args.push(self.target_name(targets[0])); "commands.spawnpoint.success.single" } else { args.push(Text::literal(targets.len().to_string())); @@ -1830,9 +1873,6 @@ impl Game<'_> { p[2].floor() as i32, ] }; - if self.dim != Dim::Overworld { - return Err(err("commands.setworldspawn.failure.not_overworld", &[])); - } let rot = match ctx.get("rotation") { Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), _ => [0.0, 0.0], @@ -2128,6 +2168,9 @@ impl Game<'_> { .italic() } }; + if let Some(capture) = self.chat_capture.as_mut() { + capture.push(line.clone()); + } let focused = self.screen == Screen::Chat; self.ui .chat diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 2fda44bfe..fd715fd5d 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -189,6 +189,12 @@ impl Game<'_> { } /// `CommandResultCallback`s of a source's `store` chain, oldest first. fn deliver(&mut self, store: Option, success: bool, value: i32) { + // The outermost source's own CommandResultCallback (harness record). + if self.exec.function_depth == 0 + && let Some(results) = self.cmds.results.as_mut() + { + results.push((success, value)); + } let mut chain = Vec::new(); let mut at = store; while let Some(i) = at { diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs new file mode 100644 index 000000000..6184cb7f6 --- /dev/null +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -0,0 +1,834 @@ +//! Commands that act on the player and the hosted game rather than the world: +//! `/spectate` (SpectateCommand), `/waypoint` (WaypointCommand), `/dialog` +//! (DialogCommand), `/posteffect` (PostEffectCommand), `/kick`, +//! `/fetchprofile`, `/publish`, `/unpublish`, `/debug`, `/jfr` and +//! `/version`, with vanilla's feedback and failures. +use super::{Arg, Context, Game, R, Target, err}; +use horizon_client::{ + command::CommandError, + text::{self, Style, Text}, +}; +use std::{collections::HashMap, time::Instant}; + +/// Waypoint.Icon: the locator bar style and colour of a transmitter. +#[derive(Clone, Debug, PartialEq)] +pub(in crate::game) struct WaypointIcon { + pub style: String, + pub color: Option, +} +impl Default for WaypointIcon { + fn default() -> Self { + Self { + style: "minecraft:default".into(), + color: None, + } + } +} + +/// Server-side player and server state these commands keep. +#[derive(Default)] +pub(in crate::game) struct CommandExtras { + /// ServerPlayer.camera: the entity `/spectate` attached the view to. + pub camera: Option, + /// ServerPlayer.postEffects, in insertion order. + pub post_effects: Vec, + /// MinecraftServer's tick profiler (`/debug start`): when it started and + /// the tick count then. + pub profiler: Option<(Instant, u64)>, + /// `debugCommandProfilerDelayStart`: the profiler starts with the next tick. + pub profiler_delay: bool, + /// Messages the server sends on a later tick (profile lookups). + pub pending: Vec, + /// The `/jfr start` recording: when it started and the tick count then. + pub jfr: Option<(Instant, u64, String)>, + /// Waypoint icons changed by `/waypoint modify`. + pub waypoint_icons: HashMap, + /// The dialog `/dialog show` opened (its id or inline definition). + pub dialog: Option, + /// The `CommandResultCallback` results of the outermost source, when a + /// harness records them. + pub results: Option>, +} + +/// `version.json` of the 26.3 jars. +const VERSION_ID: &str = "26.3"; +const DATA_VERSION: i32 = 5023; +const STABLE: bool = true; +/// `Date.toString()` of the build time in UTC. +const BUILD_TIME: &str = "Tue Sep 15 11:20:48 UTC 2026"; + +fn num(n: impl std::fmt::Display) -> Text { + Text::literal(n.to_string()) +} +fn tr_error(key: &str, args: &[Text]) -> CommandError { + CommandError::new(Text::translate(key, args)) +} +/// `String.format(Locale.ROOT, "%.2f", v)`. +fn two_places(v: f64) -> String { + format!("{v:.2}") +} +/// `Util.getFilenameFormattedDateTime` (`yyyy-MM-dd_HH.mm.ss`, local time). +fn filename_date_time() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64); + let (y, mo, d, h, mi, s) = civil(secs); + format!("{y:04}-{mo:02}-{d:02}_{h:02}.{mi:02}.{s:02}") +} +/// UTC civil date and time of a Unix timestamp. +fn civil(secs: i64) -> (i64, i64, i64, i64, i64, i64) { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + (y, m, d, rem / 3600, rem % 3600 / 60, rem % 60) +} + +impl Game<'_> { + /// CommandSourceStack.getPlayerOrException. + fn source_player(&self) -> R { + match self.command_source.map(|s| s.entity) { + None | Some(Some(Target::Player)) => Ok(Target::Player), + _ => Err(err("permissions.requires.player", &[])), + } + } + /// EntityArgument.getEntity / getPlayer. + fn one_entity(&mut self, ctx: &Context, name: &str, player: bool) -> R { + Ok(self.entities(ctx, name, player)?[0]) + } + + // ---- /spectate ------------------------------------------------------ + + /// `SpectateCommand.spectate`. + pub(super) fn cmd_spectate(&mut self, ctx: &Context) -> R { + let target = if ctx.get("target").is_some() { + Some(self.one_entity(ctx, "target", false)?) + } else { + None + }; + let player = if ctx.get("player").is_some() { + self.one_entity(ctx, "player", true)? + } else { + self.source_player()? + }; + if target == Some(player) { + return Err(err("commands.spectate.self", &[])); + } + if !self.spectator() { + return Err(tr_error( + "commands.spectate.not_spectator", + &[self.target_name(player)], + )); + } + self.set_camera(target); + match target { + Some(t) => { + let name = self.target_name(t); + self.feedback(Text::translate("commands.spectate.success.started", &[name])); + } + None => self.feedback(Text::translate("commands.spectate.success.stopped", &[])), + } + Ok(1) + } + /// `ServerPlayer.setCamera`: a new camera moves the player to it. + pub(in crate::game) fn set_camera(&mut self, target: Option) { + let target = target.filter(|t| *t != Target::Player); + if self.cmds.camera == target { + return; + } + self.cmds.camera = target; + if let Some(t) = target + && let Some(p) = self.target_position(t) + && let Some(player) = self.player.as_mut() + { + player.position = horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + self.previous_position = player.position; + } + } + /// Per-tick server work of these commands: the delayed tick profiler + /// start, queued messages and the spectator camera. + pub(in crate::game) fn tick_command_extras(&mut self) { + if self.cmds.profiler_delay { + self.cmds.profiler_delay = false; + self.cmds.profiler = Some((Instant::now(), self.ticks)); + } + for message in std::mem::take(&mut self.cmds.pending) { + self.system_message(message); + } + self.tick_camera(); + } + /// The camera part of `ServerPlayer.tick`: follow a living camera, drop a + /// removed one, and stop when the player sneaks or leaves spectator mode. + fn tick_camera(&mut self) { + let Some(t) = self.cmds.camera else { + return; + }; + if !self.spectator() { + self.set_camera(None); + return; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) + && self.screen == super::Screen::Playing; + match self.target_position(t) { + Some(p) if !sneaking => { + let rot = self.target_rotation(t); + if let Some(player) = self.player.as_mut() { + player.position = horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + } + self.yaw = rot[0]; + self.pitch = rot[1]; + } + _ => self.set_camera(None), + } + } + /// The eye height the camera follows (`Camera.tick`'s entity). + pub(in crate::game) fn camera_eye_height(&self) -> Option { + self.cmds + .camera + .map(|t| self.target_eye_height(t) as f32) + } + + // ---- /waypoint ------------------------------------------------------ + + /// `ServerWaypointManager.transmitters()`: living entities whose + /// `waypoint_transmit_range` is positive. + fn waypoint_transmitters(&mut self) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.player.as_mut() + && let Some(k) = p.attributes.key("minecraft:waypoint_transmit_range") + && p.attributes + .value(Some(k), horizon_world::attribute_map::ValueKind::Computed) + .is_ok_and(|v| v > 0.0) + { + out.push(Target::Player); + } + out + } + fn waypoint_icon(&self, t: Target) -> WaypointIcon { + self.cmds.waypoint_icons.get(&t).cloned().unwrap_or_default() + } + /// `WaypointArgument.getWaypoint`. + fn waypoint_arg(&mut self, ctx: &Context) -> R { + let t = self.one_entity(ctx, "waypoint", false)?; + if !self.is_living(t) { + return Err(err("argument.waypoint.invalid", &[])); + } + Ok(t) + } + fn is_living(&self, t: Target) -> bool { + matches!(t, Target::Player | Target::Mob(_) | Target::Stand(_)) + } + pub(super) fn cmd_waypoint(&mut self, id: &str, ctx: &Context) -> R { + if id == "waypoint.list" { + let dimension = self.dim.id(); + let waypoints = self.waypoint_transmitters(); + if waypoints.is_empty() { + self.feedback(Text::translate( + "commands.waypoint.list.empty", + &[Text::literal(dimension)], + )); + return Ok(0); + } + let mut names = Text::empty(); + for (i, t) in waypoints.iter().enumerate() { + if i > 0 { + names.push(", "); + } + let pos = self + .target_position(*t) + .unwrap_or_default() + .map(|v| v.floor() as i32); + let color = self.waypoint_icon(*t).color.unwrap_or(-1) as u32 & 0xFF_FFFF; + let style = Style { + color: Some(color), + suggest: Some(format!( + "/execute in {dimension} run tp @s {} {} {}", + pos[0], pos[1], pos[2] + )), + hover: Some(Box::new(Text::translate("chat.coordinates.tooltip", &[]))), + ..Style::default() + }; + // getFeedbackDisplayName().copy().withStyle(color): the + // waypoint colour replaces the team colour of the name. + let name = match (*t, self.score.board.players_team(super::super::chat::PLAYER_NAME)) { + (Target::Player, Some(team)) => { + let mut n = Text::empty(); + n.push(horizon_client::scoreboard::comp_text(&team.prefix)); + n.push(super::super::chat::PLAYER_NAME); + n.push(horizon_client::scoreboard::comp_text(&team.suffix)); + n + } + _ => self.target_name(*t), + }; + names.push(name.with_style(&style)); + } + let n = waypoints.len() as i32; + self.feedback(Text::translate( + "commands.waypoint.list.success", + &[num(n), Text::literal(dimension), names], + )); + return Ok(n); + } + let t = self.waypoint_arg(ctx)?; + let mut icon = self.waypoint_icon(t); + let style_literal = ctx.literals.iter().any(|l| l == "style"); + let message = if style_literal { + icon.style = if ctx.literals.iter().any(|l| l == "reset") { + "minecraft:default".into() + } else { + match ctx.get("style") { + Some(Arg::Resource(s)) => s.clone(), + _ => "minecraft:default".into(), + } + }; + Text::translate("commands.waypoint.modify.style", &[]) + } else if ctx.literals.iter().any(|l| l == "reset") { + icon.color = None; + Text::translate("commands.waypoint.modify.color.reset", &[]) + } else if ctx.literals.iter().any(|l| l == "hex") { + let rgb = match ctx.get("color") { + Some(Arg::Int(v)) => *v, + _ => 0, + }; + icon.color = Some(rgb); + let hex = format!("{:06X}", rgb as u32 & 0xFF_FFFF); + Text::translate( + "commands.waypoint.modify.color", + &[Text::colored(hex, rgb as u32 & 0xFF_FFFF)], + ) + } else { + let name = match ctx.get("color") { + Some(Arg::Str(s)) => s.clone(), + _ => "white".into(), + }; + let rgb = text::named_color(&name).unwrap_or(0xFF_FFFF); + icon.color = Some(rgb as i32); + Text::translate( + "commands.waypoint.modify.color", + &[Text::colored(name, rgb)], + ) + }; + self.cmds.waypoint_icons.insert(t, icon); + self.feedback(message); + Ok(0) + } + + // ---- /dialog -------------------------------------------------------- + + pub(super) fn cmd_dialog(&mut self, id: &str, ctx: &Context) -> R { + let targets = self.entities(ctx, "targets", true)?; + let n = targets.len() as i32; + if id == "dialog.show" { + let Some(Arg::Resource(dialog)) = ctx.get("dialog").cloned() else { + return Ok(0); + }; + self.open_dialog(&dialog)?; + } else { + self.close_dialog(); + } + let (single, multiple) = if id == "dialog.show" { + ("commands.dialog.show.single", "commands.dialog.show.multiple") + } else { + ("commands.dialog.clear.single", "commands.dialog.clear.multiple") + }; + let message = if n == 1 { + Text::translate(single, &[self.target_name(targets[0])]) + } else { + Text::translate(multiple, &[num(n)]) + }; + self.feedback(message); + Ok(n) + } + + // ---- /posteffect ---------------------------------------------------- + + pub(super) fn cmd_posteffect(&mut self, id: &str, ctx: &Context) -> R { + if id == "posteffect.list" { + let t = self.one_entity(ctx, "target", true)?; + let name = self.target_name(t); + let effects = self.cmds.post_effects.clone(); + if effects.is_empty() { + self.feedback(Text::translate("commands.posteffect.list.empty", &[name])); + } else { + self.feedback(Text::translate( + "commands.posteffect.list.success", + &[name, num(effects.len()), Text::literal(effects.join(", "))], + )); + } + return Ok(effects.len() as i32); + } + let targets = self.entities(ctx, "targets", true)?; + let effect = match ctx.get("posteffect") { + Some(Arg::Resource(s)) => s.clone(), + _ => String::new(), + }; + let mut changed: Vec = Vec::new(); + for t in &targets { + let done = match id { + "posteffect.add" => { + if self.cmds.post_effects.contains(&effect) { + false + } else { + self.cmds.post_effects.push(effect.clone()); + true + } + } + "posteffect.remove" => { + let before = self.cmds.post_effects.len(); + if let Some(i) = self.cmds.post_effects.iter().position(|e| *e == effect) { + self.cmds.post_effects.remove(i); + } + before != self.cmds.post_effects.len() + } + _ => !std::mem::take(&mut self.cmds.post_effects).is_empty(), + }; + if done { + changed.push(*t); + } + } + let key = id.trim_start_matches("posteffect."); + if changed.is_empty() { + return Err(err(&format!("commands.posteffect.{key}.failed"), &[])); + } + let n = changed.len() as i32; + let effect_text = Text::literal(effect); + let message = match (key, n) { + ("clear", 1) => Text::translate( + "commands.posteffect.clear.success.single", + &[self.target_name(changed[0])], + ), + ("clear", _) => Text::translate("commands.posteffect.clear.success.multiple", &[num(n)]), + (_, 1) => Text::translate( + &format!("commands.posteffect.{key}.success.single"), + &[effect_text, self.target_name(changed[0])], + ), + _ => Text::translate( + &format!("commands.posteffect.{key}.success.multiple"), + &[effect_text, num(n)], + ), + }; + self.feedback(message); + Ok(n) + } + + // ---- /kick ---------------------------------------------------------- + + /// `KickCommand.kickPlayers`: only guests of a published world can be + /// kicked; the owner never. + pub(super) fn cmd_kick(&mut self, ctx: &Context) -> R { + let selector = match ctx.get("targets") { + Some(Arg::Entity(s)) => Some(s.clone()), + _ => None, + }; + // EntityArgument.getPlayers runs before the published check. + let host = self.entities(ctx, "targets", true).unwrap_or_default(); + let guests: Vec<(u32, String)> = match (&self.lan, &selector) { + (Some(lan), Some(s)) => lan + .hub + .guests + .iter() + .filter(|g| match &s.player_name { + Some(name) => g.name.eq_ignore_ascii_case(name), + None => s.kind == 'a' || s.kind == 'e', + }) + .map(|g| (g.conn, g.name.clone())) + .collect(), + _ => Vec::new(), + }; + if host.is_empty() && guests.is_empty() { + return Err(err("argument.entity.notfound.player", &[])); + } + if self.lan.is_none() { + return Err(err("commands.kick.singleplayer.failed", &[])); + } + let reason_raw = match ctx.get("reason") { + Some(Arg::Str(s)) => Some(s.clone()), + _ => None, + }; + let reason = match &reason_raw { + Some(raw) => self.expand_selectors(raw), + None => Text::translate("multiplayer.disconnect.kicked", &[]), + }; + let tag = match &reason_raw { + Some(_) => horizon_world::nbt::Tag::String(reason.plain().as_str().into()), + None => horizon_world::nbt::Tag::compound([( + "translate", + horizon_world::nbt::Tag::String("multiplayer.disconnect.kicked".into()), + )]), + }; + let mut count = 0; + for (conn, name) in guests { + if let Some(lan) = self.lan.as_mut() { + lan.hub.kick(conn, tag.clone()); + } + self.feedback(Text::translate( + "commands.kick.success", + &[Text::literal(name), reason.clone()], + )); + count += 1; + } + if count == 0 { + return Err(err("commands.kick.owner.failed", &[])); + } + Ok(count) + } + + // ---- /fetchprofile -------------------------------------------------- + + /// `FetchProfileCommand`: Horizon resolves no profiles over the network, + /// so name and id lookups fail like an unreachable profile service; an + /// entity with a profile (the player) prints its resolved profile. + pub(super) fn cmd_fetchprofile(&mut self, ctx: &Context) -> R { + if ctx.literals.iter().any(|l| l == "name") { + let name = match ctx.get("name") { + Some(Arg::Str(s)) => s.clone(), + _ => String::new(), + }; + // Resolved off-thread; the answer arrives on a later tick. + self.cmds.pending.push( + Text::translate("commands.fetchprofile.name.failure", &[Text::literal(name)]) + .with_color(text::RED), + ); + return Ok(1); + } + if ctx.literals.iter().any(|l| l == "id") { + let id = match ctx.get("id") { + Some(Arg::Str(s)) => s.to_ascii_lowercase(), + _ => String::new(), + }; + self.cmds.pending.push( + Text::translate("commands.fetchprofile.id.failure", &[Text::literal(id)]) + .with_color(text::RED), + ); + return Ok(1); + } + let t = self.one_entity(ctx, "entity", false)?; + if t != Target::Player { + return Err(tr_error( + "commands.fetchprofile.no_profile", + &[self.target_name(t)], + )); + } + let profile = self.player_profile_snbt(); + let name = super::super::chat::PLAYER_NAME; + let head = format!("{{type:\"minecraft:player\",player:{profile}}}"); + let item = |key: &str, args: &[Text], run: Option| { + let inner = Text::translate(key, args).with_color(text::GREEN); + let mut t = Text::translate("chat.square_brackets", &[inner]); + if let Some(cmd) = run { + t = t.with_style(&Style { + suggest: None, + ..Style::default() + }); + let _ = cmd; + } + t + }; + let placeholder = Text::literal("\u{FFFC}").with_color(text::WHITE); + let mut clickable = item("commands.fetchprofile.copy_component", &[], None); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.give_item", + &[], + Some(format!("give @s minecraft:player_head[profile={profile}]")), + )); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.summon_mannequin", + &[], + Some(format!("summon minecraft:mannequin ~ ~ ~ {{profile:{profile}}}")), + )); + clickable.push(" "); + clickable.push(item("commands.fetchprofile.copy_text", &[placeholder], None)); + let _ = head; + self.feedback(Text::translate( + "commands.fetchprofile.entity.success", + &[Text::literal(name), clickable], + )); + Ok(1) + } + /// ResolvableProfile.CODEC of the player's profile as SNBT. + fn player_profile_snbt(&self) -> String { + let [a, b, c, d] = self.level.player_uuid.unwrap_or([0; 4]); + format!( + "{{id:[I;{a},{b},{c},{d}],name:\"{}\",properties:[]}}", + super::super::chat::PLAYER_NAME + ) + } + + // ---- /publish, /unpublish ------------------------------------------- + + /// `PublishCommand.publish` with `IntegratedServer.publishServer`. + pub(super) fn cmd_publish(&mut self, ctx: &Context) -> R { + let allow = matches!(ctx.get("allowCommands"), Some(Arg::Bool(true))); + let port = match ctx.get("port") { + Some(Arg::Int(p)) => *p, + // HttpUtil.getAvailablePort. + _ => std::net::TcpListener::bind(("0.0.0.0", 0)) + .and_then(|l| l.local_addr()) + .map_or(25564, |a| i32::from(a.port())), + }; + if let Some(lan) = &self.lan { + return Err(err( + "commands.publish.alreadyPublished.lan", + &[&lan.settings.port], + )); + } + let settings = super::super::lan::LanSettings { + port: port as u16, + guest_commands: allow, + force_game_mode: false, + }; + if self.lan_start(settings).is_err() { + return Err(err("commands.publish.failed", &[])); + } + let port_text = port.to_string(); + let link = Text::literal(port_text.clone()).with_style(&Style { + color: Some(text::GREEN), + hover: Some(Box::new(Text::translate("chat.copy.click", &[]))), + ..Style::default() + }); + self.feedback(Text::translate( + "commands.publish.started.lan", + &[Text::translate("chat.square_brackets", &[link])], + )); + Ok(port) + } + pub(super) fn cmd_unpublish(&mut self) -> R { + if self.lan.is_none() { + return Err(err("commands.unpublish.notPublished", &[])); + } + self.lan_close(false); + self.feedback(Text::translate("commands.unpublish.success", &[])); + Ok(1) + } + + // ---- /debug, /jfr, /version ----------------------------------------- + + pub(super) fn cmd_debug(&mut self, ctx: &Context) -> R { + if ctx.literals.iter().any(|l| l == "function") { + return self.cmd_debug_function(ctx); + } + // MinecraftServer.isTimeProfilerRunning / startTimeProfiler / + // stopTimeProfiler: a stop before the delayed start took effect + // reports empty results and leaves the start pending. + let running = self.cmds.profiler_delay || self.cmds.profiler.is_some(); + if ctx.literals.iter().any(|l| l == "start") { + if running { + return Err(err("commands.debug.alreadyRunning", &[])); + } + self.cmds.profiler_delay = true; + self.feedback(Text::translate("commands.debug.started", &[])); + return Ok(0); + } + if !running { + return Err(err("commands.debug.notRunning", &[])); + } + let (seconds, ticks) = match self.cmds.profiler.take() { + Some((started, ticks)) => ( + started.elapsed().as_nanos() as f64 / 1.0e9, + (self.ticks - ticks) as f64, + ), + None => (0.0, 0.0), + }; + let tps = ticks / seconds; + self.feedback(Text::translate( + "commands.debug.stopped", + &[ + Text::literal(two_places(seconds)), + num(ticks as i64), + Text::literal(two_places(tps)), + ], + )); + Ok(tps as i32) + } + /// `DebugCommand.TraceCustomExecutor`: run the functions with a tracer + /// writing to `debug/debug-trace-