diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index 1b6905bef..39d738b7f 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -61,6 +61,7 @@ fn parser_id(ty: &ArgType) -> String { _ => "minecraft:template_rotation".into(), }, ArgType::HexColor => "minecraft:hex_color".into(), + ArgType::ResourceSelector(_) => "minecraft:resource_selector".into(), ArgType::Uuid => "minecraft:uuid".into(), ArgType::GameProfile => "minecraft:game_profile".into(), ArgType::Style => "minecraft:style".into(), @@ -120,7 +121,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value { } children.insert(child.name().to_owned(), v); } - let mut v = json!({"children": children}); + let order: Vec<&str> = n.children.iter().map(|&c| d.nodes[c].name()).collect(); + let mut v = json!({"children": children, "order": order}); if n.command.is_some() { v["executable"] = json!(true); } 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 43770802f..219f59654 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -83,6 +83,73 @@ 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) { @@ -254,6 +321,47 @@ pub enum ArgType { SlotSource, /// ResourceOrIdArgument over a registry: an id or an inline SNBT value. ResourceOrId(&'static str), + /// ResourceSelectorArgument: a `*`/`?` pattern over a registry's ids. + ResourceSelector(&'static str), +} + +/// FilenameUtils.wildcardMatch (case-sensitive) of `*` and `?` patterns. +pub fn wildcard_match(text: &str, pattern: &str) -> bool { + let t: Vec = text.chars().collect(); + let p: Vec = pattern.chars().collect(); + let (mut ti, mut pi) = (0, 0); + let (mut star, mut mark) = (None, 0); + while ti < t.len() { + if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { + ti += 1; + pi += 1; + } else if pi < p.len() && p[pi] == '*' { + star = Some(pi); + mark = ti; + pi += 1; + } else if let Some(s) = star { + pi = s + 1; + mark += 1; + ti = mark; + } else { + return false; + } + } + while pi < p.len() && p[pi] == '*' { + pi += 1; + } + pi == p.len() +} +/// ResourceSelectorArgument: the registry ids a pattern selects. +pub fn select_resources<'a>(ids: &'a [String], pattern: &str) -> Vec<&'a String> { + let pattern = if pattern.contains(':') { + pattern.to_owned() + } else { + format!("minecraft:{pattern}") + }; + ids.iter() + .filter(|id| wildcard_match(id, &pattern)) + .collect() } /// SlotRanges.SLOTS: every slot range name and its size, in vanilla order. @@ -1348,6 +1456,29 @@ impl ArgType { } Arg::Str(name.to_owned()) } + ArgType::ResourceSelector(registry) => { + let start = reader.cursor; + while reader.can_read() && { + let c = reader.peek(); + is_id_char(c) || c == '*' || c == '?' + } { + reader.skip(); + } + let raw = reader.string[start..reader.cursor].to_owned(); + let pattern = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + if select_resources(reg.ids(registry), &pattern).is_empty() { + return Err(CommandError::tr_at( + "argument.resource_selector.not_found", + &[&pattern, registry], + reader, + )); + } + Arg::Str(pattern) + } ArgType::HexColor => { let text = reader.read_unquoted_string(); if !matches!(text.len(), 3 | 6) { @@ -1579,7 +1710,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)?; @@ -1741,6 +1873,9 @@ impl ArgType { } ArgType::StrEnum(values, _) => builder.suggest_matching(values.iter().copied()), ArgType::HexColor => builder.suggest_matching(["F00", "FF0000"]), + ArgType::ResourceSelector(registry) => { + suggest_resources(builder, reg.ids(registry), "") + } ArgType::GameProfile => { let players = reg.players.clone(); super::selector::suggest(builder, reg, &|b| { diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-client/src/command/codec.rs index 783d26e30..7c4d26682 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-client/src/command/codec.rs @@ -77,11 +77,23 @@ fn require(map: &Compound, t: &Tag, keys: &[&str]) -> Result<(), String> { Err(missing.join("; ")) } } +/// The required fields of each context number provider type, in the +/// order DataFixerUpper reports them missing (the reverse of the record's). fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> { - match id { - "minecraft:uniform" => require(map, t, &["max", "min"]), - "minecraft:constant" => require(map, t, &["value"]), - "minecraft:binomial" => require(map, t, &["n", "p"]), + match id.trim_start_matches("minecraft:") { + "uniform" => require(map, t, &["max", "min"]), + "constant" => require(map, t, &["value"]), + "binomial" => require(map, t, &["p", "n"]), + "add" | "mul" | "avg" | "max" | "min" | "length" => require(map, t, &["inputs"]), + "sub" | "div" | "mod" | "floor_div" | "floor_mod" => require(map, t, &["right", "left"]), + "pow" => require(map, t, &["exponent", "base"]), + "abs" | "negate" | "from_float" | "from_int" | "floor" | "ceil" | "round" | "sqrt" + | "sin" | "cos" | "truncate" => require(map, t, &["input"]), + "conditional" => require(map, t, &["on_true", "condition"]), + "number_dispatcher" => require(map, t, &["cases"]), + "weighted_list" => require(map, t, &["distribution"]), + "enchantment_level" => require(map, t, &["amount"]), + "score" => require(map, t, &["score", "target"]), _ => Ok(()), } } @@ -130,7 +142,19 @@ pub fn decode(registry: &str, t: &Tag, reg: &Registries) -> Result<(), String> { "minecraft:slot_source" => element_or_list(t, &|x| { dispatch(x, reg, "minecraft:slot_source_type", &|_, _, _| Ok(())) }), - "minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|_, _, _| Ok(())), + // Dialog types: CommonDialogData's title, then each type's own. + "minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|id, map, t| { + let own: &[&str] = match id { + "minecraft:confirmation" => &["yes", "no"], + "minecraft:multi_action" => &["actions"], + "minecraft:dialog_list" => &["dialogs"], + _ => &[], + }; + let keys: Vec<&str> = std::iter::once("title") + .chain(own.iter().copied()) + .collect(); + require(map, t, &keys) + }), "minecraft:worldgen/feature" | "minecraft:loot_table" => match t { Tag::Compound(_) => Ok(()), _ => Err(not_map(t)), diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index e6931852a..79041beb5 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -18,6 +18,7 @@ pub mod tree_misc; pub mod tree_scoreboard; pub mod tree_world; pub mod vanilla; +mod vanilla_order; use crate::text::Text; pub use args::{Arg, ArgType, Registries}; diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-client/src/command/tree_extra.rs index 636aaf0db..a4f0d15ff 100644 --- a/crates/horizon-client/src/command/tree_extra.rs +++ b/crates/horizon-client/src/command/tree_extra.rs @@ -1,7 +1,6 @@ -//! Commands Horizon parses but does not run (multiplayer, profiling and -//! server-only features): `/dialog`, `/kick`, `/posteffect`, `/fetchprofile`, -//! `/spectate`, `/publish`, `/unpublish`, `/waypoint`, `/debug`, `/jfr` and -//! the `/test` root. +//! Commands of the hosted game rather than the world: `/dialog`, `/kick`, +//! `/posteffect`, `/fetchprofile`, `/spectate`, `/publish`, `/unpublish`, +//! `/waypoint`, `/debug`, `/jfr` and `/test`. use super::{ Dispatcher, args::ArgType, @@ -126,7 +125,84 @@ pub fn register(d: &mut Dispatcher, root: usize) { d.executes(l, "jfr"); } - // TestCommand (game tests; only its root is modelled) + // TestCommand (release build: no export subcommands) let test = d.literal(root, "test"); d.requires(test, GAMEMASTERS); + let tests = ArgType::ResourceSelector("minecraft:test_instance"); + let int0 = ArgType::Integer { + min: 0, + max: i32::MAX, + }; + let int = ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }; + // numberOfTimes [untilFailed [rotationSteps [testsPerRow]]], or only + // the first two. + let retry = |d: &mut Dispatcher, node: usize, id: &'static str, build_info: bool| { + let n = d.argument(node, "numberOfTimes", int0.clone()); + d.executes(n, id); + let u = d.argument(n, "untilFailed", ArgType::Bool); + d.executes(u, id); + if build_info { + let r = d.argument(u, "rotationSteps", int.clone()); + d.executes(r, id); + let t = d.argument(r, "testsPerRow", int.clone()); + d.executes(t, id); + } + }; + let run = d.literal(test, "run"); + let t = d.argument(run, "tests", tests.clone()); + d.executes(t, "test.run"); + retry(d, t, "test.run", true); + let multiple = d.literal(test, "runmultiple"); + let t = d.argument(multiple, "tests", tests.clone()); + d.executes(t, "test.run"); + let a = d.argument(t, "amount", int.clone()); + d.executes(a, "test.run"); + for name in ["runthese", "runclosest", "runthat"] { + let l = d.literal(test, name); + d.executes(l, "test.run.found"); + retry(d, l, "test.run.found", false); + } + let failed = d.literal(test, "runfailed"); + d.executes(failed, "test.run.found"); + let only = d.argument(failed, "onlyRequiredTests", ArgType::Bool); + d.executes(only, "test.run.found"); + retry(d, only, "test.run.found", true); + retry(d, failed, "test.run.found", true); + let verify = d.literal(test, "verify"); + let t = d.argument(verify, "tests", tests.clone()); + d.executes(t, "test.verify"); + let locate = d.literal(test, "locate"); + let t = d.argument(locate, "tests", tests); + d.executes(t, "test.locate"); + for name in [ + "resetclosest", + "resetthese", + "resetthat", + "clearthat", + "clearthese", + ] { + let l = d.literal(test, name); + d.executes(l, "test.clear"); + } + let all = d.literal(test, "clearall"); + d.executes(all, "test.clear"); + let r = d.argument(all, "radius", int.clone()); + d.executes(r, "test.clear"); + let stop = d.literal(test, "stop"); + d.executes(stop, "test.stop"); + let pos = d.literal(test, "pos"); + d.executes(pos, "test.pos"); + let var = d.argument(pos, "var", ArgType::Word); + d.executes(var, "test.pos"); + let create = d.literal(test, "create"); + let id = d.argument(create, "id", ArgType::Id("none")); + d.executes(id, "test.create"); + let w = d.argument(id, "width", int.clone()); + d.executes(w, "test.create"); + let h = d.argument(w, "height", int.clone()); + let depth = d.argument(h, "depth", int); + d.executes(depth, "test.create"); } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 495f36966..daf4ecf86 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -403,6 +403,7 @@ pub fn build_with(dev: bool) -> Dispatcher { super::tree_misc::register(&mut d, root); super::tree_world::register(&mut d, root); super::tree_extra::register(&mut d, root); + apply_vanilla_order(&mut d); d } @@ -506,6 +507,42 @@ pub fn game_modes() -> [&'static str; 4] { GameMode::ALL.map(GameMode::name) } /// The shared vanilla tree. +/// Reorder node children as vanilla registers them (Brigadier keeps +/// children in registration order; smart usage lists them that way). +fn apply_vanilla_order(d: &mut Dispatcher) { + for (path, order) in super::vanilla_order::ORDER { + let mut node = Some(0usize); + for name in path.split(' ').filter(|n| !n.is_empty()) { + node = node.and_then(|n| { + d.nodes[n] + .children + .iter() + .copied() + .find(|&c| d.nodes[c].name() == name) + }); + } + let Some(n) = node else { continue }; + let mut children = d.nodes[n].children.clone(); + let rank = |c: usize| { + order + .iter() + .position(|o| *o == d.nodes[c].name()) + .unwrap_or(order.len()) + }; + children.sort_by_key(|&c| rank(c)); + d.nodes[n].children = children; + } +} +/// The tree the game runs: a release integrated server's, or with +/// `HORIZON_DEV_COMMANDS` set the development one +/// (SharedConstants.DEBUG_DEV_COMMANDS). +pub fn game_dispatcher() -> &'static Dispatcher { + if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() { + dispatcher() + } else { + release_dispatcher() + } +} pub fn dispatcher() -> &'static Dispatcher { static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); TREE.get_or_init(build) diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-client/src/command/vanilla_order.rs new file mode 100644 index 000000000..fb7dcde2b --- /dev/null +++ b/crates/horizon-client/src/command/vanilla_order.rs @@ -0,0 +1,234 @@ +//! The order of node children in vanilla's command tree, for the nodes +//! where Horizon's tree registers them differently (path of node names +//! from the root, children in vanilla's order). Generated by +//! tools/generate_command_order.py; do not edit by hand. + +pub const ORDER: &[(&str, &[&str])] = &[ + ( + "", + &[ + "advancement", + "attribute", + "execute", + "bossbar", + "clear", + "clone", + "compute", + "damage", + "data", + "datapack", + "debug", + "defaultgamemode", + "dialog", + "difficulty", + "effect", + "me", + "enchant", + "experience", + "xp", + "fill", + "fillbiome", + "forceload", + "function", + "gamemode", + "gamerule", + "give", + "help", + "item", + "kick", + "kill", + "list", + "locate", + "loot", + "msg", + "tell", + "w", + "swing", + "particle", + "place", + "playsound", + "posteffect", + "random", + "reload", + "recipe", + "fetchprofile", + "return", + "ride", + "rotate", + "say", + "schedule", + "scoreboard", + "seed", + "version", + "setblock", + "spawnpoint", + "setworldspawn", + "spectate", + "spreadplayers", + "stopsound", + "stopwatch", + "summon", + "tag", + "team", + "teammsg", + "tm", + "teleport", + "tp", + "tellraw", + "test", + "tick", + "time", + "title", + "trigger", + "waypoint", + "weather", + "worldborder", + "jfr", + "publish", + "unpublish", + ], + ), + ( + "execute", + &[ + "run", + "if", + "unless", + "as", + "at", + "store", + "positioned", + "rotated", + "facing", + "align", + "anchored", + "in", + "summon", + "on", + ], + ), + ( + "execute if", + &[ + "block", + "biome", + "loaded", + "dimension", + "score", + "blocks", + "entity", + "predicate", + "function", + "stopwatch", + "data", + "items", + "slots", + ], + ), + ( + "execute unless", + &[ + "block", + "biome", + "loaded", + "dimension", + "score", + "blocks", + "entity", + "predicate", + "function", + "stopwatch", + "data", + "items", + "slots", + ], + ), + ("execute facing", &["entity", "pos"]), + ("datapack", &["enable", "disable", "list", "create"]), + ( + "datapack enable name", + &["after", "before", "last", "first"], + ), + ("item", &["replace", "fill", "override", "modify"]), + ("item replace entity target slots", &["from", "with"]), + ("item fill entity target slots", &["from", "with"]), + ("item override entity target slots", &["from", "with"]), + ( + "loot replace entity entities slot", + &["fish", "loot", "kill", "mine", "count"], + ), + ( + "loot replace entity entities slot fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace entity entities slot mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace entity entities slot count fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace entity entities slot count mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot", + &["fish", "loot", "kill", "mine", "count"], + ), + ( + "loot replace block targetPos slot fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot count fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot count mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot insert targetPos fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot insert targetPos mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot give players fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot give players mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot spawn targetPos fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot spawn targetPos mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "scoreboard players", + &[ + "list", + "set", + "get", + "add", + "remove", + "reset", + "enable", + "display", + "operation", + ], + ), +]; diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 115bf74af..0e04eab5e 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -172,6 +172,14 @@ fn object_style(o: &serde_json::Map) -> Style { /// `ComponentSerialization.CODEC` decoding into text. `selector` components /// are resolved by `resolve` (ComponentUtils.updateForEntity). pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { + to_text_with(v, resolve, &mut |_| None) +} +/// `to_text` with a hook resolving other contents (`nbt`) from the object. +pub fn to_text_with( + v: &Value, + resolve: &mut dyn FnMut(&str) -> Text, + contents: &mut dyn FnMut(&serde_json::Map) -> Option, +) -> Text { match v { Value::String(s) => Text::literal(s.clone()), Value::Number(n) => Text::literal(n.to_string()), @@ -181,7 +189,7 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { let Some((first, rest)) = list.split_first() else { return Text::empty(); }; - let mut base = to_text(first, resolve); + let mut base = to_text_with(first, resolve, contents); // The siblings take the first component's own style, even when // its text is empty. let style = match first { @@ -193,13 +201,15 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { .unwrap_or_default(), }; for sibling in rest { - base.push(to_text(sibling, resolve).with_style(&style)); + base.push(to_text_with(sibling, resolve, contents).with_style(&style)); } base } Value::Object(o) => { let style = object_style(o); - let content = if let Some(t) = o.get("text") { + let content = if let Some(t) = contents(o) { + t + } else if let Some(t) = o.get("text") { match t { Value::String(s) => Text::literal(s.clone()), other => Text::literal(other.to_string()), @@ -208,7 +218,11 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { let args: Vec = o .get("with") .and_then(Value::as_array) - .map(|a| a.iter().map(|x| to_text(x, resolve)).collect()) + .map(|a| { + a.iter() + .map(|x| to_text_with(x, resolve, contents)) + .collect() + }) .unwrap_or_default(); let translated = Text::translate(key, &args); match o.get("fallback").and_then(Value::as_str) { @@ -229,7 +243,7 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { .into_iter() .flatten() { - out.push(to_text(extra, resolve).with_style(&style)); + out.push(to_text_with(extra, resolve, contents).with_style(&style)); } out } diff --git a/crates/horizon-client/src/datapack.rs b/crates/horizon-client/src/datapack.rs index d0874ac03..b76a4f243 100644 --- a/crates/horizon-client/src/datapack.rs +++ b/crates/horizon-client/src/datapack.rs @@ -67,6 +67,15 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec) { } } } +impl DataPack { + /// The built-in `vanilla` pack: the game's own data directory. + pub fn builtin(root: &Path) -> Self { + DataPack { + id: "vanilla".into(), + source: Source::Dir(root.to_path_buf()), + } + } +} /// The packs in `/datapacks`, sorted by name. pub fn discover(world: &Path) -> Vec { let Ok(entries) = std::fs::read_dir(world.join("datapacks")) else { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 1eddf2593..1afcd4f91 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1120,6 +1120,25 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> { put(&mut tag, "Health", Tag::Float(20f32.to_bits())); } + // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. + if let Tag::Compound(map) = &mut tag { + for (key, value) in [ + ("HurtTime", Tag::Short(0)), + ("DeathTime", Tag::Short(0)), + ("AbsorptionAmount", Tag::Float(0)), + ("FallFlying", Tag::Byte(0)), + ("current_impulse_context_reset_grace_time", Tag::Int(0)), + ("attributes", Tag::List(Vec::new())), + ( + "Brain", + Tag::compound([("memories", Tag::Compound(Compound::new()))]), + ), + ("DisabledSlots", Tag::Int(0)), + ("Pose", Tag::Compound(Compound::new())), + ] { + map.entry(key.into()).or_insert(value); + } + } tag } pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client/src/fastutil_order.rs new file mode 100644 index 000000000..6065763d2 --- /dev/null +++ b/crates/horizon-client/src/fastutil_order.rs @@ -0,0 +1,153 @@ +//! 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 68b13055e..bf3787426 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -15,6 +15,7 @@ mod breezes; mod cartography; mod chat; mod combat; +mod command_harness; mod commands; mod control; mod creaking; @@ -683,6 +684,8 @@ struct Game<'a> { map_frame_model: frames::FrameModel, glow_map_frame_model: frames::FrameModel, armor_stands: Vec, + /// Entities of types Horizon does not simulate. + others: Vec, armor_stand_assets: armor_stands::ArmorStandAssets, boats: Vec, boat_models: boats::BoatModels, @@ -742,7 +745,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, @@ -2512,6 +2517,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); @@ -2609,7 +2616,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.tick_avatar(before, riding); self.record_combat(&events); @@ -8084,6 +8091,7 @@ pub fn run() -> Result<()> { map_frame_model: frames::bake_frame(&root, "item_frame_map"), glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), armor_stands: Vec::new(), + others: Vec::new(), armor_stand_assets: armor_stands::ArmorStandAssets::load(&root), boats: Vec::new(), boat_models: boats::BoatModels::load(&root), @@ -8127,6 +8135,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(), @@ -8173,6 +8182,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/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 6742e7043..3c8a406cc 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -168,6 +168,12 @@ fn now_text() -> String { rem % 60 ) } +impl Game<'_> { + /// `ItemPredicate.test` (the `item_filter` of a filtered item modifier). + pub(super) fn loot_item_filter(&self, predicate: &Value, s: &ItemStack) -> bool { + adv::item(predicate, &item_view(s), &View(self)) + } +} pub(super) fn item_view(s: &ItemStack) -> ItemView { ItemView { id: s.item.to_string(), @@ -505,6 +511,17 @@ impl Game<'_> { return; } self.check_inventory_trigger(); + // ServerPlayer.tick: PlayerTrigger.TICK every tick. + let me = self.player_entity(); + self.trigger("minecraft:tick", |c, w| { + let ctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &ctx, w) + }); if self.ticks.is_multiple_of(20) { let me = self.player_entity(); self.trigger("minecraft:location", |c, w| { diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 579ee99d7..c4c235aca 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -286,7 +286,11 @@ impl Game<'_> { reg.structures = list("data/minecraft/worldgen/structure"); reg.biomes = list("data/minecraft/worldgen/biome"); reg.clocks = list("data/minecraft/world_clock"); - reg.dimensions = vec!["minecraft:overworld".into(), "minecraft:the_nether".into()]; + reg.dimensions = vec![ + "minecraft:overworld".into(), + "minecraft:the_nether".into(), + "minecraft:the_end".into(), + ]; reg.players = vec![PLAYER_NAME.into()]; // Timelines of the overworld clock and their time markers. self.ui.markers.clear(); @@ -324,6 +328,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 +381,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; @@ -397,7 +410,7 @@ impl Game<'_> { return; }; let atlas = &self.res.atlas; - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) { self.ui.chat_screen = Some(screen); return; @@ -515,7 +528,7 @@ impl Game<'_> { screen.draw( batch, &self.res.atlas, - vanilla::dispatcher(), + vanilla::game_dispatcher(), &self.ui.registries, self.cursor, bg, 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..0409b410c --- /dev/null +++ b/crates/horizon-client/src/game/command_harness.rs @@ -0,0 +1,137 @@ +//! 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() { + 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()); + // The oracle's player has no client moving it: hold the + // player where commands put it while the game ticks. + let held = self.player.as_ref().map(|p| p.position); + for _ in 0..op["n"].as_u64().unwrap_or(1) { + self.update_world(); + self.tick()?; + if let (Some(p), Some(at)) = (self.player.as_mut(), held) { + p.position = at; + p.velocity = horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0); + p.fall_distance = 0.0; + } + } + 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 0c7f2ca1d..d45e10e8a 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1,8 +1,10 @@ //! Command execution (the `execute` side of each vanilla command class): //! entity selectors resolved against the game, vanilla feedback and errors. +mod compute; mod data; mod effects; pub(super) mod execute; +pub(super) mod extra; mod items; mod misc; mod place; @@ -40,6 +42,19 @@ pub(super) enum Target { Painting(u32), Boat(u32), Cart(u32), + /// An entity of a type Horizon does not simulate (markers, displays, + /// interactions...): kept as its saved data at a position. + Other(u32), +} +/// An entity of a type Horizon does not simulate: its compound lives in the +/// entity memory (`persist.raw`), its position and rotation here. +#[derive(Clone, Debug)] +pub(in crate::game) struct OtherEntity { + pub id: u32, + pub kind: String, + pub position: Vec3, + pub yaw: f32, + pub pitch: f32, } pub(super) fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError { CommandError::tr(key, args) @@ -63,7 +78,7 @@ fn format_double(v: f64) -> String { impl Game<'_> { /// Commands.performCommand for a line without its slash. pub(super) fn run_command(&mut self, command: &str) { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let parse = d.parse(command, &self.ui.registries); let result = match parse.executable() { Err(e) => { @@ -84,6 +99,10 @@ impl Game<'_> { self.command_failure(e.message); } } + // InventoryChangeTrigger fires as slots change, not on the next tick. + if self.player.is_some() { + self.check_inventory_trigger(); + } } fn syntax_failure(&mut self, e: &CommandError, command: &str) { self.command_failure(e.message.clone()); @@ -169,7 +188,8 @@ impl Game<'_> { .ok_or_else(|| err("argument.pos.missing.int", &[]))?; // BlockPos.containing(getPosition) let p = self.resolve_coords(&c).map(|v| v.floor() as i32); - if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { + let elsewhere = self.command_source.is_some_and(|s| s.elsewhere); + if elsewhere || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { return Err(err("argument.pos.unloaded", &[])); } if p[1] < horizon_client::chunk::MIN_Y @@ -242,6 +262,11 @@ impl Game<'_> { .iter() .find(|c| c.id == id) .map(|c| [c.position.x, c.position.y, c.position.z]), + Target::Other(id) => self + .others + .iter() + .find(|o| o.id == id) + .map(|o| [o.position.x, o.position.y, o.position.z]), } } pub(super) fn target_type(&self, t: Target) -> String { @@ -276,12 +301,21 @@ impl Game<'_> { .iter() .find(|c| c.id == id) .map_or_else(|| "minecraft:minecart".into(), |c| c.kind.id().into()), + Target::Other(id) => self + .others + .iter() + .find(|o| o.id == id) + .map_or_else(String::new, |o| o.kind.clone()), } } /// 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 @@ -305,6 +339,21 @@ impl Game<'_> { Text::literal(name.unwrap_or_default()) } other => { + // Entity.getDisplayName: the CustomName component, else the type. + let custom = match other { + Target::Stand(id) + | Target::Frame(id) + | Target::Painting(id) + | Target::Boat(id) + | Target::Cart(id) + | Target::Other(id) => self.persist_raw(id).and_then(|r| r.get("CustomName")), + _ => None, + }; + if let Some(c) = custom { + return horizon_client::scoreboard::comp_text( + &horizon_client::scoreboard::tag_to_json(c), + ); + } let ty = self.target_type(other); Text::translate(&format!("entity.{}", ty.replace(':', ".")), &[]) } @@ -349,6 +398,7 @@ impl Game<'_> { candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); + candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); } let level = self.experience.level; let creative = self.creative; @@ -535,7 +585,23 @@ 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(), + id if id.starts_with("test.") => self.cmd_test(id, ctx), + "compute" => self.cmd_compute(ctx), "place" => self.cmd_place(ctx), + "place.feature" | "place.jigsaw" | "place.structure" => { + self.cmd_place_generated(id, ctx) + } "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), "rotate" => self.cmd_rotate(ctx), @@ -543,7 +609,18 @@ impl Game<'_> { "playsound" => self.cmd_playsound(ctx), "stopsound" => self.cmd_stopsound(ctx), "particle" => self.cmd_particle(ctx), - id if id.starts_with("attribute.") => self.cmd_attribute(id, ctx), + id if id.starts_with("attribute.") => { + let result = self.cmd_attribute(id, ctx); + // AttributeInstance.setDirty: the entity reacts when it ticks. + if result.is_ok() + && matches!(ctx.get("attribute"), Some(Arg::Resource(a)) if a == "minecraft:waypoint_transmit_range") + && !id.ends_with("get") + && let Ok(t) = self.entities(ctx, "target", false) + { + self.cmds.waypoint_dirty.push(t[0]); + } + result + } "ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx), "spreadplayers" => self.cmd_spreadplayers(ctx), id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx), @@ -569,6 +646,7 @@ impl Game<'_> { self.cmd_scoreboard(id, ctx) } "locate.structure" | "locate.biome" => self.cmd_locate(id, ctx), + "locate.poi" => self.cmd_locate_poi(ctx), "warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => { let level = Self::int(ctx, "warning_level"); self.cmd_warden_spawn_tracker(level); @@ -581,7 +659,7 @@ impl Game<'_> { "commands.list.nameAndId", &[ Text::literal(PLAYER_NAME), - Text::literal("00000000-0000-0000-0000-000000000000"), + Text::literal(self.player_uuid_string()), ], ) } else { @@ -597,7 +675,7 @@ impl Game<'_> { } } fn cmd_help(&mut self, ctx: &Context) -> R { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let level = self.ui.registries.permission; match ctx.get("command") { None => { @@ -653,16 +731,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], @@ -685,6 +770,57 @@ impl Game<'_> { .append("]") .with_color(color) } + /// `ItemStack.getDisplayName`: the hover name (custom name in italics, + /// a written book's title, a potion's effect name...) in brackets, in the + /// rarity colour unless the stack is empty. + pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text { + let item = &*s.item; + let empty = item == "minecraft:air" || s.count == 0; + let custom = s.custom_name(); + let hover = if let Some(c) = custom { + Text::literal(c).italic() + } else if let Some(title) = s + .data() + .and_then(|d| d.written.as_ref()) + .map(|w| w.title.clone()) + .filter(|t| !t.trim().is_empty()) + { + Text::literal(title) + } else if matches!( + item, + "minecraft:potion" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:tipped_arrow" + ) && s.potion().is_some() + { + Text::translate( + &horizon_client::brewing::potion_name_key(item, s.potion()), + &[], + ) + } else { + Text::literal(self.res.names.item(item)) + }; + let wrapped = Text::translate("chat.square_brackets", &[hover]); + if empty { + return wrapped; + } + let mut rarity = self.item_rarity(item); + if !s.enchantments().is_empty() { + rarity = match rarity.as_str() { + "rare" => "epic".into(), + "epic" => rarity, + _ => "rare".into(), + }; + } + let color = match rarity.as_str() { + "uncommon" => text::YELLOW, + "rare" => text::AQUA, + "epic" => text::LIGHT_PURPLE, + _ => text::WHITE, + }; + wrapped.with_color(color) + } pub(super) fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -731,7 +867,9 @@ impl Game<'_> { ], ))); } - for _ in &targets { + // An air stack is empty: nothing is given (but the message still is). + let empty = id == "minecraft:air"; + for _ in targets.iter().filter(|_| !empty) { let mut remaining = count; while remaining > 0 { let size = remaining.min(max_stack); @@ -755,7 +893,12 @@ impl Game<'_> { } } } - let name = self.item_display_name(&id); + let name = self.stack_display_name(&ItemStack { + item: id.as_str().into(), + count: count.max(1) as u32, + damage, + extra: extra.clone(), + }); let message = if targets.len() == 1 { Text::translate( "commands.give.success.single", @@ -848,6 +991,15 @@ impl Game<'_> { } } } + Target::Other(id) => { + if let Some(o) = self.others.iter_mut().find(|o| o.id == id) { + o.position = v; + if let Some([yaw, pitch]) = rotation { + o.yaw = yaw; + o.pitch = pitch; + } + } + } // Wall-mounted entities do not move. Target::Frame(_) | Target::Painting(_) => {} } @@ -1117,7 +1269,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 { @@ -1151,6 +1303,7 @@ impl Game<'_> { Target::Painting(id) => self.paintings.retain(|p| p.id != id), Target::Boat(id) => self.boats.retain(|b| b.id != id), Target::Cart(id) => self.carts.retain(|c| c.id != id), + Target::Other(id) => self.others.retain(|o| o.id != id), } } fn cmd_kill(&mut self, ctx: &Context) -> R { @@ -1185,6 +1338,13 @@ impl Game<'_> { let Some(Arg::Resource(kind)) = ctx.get("entity").cloned() else { return Ok(0); }; + // ResourceArgument.getSummonableEntityType. + if matches!( + kind.as_str(), + "minecraft:player" | "minecraft:fishing_bobber" + ) { + return Err(err("entity.not_summonable", &[&kind])); + } let pos = self .position_arg(ctx, "pos") .unwrap_or(self.source_position()); @@ -1355,12 +1515,14 @@ impl Game<'_> { return Err(err("commands.setblock.failed", &[])); } if ctx.has("destroy") && current != self.world.air { - let creative = self.creative; - self.creative = false; - let _ = self.break_block(pos); - self.creative = creative; + self.destroy_block_dropping(pos)?; } - if !self.place_state(pos, state, ctx.has("strict"))? { + let placed = self.place_state(pos, state, ctx.has("strict"))?; + let loaded = match &b.nbt { + Some(nbt) => self.load_block_entity_nbt(pos, nbt), + None => false, + }; + if !placed && !loaded { return Err(err("commands.setblock.failed", &[])); } self.feedback(Text::tr( @@ -1369,6 +1531,64 @@ impl Game<'_> { )); Ok(1) } + /// `Level.destroyBlock(pos, true)`: the block's drops without a tool or + /// breaker (its loot table, contents of a container), then air. + pub(super) fn destroy_block_dropping(&mut self, pos: [i32; 3]) -> R<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + self.destroy_particles(pos, state); + self.jukebox_removed(pos); + if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) { + let name = self.res.facts.get(state).name.clone(); + self.release_contents(pos, entity, &name); + } + let drops = self.res.items.block_drops_in( + self.res.assets.registry, + state, + None, + &mut self.world.random, + Some((&mut self.rand_sequences, self.level.seed)), + ); + for d in drops { + if &*d.item != "minecraft:air" { + self.pop_resource(pos, d); + } + } + let air = self.world.air; + self.place_state(pos, air, false)?; + Ok(()) + } + /// The block entity part of `BlockInput.place`: load the block entity + /// from the argument's tag; true when its saved data changed. + pub(super) fn load_block_entity_nbt(&mut self, pos: [i32; 3], nbt: &str) -> bool { + use horizon_world::nbt::Tag; + let key = (pos[0], pos[1], pos[2]); + let Some(e) = self.world.block_entities.get(&key) else { + return false; + }; + let name = self.data_block_name(pos); + let before = horizon_client::save::encode_block_entity(key, e, &name); + let Ok((mut tag, _)) = horizon_world::nbt::parse_snbt(nbt) else { + return false; + }; + if let Tag::Compound(c) = &mut tag { + for k in ["id", "x", "y", "z"] { + if let Some(v) = before.get(k) { + c.insert(k.into(), v.clone()); + } + } + } + let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else { + return false; + }; + let after = horizon_client::save::encode_block_entity(key, &new, &name); + if after == before { + return false; + } + self.world.block_entities.insert(key, new); + let state = self.world.block(pos[0], pos[1], pos[2]); + let _ = self.world.set(pos[0], pos[1], pos[2], state); + true + } fn cmd_fill(&mut self, ctx: &Context) -> R { let a = self.block_pos_arg(ctx, "from")?; let b = self.block_pos_arg(ctx, "to")?; @@ -1418,10 +1638,7 @@ impl Game<'_> { || z == max[2]; let mut affected = false; if destroy && current != air { - let creative = self.creative; - self.creative = false; - let _ = self.break_block([x, y, z]); - self.creative = creative; + self.destroy_block_dropping([x, y, z])?; affected = true; } let target = if (outline || hollow) && !edge { @@ -1497,21 +1714,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", &[])); @@ -1758,7 +1983,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; @@ -1808,7 +2033,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())); @@ -1828,9 +2053,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], @@ -1865,6 +2087,89 @@ impl Game<'_> { } predicate.id == item } + /// `ItemPredicateArgument`: the item test and its `[...]` component + /// tests (presence, `=` equality, `!` negation, `|` alternatives). + pub(super) fn stack_matches(&self, predicate: &ItemInput, stack: &ItemStack) -> bool { + if !self.item_matches(predicate, &stack.item) { + return false; + } + let Some(tests) = predicate.components.as_deref() else { + return true; + }; + let inner = tests + .trim() + .strip_prefix('[') + .and_then(|t| t.strip_suffix(']')) + .unwrap_or(""); + let components = match horizon_client::item_data::encode_components(stack) { + Some(horizon_world::nbt::Tag::Compound(c)) => c, + _ => Default::default(), + }; + let test = |term: &str| -> bool { + let term = term.trim(); + let (negated, term) = match term.strip_prefix('!') { + Some(t) => (true, t.trim()), + None => (false, term), + }; + let split = term.find(['=', '~']).unwrap_or(term.len()); + let id = term[..split].trim(); + let id = if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + }; + let present = components.get(&id.as_str().into()); + let result = match term[split..].chars().next() { + Some('=') => { + let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim()) + .ok() + .map(|(t, _)| t); + match (present, value) { + (Some(have), Some(want)) => { + horizon_client::nbt_path::compare_nbt(&want, Some(have)) + && horizon_client::nbt_path::compare_nbt(have, Some(&want)) + } + _ => false, + } + } + Some('~') => { + // Sub-predicates: `count` and component predicates. + let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim()) + .ok() + .map(|(t, _)| t); + match (id.as_str(), value) { + ("minecraft:count", Some(v)) => { + let n = i64::from(stack.count); + match &v { + horizon_world::nbt::Tag::Compound(_) => { + let get = |k: &str| match v.get(k) { + Some(horizon_world::nbt::Tag::Int(i)) => { + Some(i64::from(*i)) + } + _ => None, + }; + get("min").is_none_or(|m| n >= m) + && get("max").is_none_or(|m| n <= m) + } + horizon_world::nbt::Tag::Int(i) => n == i64::from(*i), + _ => false, + } + } + (_, Some(v)) => present.is_some_and(|have| { + horizon_client::nbt_path::compare_nbt(&v, Some(have)) + }), + _ => false, + } + } + _ => present.is_some(), + }; + result != negated + }; + split_top_level(inner, ',') + .iter() + .filter(|t| !t.trim().is_empty()) + .all(|term| split_top_level(term, '|').iter().any(|alt| test(alt))) + } fn cmd_clear(&mut self, ctx: &Context) -> R { let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", true)? @@ -1885,19 +2190,30 @@ impl Game<'_> { // Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried. let mut removed = 0i32; let mut budget = if max < 0 { i32::MAX } else { max }; + let all = |g: &Self| -> Vec> { + let mut v: Vec> = g.inventory.clone(); + v.extend(g.armor.iter().cloned()); + v.extend(g.craft_grid.iter().cloned()); + v.push(g.carried.clone()); + v + }; + let matching: Vec = all(self) + .iter() + .map(|s| { + s.as_ref() + .is_some_and(|s| self.stack_matches(&predicate, s)) + }) + .collect(); let mut slots: Vec<&mut Option> = Vec::new(); slots.extend(self.inventory.iter_mut()); slots.extend(self.armor.iter_mut()); slots.extend(self.craft_grid.iter_mut()); slots.push(&mut self.carried); - for slot in slots { + for (slot, matches) in slots.into_iter().zip(matching) { + if !matches { + continue; + } let Some(stack) = slot.as_mut() else { continue }; - if !(predicate.any || predicate.tag || predicate.id == *stack.item) && !predicate.tag { - continue; - } - if predicate.tag { - continue; - } let take = if counting { stack.count as i32 } else { @@ -1915,35 +2231,6 @@ impl Game<'_> { } } } - if predicate.tag { - // Tag predicates: match against item tags. - let pred = predicate.clone(); - let mut budget = if max < 0 { i32::MAX } else { max }; - let items: Vec<(usize, String, u32)> = self - .inventory - .iter() - .enumerate() - .filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count))) - .collect(); - for (i, item, count) in items { - if !self.item_matches(&pred, &item) { - continue; - } - let take = if counting { - count as i32 - } else { - (count as i32).min(budget) - }; - removed += take; - if !counting && let Some(s) = self.inventory[i].as_mut() { - budget -= take; - s.count -= take as u32; - if s.count == 0 { - self.inventory[i] = None; - } - } - } - } if removed == 0 { return Err(if targets.len() == 1 { CommandError::new(Text::translate( @@ -1964,35 +2251,179 @@ impl Game<'_> { )); Ok(removed) } + /// `PoiTypes`: the point of interest type of a block state. + fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { + let s = self.res.assets.registry.state(state)?; + let name = s.name.strip_prefix("minecraft:")?; + Some(match name { + "blast_furnace" => "minecraft:armorer", + "smoker" => "minecraft:butcher", + "cartography_table" => "minecraft:cartographer", + "brewing_stand" => "minecraft:cleric", + "composter" => "minecraft:farmer", + "barrel" => "minecraft:fisherman", + "fletching_table" => "minecraft:fletcher", + "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { + "minecraft:leatherworker" + } + "lectern" => "minecraft:librarian", + "stonecutter" => "minecraft:mason", + "loom" => "minecraft:shepherd", + "smithing_table" => "minecraft:toolsmith", + "grindstone" => "minecraft:weaponsmith", + "bell" => "minecraft:meeting", + "beehive" => "minecraft:beehive", + "bee_nest" => "minecraft:bee_nest", + "nether_portal" => "minecraft:nether_portal", + "lodestone" => "minecraft:lodestone", + "test_instance_block" => "minecraft:test_instance", + n if n.ends_with("_bed") => { + if s.properties.get("part").map(String::as_str) != Some("head") { + return None; + } + "minecraft:home" + } + n if n.ends_with("lightning_rod") => "minecraft:lightning_rod", + _ => return None, + }) + } + /// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within + /// 256 blocks of the source, over the loaded chunks. + fn cmd_locate_poi(&mut self, ctx: &Context) -> R { + let Some(Arg::Resource(poi)) = ctx.get("poi").cloned() else { + return Ok(0); + }; + let wanted: Vec = match poi.strip_prefix('#') { + Some(tag) => self.tag_entries("point_of_interest_type", tag), + None => vec![poi.clone()], + }; + let from = self.source_position().map(|v| v.floor() as i32); + const RANGE: i32 = 256; + let mut cache: std::collections::HashMap> = + std::collections::HashMap::new(); + let mut best: Option<(i64, [i32; 3], &'static str)> = None; + let (cx0, cz0) = ((from[0] - RANGE) >> 4, (from[2] - RANGE) >> 4); + let (cx1, cz1) = ((from[0] + RANGE) >> 4, (from[2] + RANGE) >> 4); + for cx in cx0..=cx1 { + for cz in cz0..=cz1 { + let Some(chunk) = self.world.chunks.get(&(cx, cz)) else { + continue; + }; + for (i, section) in chunk.sections.iter().enumerate() { + let mut wanted_state = |v: u32| { + let state = v as u16; + cache + .entry(state) + .or_insert_with(|| { + self.poi_type(horizon_world::registry::BlockStateId(u32::from( + state, + ))) + .filter(|t| wanted.iter().any(|w| w == t)) + }) + .is_some() + }; + if !section.blocks.maybe_has(&mut wanted_state) { + continue; + } + let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32; + for j in 0..4096 { + let state = section.get(j); + let Some(kind) = cache.get(&state).copied().flatten() else { + continue; + }; + let p = [ + cx * 16 + (j & 15) as i32, + base_y + (j >> 8) as i32, + cz * 16 + ((j >> 4) & 15) as i32, + ]; + let d = [p[0] - from[0], p[1] - from[1], p[2] - from[2]] + .map(|d| i64::from(d) * i64::from(d)) + .iter() + .sum::(); + if d <= i64::from(RANGE * RANGE) && best.is_none_or(|(b, _, _)| d < b) { + best = Some((d, p, kind)); + } + } + } + } + } + let Some((_, p, kind)) = best else { + return Err(CommandError::new(Text::tr( + "commands.locate.poi.not_found", + &[&poi], + ))); + }; + let coords = Text::translate( + "chat.coordinates", + &[ + Text::literal(p[0].to_string()), + Text::literal("~"), + Text::literal(p[2].to_string()), + ], + ); + let link = Text::literal("[") + .append(coords) + .append("]") + .with_style(&Style { + color: Some(text::GREEN), + suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])), + ..Style::default() + }); + let (dx, dz) = (p[0] - from[0], p[2] - from[2]); + let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32; + let shown = if poi.starts_with('#') { + format!("{poi} ({kind})") + } else { + poi + }; + self.feedback(Text::translate( + "commands.locate.poi.success", + &[ + Text::literal(shown), + link, + Text::literal(distance.to_string()), + ], + )); + Ok(distance) + } fn cmd_locate(&mut self, id: &str, ctx: &Context) -> R { let origin = self.source_position(); if id == "locate.biome" { let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { return Ok(0); }; - // Search loaded chunks around the player (BiomeSource.findClosestBiome3d - // samples a 6400-block radius; Horizon searches what is generated). - let (px, pz) = (origin[0].floor() as i32, origin[2].floor() as i32); - let mut best: Option<([i32; 3], f64)> = None; - for (&(cx, cz), chunk) in &self.world.chunks { - for (dx, dz) in [(0, 0), (8, 8)] { - let (x, z) = (cx * 16 + dx, cz * 16 + dz); - let y = origin[1].floor() as i32; - let b = self.res.biomes.get(chunk.biome(x, y, z)); - if b.name == biome { - let d = f64::from((x - px).pow(2) + (z - pz).pow(2)); - if best.is_none_or(|(_, bd)| d < bd) { - best = Some(([x, y, z], d)); - } - } - } - } - let Some((p, d2)) = best else { + // LocateCommand.locateBiome: BiomeSource.findClosestBiome3d with + // a 6400-block radius, 32-block columns and 64-block layers. + let from = origin.map(|v| v.floor() as i32); + let allowed = |name: &str| self.biome_matches(&biome, name); + let search = horizon_world::worldgen::generator::BiomeSearch { + allowed: &allowed, + origin: from, + radius: 6400, + horizontal: 32, + vertical: 64, + min_y: horizon_client::chunk::MIN_Y, + max_y: horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT - 1, + }; + let found = self + .end + .locator() + .and_then(|t| t.find_closest_biome(&search)); + let Some((name, p)) = found else { return Err(CommandError::new(Text::tr( "commands.locate.biome.not_found", &[&biome], ))); }; + let d2 = [p[0] - from[0], p[1] - from[1], p[2] - from[2]] + .map(|d| f64::from(d) * f64::from(d)) + .iter() + .sum::(); + let shown = if biome.starts_with('#') { + format!("{biome} ({name})") + } else { + biome.clone() + }; let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]); let link = Text::literal("[") .append(coords) @@ -2002,11 +2433,11 @@ impl Game<'_> { suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), ..Style::default() }); - let distance = d2.sqrt().floor() as i32; - self.system_message(Text::translate( + let distance = (d2 as f32).sqrt().floor() as i32; + self.feedback(Text::translate( "commands.locate.biome.success", &[ - Text::literal(biome), + Text::literal(shown), link, Text::literal(distance.to_string()), ], @@ -2064,6 +2495,10 @@ impl Game<'_> { } /// The structures of a `worldgen/structure` tag, nested tags expanded. pub(super) fn structure_tag(&self, tag: &str) -> Vec { + self.tag_entries("worldgen/structure", tag) + } + /// The entries of a data pack tag of `registry`, nested tags expanded. + pub(super) fn tag_entries(&self, registry: &str, tag: &str) -> Vec { let mut out = Vec::new(); let mut pending = vec![tag.to_owned()]; let mut seen = std::collections::HashSet::new(); @@ -2075,7 +2510,7 @@ impl Game<'_> { let file = self .options .resources - .join(format!("data/{ns}/tags/worldgen/structure/{path}.json")); + .join(format!("data/{ns}/tags/{registry}/{path}.json")); let Ok(v) = std::fs::read(file) .map_err(|_| ()) .and_then(|b| serde_json::from_slice::(&b).map_err(|_| ())) @@ -2126,6 +2561,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 @@ -2165,3 +2603,33 @@ impl Game<'_> { out } } + +/// Split at a separator outside brackets, braces and quotes. +fn split_top_level(s: &str, sep: char) -> Vec<&str> { + let mut out = Vec::new(); + let (mut depth, mut quote, mut escaped, mut start) = (0i32, None::, false, 0); + for (i, ch) in s.char_indices() { + if let Some(q) = quote { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == q { + quote = None; + } + continue; + } + match ch { + '"' | '\'' => quote = Some(ch), + '[' | '{' => depth += 1, + ']' | '}' => depth -= 1, + c if c == sep && depth == 0 => { + out.push(&s[start..i]); + start = i + ch.len_utf8(); + } + _ => {} + } + } + out.push(&s[start..]); + out +} diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs new file mode 100644 index 000000000..8ffcfac03 --- /dev/null +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -0,0 +1,542 @@ +//! `/compute` (ComputeCommand): context number providers +//! (`context_int_provider`, `context_float_provider`) evaluated in a loot +//! context of the source, optionally with a block or a target entity. +use super::{Arg, Context, Game, R, Target, err}; +use horizon_client::{command::CommandError, text::Text}; +use horizon_core::random::RandomSource; +use serde_json::Value; + +/// The loot context parameters of `LootContextSources`. +#[derive(Clone, Copy, Default)] +pub(in crate::game) struct ComputeContext { + /// `BLOCK_STATE` (`compute block `). + pub block: Option<[i32; 3]>, + /// `TARGET_ENTITY` (`compute entity `). + pub target: Option, +} + +/// An ArithmeticException's message. +type Arith = String; + +fn java_float(v: f32) -> String { + horizon_client::snbt::java_float(v) +} + +impl Game<'_> { + /// A provider argument: its registry id (None when inline) and value. + pub(in crate::game) fn provider_arg( + &self, + ctx: &Context, + registry: &str, + ) -> R<(Option, Value)> { + let raw = match ctx.get("provider") { + Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(), + _ => return Err(err("command.failed", &[])), + }; + let first = raw.trim_start().chars().next().unwrap_or(' '); + if first == '{' || first == '[' || first == '-' || first.is_ascii_digit() || first == '"' { + let (tag, _) = horizon_world::nbt::parse_snbt(&raw) + .map_err(|e| err("argument.nbt.invalid", &[&e]))?; + return Ok((None, horizon_client::scoreboard::tag_to_json(&tag))); + } + let id = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + let value = self + .provider_file(registry, &id) + .ok_or_else(|| err("argument.resource_or_id.no_such_element", &[&id, ®istry]))?; + Ok((Some(id), value)) + } + /// A registered provider's definition. + fn provider_file(&self, registry: &str, id: &str) -> Option { + let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); + let dir = registry.trim_start_matches("minecraft:"); + let file = self + .options + .resources + .join(format!("data/{ns}/{dir}/{path}.json")); + serde_json::from_slice(&std::fs::read(file).ok()?).ok() + } + /// The compute context the command's source literal selects. + pub(in crate::game) fn compute_context(&mut self, ctx: &Context) -> R { + let mut c = ComputeContext::default(); + if ctx.literals.iter().any(|l| l == "block") && ctx.get("computePos").is_some() { + c.block = Some(self.block_pos_arg(ctx, "computePos")?); + } + if ctx.get("computeTarget").is_some() { + let t = self.entities(ctx, "computeTarget", false)?; + if t.len() > 1 { + return Err(err("argument.entity.toomany", &[])); + } + c.target = t.first().copied(); + } + Ok(c) + } + /// `ComputeCommand.computeAsInt` / `computeAsFloat`. + pub(super) fn cmd_compute(&mut self, ctx: &Context) -> R { + let integer = ctx.literals.iter().any(|l| l == "integer"); + let registry = if integer { + "minecraft:context_int_provider" + } else { + "minecraft:context_float_provider" + }; + let (id, provider) = self.provider_arg(ctx, registry)?; + let c = self.compute_context(ctx)?; + let invalid = |value: String| -> CommandError { + match &id { + Some(id) => CommandError::new(Text::translate( + "command.compute.result.named.invalid", + &[Text::literal(id.clone()), Text::literal(value)], + )), + None => CommandError::new(Text::translate( + "command.compute.result.unnamed.invalid", + &[Text::literal(value)], + )), + } + }; + let exact = |result: i32| match &id { + Some(id) => Text::translate( + "command.compute.result.named.exact", + &[Text::literal(id.clone()), Text::literal(result.to_string())], + ), + None => Text::translate( + "command.compute.result.unnamed.exact", + &[Text::literal(result.to_string())], + ), + }; + if integer { + let result = self.provider_int(&provider, &c, 0).map_err(invalid)?; + self.feedback(exact(result)); + return Ok(result); + } + let scale = match ctx.get("scale") { + Some(Arg::Float(s)) => *s, + _ => 1.0, + }; + let original = self.provider_float(&provider, &c, 0).map_err(invalid)?; + if !original.is_finite() { + return Err(invalid(java_float(original))); + } + // Mth.floor(original * scale) + let result = (original * scale).floor() as i32; + if result as f32 == original { + self.feedback(exact(result)); + } else { + let original_text = Text::literal(java_float(original)); + let message = match &id { + Some(id) => Text::translate( + "command.compute.result.named.rounded", + &[ + Text::literal(id.clone()), + original_text, + Text::literal(result.to_string()), + ], + ), + None => Text::translate( + "command.compute.result.unnamed.rounded", + &[original_text, Text::literal(result.to_string())], + ), + }; + self.feedback(message); + } + Ok(result) + } + + // ---- evaluation --------------------------------------------------------------- + + /// `ContextIntProvider.getIntUnsafe`. + pub(in crate::game) fn provider_int( + &mut self, + v: &Value, + c: &ComputeContext, + depth: u32, + ) -> Result { + if depth > 64 { + return Ok(0); + } + let d = depth + 1; + match v { + Value::Number(n) => Ok(n + .as_i64() + .map_or_else(|| n.as_f64().unwrap_or(0.0) as i32, |i| i as i32)), + Value::Bool(b) => Ok(i32::from(*b)), + Value::String(id) => match self.provider_file("minecraft:context_int_provider", id) { + Some(def) => self.provider_int(&def, c, d), + None => Ok(0), + }, + Value::Object(o) => { + let ty = o + .get("type") + .and_then(Value::as_str) + .unwrap_or("") + .trim_start_matches("minecraft:") + .to_owned(); + let inputs = |g: &mut Self| -> Result, Arith> { + let list: Vec = match o.get("inputs") { + Some(Value::Array(a)) => a.clone(), + Some(other) => vec![other.clone()], + None => Vec::new(), + }; + list.iter().map(|x| g.provider_int(x, c, d)).collect() + }; + let field = |g: &mut Self, k: &str| -> Result { + match o.get(k) { + Some(x) => g.provider_int(x, c, d), + None => Ok(0), + } + }; + let overflow = || "integer overflow".to_owned(); + let long_to_int = |v: i64| -> Result { + i32::try_from(v) + .map_err(|_| format!("Value {v} can't be safely converted to int")) + }; + Ok(match ty.as_str() { + "constant" => field(self, "value")?, + "add" => long_to_int(inputs(self)?.iter().map(|&x| i64::from(x)).sum())?, + "mul" => long_to_int( + inputs(self)? + .iter() + .fold(1i64, |a, &x| a.wrapping_mul(i64::from(x))), + )?, + "avg" => { + let xs = inputs(self)?; + if xs.is_empty() { + return Err("/ by zero".into()); + } + let sum: i64 = xs.iter().map(|&x| i64::from(x)).sum(); + long_to_int(sum / xs.len() as i64)? + } + "max" => inputs(self)?.into_iter().fold(i32::MIN, i32::max), + "min" => inputs(self)?.into_iter().fold(i32::MAX, i32::min), + "sub" => { + let (a, b) = (field(self, "left")?, field(self, "right")?); + a.checked_sub(b).ok_or_else(overflow)? + } + "div" | "mod" | "floor_div" | "floor_mod" => { + let (a, b) = (field(self, "left")?, field(self, "right")?); + if b == 0 { + return Err("/ by zero".into()); + } + match ty.as_str() { + "div" => a.wrapping_div(b), + "mod" => a.wrapping_rem(b), + "floor_mod" => { + a.rem_euclid(b) + if b < 0 && a.rem_euclid(b) != 0 { b } else { 0 } + } + _ => { + if a == i32::MIN && b == -1 { + return Err(overflow()); + } + a.div_euclid(b) - if b < 0 && a.rem_euclid(b) != 0 { 1 } else { 0 } + } + } + } + "pow" => { + let (base, exp) = (field(self, "base")?, field(self, "exponent")?); + if base == 0 && exp == 0 { + return Err("Result of 0 to the power of 0 is undefined".into()); + } + if exp < 0 { + return Err("Negative exponent".into()); + } + base.checked_pow(exp as u32).ok_or_else(overflow)? + } + // Math.absExact's message. + "abs" => field(self, "input")?.checked_abs().ok_or_else(|| { + "Overflow to represent absolute value of Integer.MIN_VALUE".to_owned() + })?, + "negate" => field(self, "input")?.checked_neg().ok_or_else(overflow)?, + "from_float" => { + let f = match o.get("input") { + Some(x) => self.provider_float(x, c, d)?, + None => 0.0, + }; + if !f.is_finite() { + return Err(format!( + "Value {} can't be safely converted to int", + java_float(f) + )); + } + long_to_int(f as i64)? + } + "uniform" => { + let (lo, hi) = (field(self, "min")?, field(self, "max")?); + if lo >= hi { + lo + } else { + self.world.random.next_int_bound(hi - lo + 1).unwrap_or(0) + lo + } + } + "binomial" => { + let n = field(self, "n")?; + let p = match o.get("p") { + Some(x) => self.provider_float(x, c, d)?, + None => 0.0, + }; + (0..n.max(0)) + .filter(|_| self.world.random.next_float() < p) + .count() as i32 + } + "conditional" | "number_dispatcher" | "weighted_list" => { + match self.provider_select(o, c)? { + Some(x) => self.provider_int(&x, c, d)?, + None => 0, + } + } + _ => 0, + }) + } + _ => Ok(0), + } + } + /// `ContextFloatProvider.getFloatUnsafe`. + pub(in crate::game) fn provider_float( + &mut self, + v: &Value, + c: &ComputeContext, + depth: u32, + ) -> Result { + if depth > 64 { + return Ok(0.0); + } + let d = depth + 1; + match v { + Value::Number(n) => Ok(n.as_f64().unwrap_or(0.0) as f32), + Value::String(id) => match self.provider_file("minecraft:context_float_provider", id) { + Some(def) => self.provider_float(&def, c, d), + None => Ok(0.0), + }, + Value::Object(o) => { + let ty = o + .get("type") + .and_then(Value::as_str) + .unwrap_or("") + .trim_start_matches("minecraft:") + .to_owned(); + let inputs = |g: &mut Self| -> Result, Arith> { + let list: Vec = match o.get("inputs") { + Some(Value::Array(a)) => a.clone(), + Some(other) => vec![other.clone()], + None => Vec::new(), + }; + list.iter().map(|x| g.provider_float(x, c, d)).collect() + }; + let field = |g: &mut Self, k: &str| -> Result { + match o.get(k) { + Some(x) => g.provider_float(x, c, d), + None => Ok(0.0), + } + }; + Ok(match ty.as_str() { + "constant" => field(self, "value")?, + "add" => inputs(self)?.iter().fold(0.0f32, |a, &x| a + x), + "mul" => inputs(self)?.iter().fold(1.0f32, |a, &x| a * x), + "avg" => { + let xs = inputs(self)?; + xs.iter().fold(0.0f32, |a, &x| a + x) / xs.len() as f32 + } + "length" => inputs(self)?.iter().fold(0.0f32, |a, &x| a + x * x).sqrt(), + "max" => inputs(self)?.into_iter().fold(-f32::MAX, f32::max), + "min" => inputs(self)?.into_iter().fold(f32::MAX, f32::min), + "sub" => field(self, "left")? - field(self, "right")?, + "div" => field(self, "left")? / field(self, "right")?, + "mod" => { + let right = field(self, "right")?; + if right == 0.0 { + f32::NAN + } else { + field(self, "left")? % right + } + } + "pow" => { + let (base, exp) = (field(self, "base")?, field(self, "exponent")?); + if base == 0.0 && exp == 0.0 { + f32::NAN + } else { + f64::from(base).powf(f64::from(exp)) as f32 + } + } + "abs" => field(self, "input")?.abs(), + "negate" => -field(self, "input")?, + "floor" => field(self, "input")?.floor(), + // Mth.ceil returns an int. + "ceil" => field(self, "input")?.ceil() as i32 as f32, + // Math.round(float): floor(x + 0.5) as int. + "round" => (field(self, "input")? + 0.5).floor() as i32 as f32, + "truncate" => field(self, "input")?.trunc(), + "sqrt" => field(self, "input")?.sqrt(), + "sin" => horizon_core::geometry::trig::sin(f64::from(field(self, "input")?)), + "cos" => horizon_core::geometry::trig::cos(f64::from(field(self, "input")?)), + "from_int" => match o.get("input") { + Some(x) => self.provider_int(x, c, d)? as f32, + None => 0.0, + }, + "uniform" => { + let (lo, hi) = (field(self, "min")?, field(self, "max")?); + if lo >= hi { + lo + } else { + self.world.random.next_float() * (hi - lo) + lo + } + } + "conditional" | "number_dispatcher" | "weighted_list" => { + match self.provider_select(o, c)? { + Some(x) => self.provider_float(&x, c, d)?, + None => 0.0, + } + } + _ => 0.0, + }) + } + _ => Ok(0.0), + } + } + /// The branch a conditional, dispatcher or weighted list provider picks. + fn provider_select( + &mut self, + o: &serde_json::Map, + c: &ComputeContext, + ) -> Result, Arith> { + match o + .get("type") + .and_then(Value::as_str) + .map(|t| t.trim_start_matches("minecraft:")) + { + Some("conditional") => { + let holds = o + .get("condition") + .is_some_and(|x| self.compute_condition(x, c)); + Ok(if holds { + o.get("on_true").cloned() + } else { + Some(o.get("on_false").cloned().unwrap_or(Value::from(0))) + }) + } + Some("number_dispatcher") => { + for case in o + .get("cases") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + if case + .get("condition") + .is_some_and(|x| self.compute_condition(x, c)) + { + return Ok(case.get("value").cloned()); + } + } + Ok(Some(o.get("default").cloned().unwrap_or(Value::from(0)))) + } + _ => { + // WeightedList.getRandomOrThrow. + let list: Vec<(Value, i32)> = o + .get("distribution") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|e| { + ( + e.get("data").cloned().unwrap_or(Value::Null), + e.get("weight").and_then(Value::as_i64).unwrap_or(1) as i32, + ) + }) + .collect(); + let total: i32 = list.iter().map(|(_, w)| *w).sum(); + if total <= 0 { + return Ok(None); + } + let mut pick = self.world.random.next_int_bound(total).unwrap_or(0); + for (v, w) in list { + pick -= w; + if pick < 0 { + return Ok(Some(v)); + } + } + Ok(None) + } + } + } + /// A loot condition in the compute context: references, the logical + /// combinators and `match_block` on the context's block state. + fn compute_condition(&mut self, cond: &Value, c: &ComputeContext) -> bool { + match cond { + Value::String(id) => match self.provider_file("minecraft:predicate", id) { + Some(def) => self.compute_condition(&def, c), + None => false, + }, + Value::Array(list) => list.iter().all(|x| self.compute_condition(x, c)), + Value::Object(o) => { + let ty = o + .get("type") + .or_else(|| o.get("condition")) + .and_then(Value::as_str) + .unwrap_or("") + .trim_start_matches("minecraft:"); + match ty { + "inverted" => !o.get("term").is_some_and(|x| self.compute_condition(x, c)), + "all_of" => o + .get("terms") + .and_then(Value::as_array) + .into_iter() + .flatten() + .all(|x| self.compute_condition(x, c)), + "any_of" => o + .get("terms") + .and_then(Value::as_array) + .into_iter() + .flatten() + .any(|x| self.compute_condition(x, c)), + "match_block" | "block_state_property" => { + let Some(p) = c.block else { + return false; + }; + let state = self.world.block(p[0], p[1], p[2]); + let Some(s) = self.res.assets.registry.state(state) else { + return false; + }; + let name = s.name.to_string(); + let blocks_ok = match o.get("blocks").or_else(|| o.get("block")) { + Some(Value::String(b)) => match b.strip_prefix('#') { + Some(tag) => self + .res + .items + .block_tags + .get(tag.trim_start_matches("minecraft:")) + .is_some_and(|set| { + set.contains(&*name) + || set.contains(name.trim_start_matches("minecraft:")) + }), + None => *b == name, + }, + Some(Value::Array(list)) => { + list.iter().any(|b| b.as_str() == Some(&name)) + } + _ => true, + }; + let props_ok = o + .get("state") + .or_else(|| o.get("properties")) + .and_then(Value::as_object) + .into_iter() + .flatten() + .all(|(k, v)| s.properties.get(k).map(String::as_str) == v.as_str()); + blocks_ok && props_ok + } + "random_chance" => { + let chance = o.get("chance").and_then(Value::as_f64).unwrap_or(0.0) as f32; + self.world.random.next_float() < chance + } + _ => { + let source = self.command_source.unwrap_or_else(|| self.player_source()); + let view = source.entity.map(|t| self.entity_view_of(t)); + self.conditions_hold(cond, view.as_ref(), source.pos) + } + } + } + _ => false, + } + } +} diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 85d298f8f..3398aa7dd 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -42,6 +42,21 @@ impl Game<'_> { if let Some(u) = player_uuid { set_key(&mut tag, "UUID", Tag::IntArray(u.to_vec())); } + // NbtPredicate.getEntityTagToCompare: a player's held stack. + let selected = self.level.selected_slot; + let held = match tag.get("Inventory") { + Some(Tag::List(items)) => items + .iter() + .find(|i| matches!(i.get("Slot"), Some(Tag::Byte(b)) if i32::from(*b) == selected)) + .cloned(), + _ => None, + }; + if let Some(mut stack) = held { + if let Tag::Compound(c) = &mut stack { + c.remove(&"Slot".into()); + } + set_key(&mut tag, "SelectedItem", stack); + } tag } Target::Mob(id) => { @@ -87,6 +102,11 @@ impl Game<'_> { let c = self.carts.iter().find(|c| c.id == id)?; c.to_nbt(uuid, self.persist.raw.get(&id)) } + Target::Other(id) => { + let uuid = self.uuid_for(id); + let o = self.others.iter().find(|o| o.id == id)?.clone(); + self.other_to_nbt(&o, uuid) + } Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()), Target::Arrow(i) => { let a = self.arrows.get(i)?; @@ -166,7 +186,8 @@ impl Game<'_> { | Target::Frame(id) | Target::Painting(id) | Target::Boat(id) - | Target::Cart(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)), + | Target::Cart(id) + | Target::Other(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)), _ => None, } } @@ -226,9 +247,16 @@ impl Game<'_> { } pub(in crate::game) fn data_of(&mut self, r: &DataRef) -> R { match r { - DataRef::Entity(t) => self - .entity_nbt(*t) - .ok_or_else(|| err("argument.entity.notfound.entity", &[])), + // EntityDataAccessor.getData: Entity.saveWithoutId. + DataRef::Entity(t) => { + let mut tag = self + .entity_nbt(*t) + .ok_or_else(|| err("argument.entity.notfound.entity", &[]))?; + if let Tag::Compound(c) = &mut tag { + c.remove(&"id".into()); + } + Ok(tag) + } DataRef::Block(p) => { let key = (p[0], p[1], p[2]); let name = self.data_block_name(*p); @@ -237,7 +265,12 @@ impl Game<'_> { .block_entities .get(&key) .ok_or_else(|| err("commands.data.block.invalid", &[]))?; - Ok(save::encode_block_entity(key, e, &name)) + // BlockEntity.saveWithFullMetadata: no chunk-only keepPacked. + let mut tag = save::encode_block_entity(key, e, &name); + if let Tag::Compound(c) = &mut tag { + c.remove(&"keepPacked".into()); + } + Ok(tag) } DataRef::Storage(id) => Ok(self.score.storage.get(id)), } @@ -626,10 +659,11 @@ impl Game<'_> { }; self.world.loaded_entities.push((key, vec![tag])); self.spawn_loaded_entities(); - let id = self.next_entity; - if id == before { + if self.next_entity == before { return None; } + // The root of the stack is the first entity spawned. + let id = before + 1; if self.mobs.iter().any(|m| m.id == id) { Some(Target::Mob(id)) } else if self.dropped.iter().any(|e| e.id == id) { @@ -644,6 +678,8 @@ impl Game<'_> { Some(Target::Boat(id)) } else if self.carts.iter().any(|c| c.id == id) { Some(Target::Cart(id)) + } else if self.others.iter().any(|o| o.id == id) { + Some(Target::Other(id)) } else { None } @@ -660,18 +696,36 @@ impl Game<'_> { return Err(err("argument.nbt.expected.compound", &[])); } set_key(&mut tag, "id", Tag::String(kind.into())); - let p = pos.map(|v| Tag::Double(v.to_bits())); - set_key(&mut tag, "Pos", Tag::List(p.to_vec())); - if tag.get("Rotation").is_none() { - set_key( - &mut tag, - "Rotation", - Tag::List(vec![ - Tag::Float(0.0f32.to_bits()), - Tag::Float(0.0f32.to_bits()), - ]), - ); + // EntityType.loadEntityRecursive snaps every entity of the stack, + // passengers included, to the position. + fn place(tag: &mut Tag, pos: [f64; 3]) { + let p = pos.map(|v| Tag::Double(v.to_bits())); + set_key(tag, "Pos", Tag::List(p.to_vec())); + // Entity.load: an absent Fire reads as 0 (until the entity moves). + if tag.get("Fire").is_none() { + set_key(tag, "Fire", Tag::Short(0)); + } + if tag.get("Rotation").is_none() { + set_key( + tag, + "Rotation", + Tag::List(vec![ + Tag::Float(0.0f32.to_bits()), + Tag::Float(0.0f32.to_bits()), + ]), + ); + } + if let Tag::Compound(c) = tag + && let Some(Tag::List(riders)) = c.get_mut(&"Passengers".into()) + { + for r in riders { + if matches!(r, Tag::Compound(_)) { + place(r, pos); + } + } + } } + place(&mut tag, pos); Ok(self.spawn_entity_from_nbt(tag)) } } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 2fda44bfe..a913b07c5 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -23,6 +23,9 @@ pub(in crate::game) struct Source { pub silent: bool, /// Index of the newest `store` in `ExecState::stores`. pub store: Option, + /// `execute in` another dimension than the one Horizon has loaded: none + /// of its chunks are loaded. + pub elsewhere: bool, } /// Where `execute store` writes. @@ -70,6 +73,7 @@ impl Game<'_> { eyes: false, silent: false, store: None, + elsewhere: false, } } /// The server as a source (function ticks and schedules): the world spawn. @@ -81,6 +85,7 @@ impl Game<'_> { eyes: false, silent: true, store: None, + elsewhere: false, } } pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] { @@ -106,6 +111,11 @@ impl Game<'_> { .iter() .find(|c| c.id == id) .map_or([0.0; 2], |c| [c.yaw, 0.0]), + Target::Other(id) => self + .others + .iter() + .find(|o| o.id == id) + .map_or([0.0; 2], |o| [o.yaw, o.pitch]), _ => [0.0; 2], } } @@ -147,7 +157,7 @@ impl Game<'_> { /// Run one command line with `source` (no error reporting): the entry /// for functions and `execute run`. pub(in crate::game) fn execute_line(&mut self, line: &str, source: Source) -> R { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let parse = d.parse(line, &self.ui.registries); let (ctx, _) = parse.executable()?; let ctx = ctx.clone(); @@ -189,6 +199,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 { @@ -235,6 +251,10 @@ impl Game<'_> { pub(in crate::game) fn run_execute(&mut self, ctx: &Context) -> R { let mut sources = vec![self.command_source.unwrap_or_else(|| self.player_source())]; let mut c = ctx; + // A fork modifier (as, at, positioned as, rotated as, facing entity, + // on, a non-terminal if/unless) makes later errors silent + // (CommandSourceStack.handleError with `forked`). + let mut forked = false; loop { let word = c .literals @@ -257,7 +277,8 @@ impl Game<'_> { for s in sources { match self.with_source(s, |g| g.run_chain(command, last)) { Ok(n) => total += n, - // Forked executions report failures and carry on. + Err(_) if forked => {} + // Several sources: report each failure and carry on. Err(e) if many => self.command_failure(e.message), Err(e) => failure = Some(e), } @@ -275,6 +296,7 @@ impl Game<'_> { if c.child.is_none() { return self.run_conditional_terminal(c, sources, want); } + forked = true; let mut kept = Vec::new(); for s in sources { let (keep, _) = self.with_source(s, |g| g.condition(c, want))?; @@ -285,6 +307,12 @@ impl Game<'_> { sources = kept; } _ => { + forked |= match word { + "as" | "at" | "on" => true, + "positioned" | "rotated" => c.has("as"), + "facing" => c.has("entity"), + _ => false, + }; let mut next = Vec::new(); for s in sources { next.extend(self.with_source(s, |g| g.modify(word, c, s))?); @@ -407,6 +435,7 @@ impl Game<'_> { Some(Source { pos: self.target_position(t)?, rot: self.target_rotation(t), + elsewhere: false, ..s }) }) @@ -497,14 +526,21 @@ impl Game<'_> { ..s }], "in" => { - // Horizon keeps one dimension loaded; others cannot be a source. + // Horizon keeps one dimension loaded: in another one, no + // chunk is loaded (as in vanilla without a player there). let Some(Arg::Resource(dim)) = c.get("dimension") else { return Ok(vec![s]); }; - if dim != self.dim.id() { + if !matches!( + dim.as_str(), + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) { return Err(err("argument.dimension.invalid", &[dim])); } - vec![s] + vec![Source { + elsewhere: dim != self.dim.id(), + ..s + }] } "summon" => { let Some(Arg::Resource(kind)) = c.get("entity").cloned() else { 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..0b437d692 --- /dev/null +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -0,0 +1,1037 @@ +//! 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, + /// `/datapack disable vanilla` took the built-in pack out of the selection. + pub vanilla_disabled: bool, + /// The waypoint manager's tracked transmitters (None until first used). + pub waypoints: Option>, + /// Entities whose waypoint transmit range changed since they last ticked. + pub waypoint_dirty: Vec, + /// Attribute maps of living entities whose attributes Horizon does not + /// model (an armor stand's, a mob's beyond its modelled three). + pub attributes: HashMap, + /// 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)], + )); + } + // EntityType.clientTrackingRange: only a marker's is zero. + if let Some(t) = target + && self.target_type(t) == "minecraft:marker" + { + return Err(tr_error( + "commands.spectate.cannot_spectate", + &[self.target_name(t)], + )); + } + 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(); + self.tick_waypoints(); + } + /// 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 ------------------------------------------------------ + + /// A living entity's `waypoint_transmit_range` (`isTransmittingWaypoint`). + fn transmit_range(&mut self, t: Target) -> f64 { + if t == Target::Player { + return self + .player + .as_mut() + .and_then(|p| { + let k = p.attributes.key("minecraft:waypoint_transmit_range")?; + p.attributes + .value(Some(k), horizon_world::attribute_map::ValueKind::Computed) + .ok() + }) + .unwrap_or(0.0); + } + let catalog = self.motion.attributes.clone(); + let Some(key) = catalog.id("minecraft:waypoint_transmit_range") else { + return 0.0; + }; + match self.cmds.attributes.get_mut(&t) { + Some(map) => map.value(key).unwrap_or(0.0), + None => 0.0, + } + } + /// `ServerWaypointManager.transmitters()`: the tracked set. The player + /// joins tracked when transmitting; a changed range takes effect when the + /// entity next ticks (`LivingEntity.onAttributeUpdated`), and + /// `/waypoint modify` re-tracks its waypoint whatever its range. + fn waypoint_transmitters(&mut self) -> Vec { + if self.cmds.waypoints.is_none() { + let tracked = if self.transmit_range(Target::Player) > 0.0 { + vec![Target::Player] + } else { + Vec::new() + }; + self.cmds.waypoints = Some(tracked); + } + let tracked = self.cmds.waypoints.clone().unwrap_or_default(); + let alive: Vec = tracked + .into_iter() + .filter(|t| self.target_position(*t).is_some()) + .collect(); + self.cmds.waypoints = Some(alive.clone()); + alive + } + /// The waypoint part of a living entity's tick: dirty transmit ranges + /// track or untrack it. + pub(in crate::game) fn tick_waypoints(&mut self) { + let dirty = std::mem::take(&mut self.cmds.waypoint_dirty); + if dirty.is_empty() { + return; + } + self.waypoint_transmitters(); + for t in dirty { + let on = self.transmit_range(t) > 0.0; + if let Some(tracked) = self.cmds.waypoints.as_mut() { + tracked.retain(|x| *x != t); + if on { + tracked.push(t); + } + } + } + } + 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); + // WaypointCommand.mutateIcon: untrack, change, track again. + self.waypoint_transmitters(); + if let Some(tracked) = self.cmds.waypoints.as_mut() { + tracked.retain(|x| *x != t); + tracked.push(t); + } + 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) + } + + // ---- /test ---------------------------------------------------------- + + /// `TestCommand`. Horizon has no game test instances or test runner: every + /// finder comes back empty, as in a world without test instance blocks. + pub(super) fn cmd_test(&mut self, id: &str, ctx: &Context) -> R { + match id { + // run , runmultiple, verify: GameTestRunner. + "test.run" | "test.verify" | "test.create" => Err(err("command.failed", &[])), + // runthese/runclosest/runthat/runfailed: TestFinder finds nothing. + "test.run.found" => { + if ctx.literals.iter().any(|l| l == "runthat") { + self.source_player()?; + } + self.feedback(Text::translate("commands.test.no_tests", &[])); + Ok(0) + } + // reset*/clear*: TestCommand.reset throws CLEAR_NO_TESTS too. + "test.clear" => { + if ctx + .literals + .iter() + .any(|l| l == "resetthat" || l == "clearthat") + { + self.source_player()?; + } + Err(err("commands.test.clear.error.no_tests", &[])) + } + "test.stop" => Ok(1), + "test.locate" => { + // CommandSourceStack.sendSystemMessage: no feedback rule. + if !self.command_source.is_some_and(|s| s.silent) { + self.system_message(Text::translate("commands.test.locate.started", &[])); + } + Err(err("commands.test.error.no_test_instances", &[])) + } + _ => { + // TestCommand.showPos: the block the player looks at (10 blocks). + self.source_player()?; + let p = self.test_pick_block(); + Err(err( + "commands.test.error.no_test_containing_pos", + &[&p[0], &p[1], &p[2]], + )) + } + } + } + /// `Entity.pick(10, 1, false)`: the first non-air block on the view ray, + /// else the block at the ray's end. + fn test_pick_block(&self) -> [i32; 3] { + use horizon_core::{ + geometry::{Vec3, traverse_blocks}, + position::BlockPos, + }; + let Some(p) = self.player.as_ref() else { + return [0; 3]; + }; + let eye = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ); + let (yaw, pitch) = ( + f64::from(self.yaw).to_radians(), + f64::from(self.pitch).to_radians(), + ); + let dir = [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ]; + let end = Vec3::new( + eye.x + dir[0] * 10.0, + eye.y + dir[1] * 10.0, + eye.z + dir[2] * 10.0, + ); + let hit = traverse_blocks(eye, end, 256, |b: BlockPos| { + let state = self.world.block(b.x, b.y, b.z); + (!self.res.facts.is_air(state)).then_some([b.x, b.y, b.z]) + }); + hit.ok().flatten().unwrap_or([ + end.x.floor() as i32, + end.y.floor() as i32, + end.z.floor() as i32, + ]) + } + + // ---- /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-