From c048369be8096ac4e1887e3bea2fbc2c54a3183f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:26:35 +0200 Subject: [PATCH] Complete /execute and add functions, bossbars, items and tick /execute now has every vanilla subcommand: store (result or success into scores, boss bars and entity, block or storage data with a type and scale), positioned over a heightmap, summon, on (owner, vehicle, controller, passengers, target, attacker), and the if/unless conditions score (all comparisons and matches), blocks, biome, predicate, function, data, items and slots on top of block, entity, loaded and dimension, with the vanilla pass, fail and count messages. Data packs in the world's datapacks folder (folders and zips) provide functions with comments, line continuation and $ macros, function tags including minecraft:load and minecraft:tick, and predicates; /function (with arguments or "with" sources), /return (value, fail and run), /schedule, /reload and /datapack list, enable and disable work against them. Also added: /bossbar with a boss bar overlay and saving, /item replace, fill and override over player, mob, armor stand, item frame and container slots, /random and /teammsg, and /tick rate, freeze, step and sprint on the game clock. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/bossbar.rs | 182 +++++ crates/horizon-client/src/clock.rs | 151 +++- crates/horizon-client/src/command/args.rs | 122 +++ crates/horizon-client/src/command/mod.rs | 2 + crates/horizon-client/src/command/tests.rs | 110 +++ .../src/command/tree_execute.rs | 232 ++++++ .../horizon-client/src/command/tree_misc.rs | 257 ++++++ crates/horizon-client/src/command/vanilla.rs | 62 +- crates/horizon-client/src/datapack.rs | 492 ++++++++++++ crates/horizon-client/src/game.rs | 90 ++- .../horizon-client/src/game/advancements.rs | 36 + crates/horizon-client/src/game/bossbars.rs | 404 ++++++++++ crates/horizon-client/src/game/commands.rs | 44 +- .../horizon-client/src/game/commands/data.rs | 18 +- .../src/game/commands/execute.rs | 729 ++++++++++++++++-- .../horizon-client/src/game/commands/items.rs | 483 ++++++++++++ .../horizon-client/src/game/commands/misc.rs | 274 +++++++ crates/horizon-client/src/game/functions.rs | 668 ++++++++++++++++ crates/horizon-client/src/game/scoreboard.rs | 17 +- crates/horizon-client/src/lib.rs | 3 + crates/horizon-client/src/random_sequences.rs | 107 +++ 21 files changed, 4314 insertions(+), 169 deletions(-) create mode 100644 crates/horizon-client/src/bossbar.rs create mode 100644 crates/horizon-client/src/command/tree_execute.rs create mode 100644 crates/horizon-client/src/command/tree_misc.rs create mode 100644 crates/horizon-client/src/datapack.rs create mode 100644 crates/horizon-client/src/game/bossbars.rs create mode 100644 crates/horizon-client/src/game/commands/items.rs create mode 100644 crates/horizon-client/src/game/commands/misc.rs create mode 100644 crates/horizon-client/src/game/functions.rs create mode 100644 crates/horizon-client/src/random_sequences.rs diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs new file mode 100644 index 000000000..9df17431c --- /dev/null +++ b/crates/horizon-client/src/bossbar.rs @@ -0,0 +1,182 @@ +//! Custom boss bars (`CustomBossEvents`): the `/bossbar` store, its saved +//! form (`data/minecraft/custom_boss_events.dat`) and how a bar is shown. +use crate::{ + scoreboard::{Comp, bracketed, comp_text, json_to_tag, literal, tag_to_json}, + text::{self, Style, Text}, +}; +use horizon_world::nbt::{Compound, Tag}; + +pub const COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"]; +pub const STYLES: [&str; 5] = [ + "progress", + "notched_6", + "notched_10", + "notched_12", + "notched_20", +]; +/// `BossBarColor.getFormatting`. +pub fn color_rgb(color: &str) -> u32 { + let name = match color { + "pink" => "red", + "red" => "dark_red", + "purple" => "dark_purple", + other => other, + }; + text::named_color(name).unwrap_or(text::WHITE) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BossBar { + pub id: String, + pub name: Comp, + pub color: String, + pub style: String, + pub value: i32, + pub max: i32, + pub visible: bool, + /// Whether the (single) local player is in the bar's player set. + pub player: bool, +} +impl BossBar { + pub fn new(id: &str, name: Comp) -> Self { + Self { + id: id.to_owned(), + name, + color: "white".into(), + style: "progress".into(), + value: 0, + max: 100, + visible: false, + player: false, + } + } + /// `CustomBossEvent.getDisplayName`. + pub fn display_name(&self) -> Text { + let style = Style { + color: Some(color_rgb(&self.color)), + hover: Some(Box::new(Text::literal(self.id.clone()))), + ..Style::default() + }; + bracketed(comp_text(&self.name).with_style(&style)) + } + /// The filled fraction of the bar (`BossEvent.getProgress`). + pub fn progress(&self) -> f32 { + (self.value as f32 / self.max.max(1) as f32).clamp(0.0, 1.0) + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BossBars { + pub bars: Vec, +} +impl BossBars { + pub fn get(&self, id: &str) -> Option<&BossBar> { + self.bars.iter().find(|b| b.id == id) + } + pub fn get_mut(&mut self, id: &str) -> Option<&mut BossBar> { + self.bars.iter_mut().find(|b| b.id == id) + } + pub fn add(&mut self, id: &str, name: Comp) -> bool { + if self.get(id).is_some() { + return false; + } + self.bars.push(BossBar::new(id, name)); + true + } + pub fn remove(&mut self, id: &str) { + self.bars.retain(|b| b.id != id); + } + pub fn ids(&self) -> Vec { + self.bars.iter().map(|b| b.id.clone()).collect() + } + /// The saved compound; the player's UUID stands for "the local player". + pub fn pack(&self, player: Option<[i32; 4]>) -> Tag { + let mut c = Compound::new(); + for b in &self.bars { + let mut e = vec![ + ("Name", json_to_tag(&b.name)), + ("Visible", Tag::Byte(i8::from(b.visible))), + ("Value", Tag::Int(b.value)), + ("Max", Tag::Int(b.max)), + ("Color", Tag::String(b.color.as_str().into())), + ("Overlay", Tag::String(b.style.as_str().into())), + ("DarkenScreen", Tag::Byte(0)), + ("PlayBossMusic", Tag::Byte(0)), + ("CreateWorldFog", Tag::Byte(0)), + ]; + let players = match (b.player, player) { + (true, Some(u)) => vec![Tag::IntArray(u.to_vec())], + _ => Vec::new(), + }; + e.push(("Players", Tag::List(players))); + c.insert(b.id.as_str().into(), Tag::compound(e)); + } + Tag::Compound(c) + } + pub fn unpack(data: &Tag, player: Option<[i32; 4]>) -> Self { + let mut bars = Vec::new(); + if let Tag::Compound(c) = data { + for (id, e) in c { + let get = |k: &str| e.get(k); + let text = |k: &str, d: &str| match get(k) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => d.to_owned(), + }; + let num = |k: &str, d: i32| match get(k) { + Some(Tag::Int(v)) => *v, + Some(Tag::Short(v)) => i32::from(*v), + Some(Tag::Byte(v)) => i32::from(*v), + _ => d, + }; + let in_players = match (get("Players"), player) { + (Some(Tag::List(l)), Some(u)) => l + .iter() + .any(|t| matches!(t, Tag::IntArray(a) if a.as_slice() == u)), + _ => false, + }; + bars.push(BossBar { + id: id.to_string_lossy(), + name: get("Name").map_or_else(|| literal(""), tag_to_json), + color: text("Color", "white"), + style: text("Overlay", "progress"), + value: num("Value", 0), + max: num("Max", 100), + visible: num("Visible", 0) != 0, + player: in_players, + }); + } + } + Self { bars } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bars_round_trip_and_show() { + let mut b = BossBars::default(); + assert!(b.add("test:x", literal("Hello"))); + assert!(!b.add("test:x", literal("Again"))); + let bar = b.get_mut("test:x").unwrap(); + bar.color = "pink".into(); + bar.style = "notched_10".into(); + bar.value = 25; + bar.max = 50; + bar.visible = true; + bar.player = true; + let uuid = Some([1, 2, 3, 4]); + let back = BossBars::unpack(&b.pack(uuid), uuid); + assert_eq!(back, b); + // Another player's UUID does not include the local player. + assert!(!BossBars::unpack(&b.pack(uuid), Some([9, 9, 9, 9])).bars[0].player); + let bar = b.get("test:x").unwrap(); + assert_eq!(bar.progress(), 0.5); + assert_eq!(bar.display_name().plain(), "chat.square_brackets"); + assert_eq!(color_rgb("pink"), text::RED); + assert_eq!(color_rgb("purple"), 0xAA00AA); + b.remove("test:x"); + assert!(b.bars.is_empty()); + } +} diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 874fec656..835d0e009 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -1,24 +1,136 @@ //! Fixed-rate development simulation driver. Rendering consumes elapsed time; //! a per-frame work cap retains its backlog instead of dropping simulation time. +//! The rate, freezing, stepping and sprinting are what `/tick` controls +//! (`ServerTickRateManager`). use std::time::Duration; pub const TICK: Duration = Duration::from_millis(50); -#[derive(Default)] +/// Ticks one sprint frame may run. +const SPRINT_PER_FRAME: u32 = 40; +const SAMPLES: usize = 100; + pub struct FixedStep { pending: Duration, + /// Ticks per second (`tickrate`). + rate: f32, + frozen: bool, + /// Ticks the frozen world still runs (`/tick step`). + step: u32, + /// Ticks left in a sprint. + sprint: u32, + /// How long recent ticks took (nanoseconds), newest last. + samples: Vec, +} +impl Default for FixedStep { + fn default() -> Self { + Self { + pending: Duration::ZERO, + rate: 20.0, + frozen: false, + step: 0, + sprint: 0, + samples: Vec::new(), + } + } } impl FixedStep { + /// The length of one tick at the current rate. + pub fn tick_duration(&self) -> Duration { + Duration::from_secs_f64(1.0 / f64::from(self.rate.max(0.01))) + } pub fn advance(&mut self, elapsed: Duration) -> u32 { + if self.sprint > 0 { + let n = self.sprint.min(SPRINT_PER_FRAME); + self.sprint -= n; + self.pending = Duration::ZERO; + return n; + } self.pending += elapsed; - let steps = (self.pending.as_nanos() / TICK.as_nanos()).min(10) as u32; - self.pending -= TICK * steps; + let tick = self.tick_duration(); + let steps = (self.pending.as_nanos() / tick.as_nanos().max(1)).min(10) as u32; + self.pending -= tick * steps; steps } pub fn reset(&mut self) { self.pending = Duration::ZERO; } pub fn fraction(&self) -> f64 { - (self.pending.as_secs_f64() / TICK.as_secs_f64()).min(1.0) + (self.pending.as_secs_f64() / self.tick_duration().as_secs_f64()).min(1.0) + } + /// Whether the world ticks this time (`ServerTickRateManager.runsNormally` + /// or a pending step); called once per tick. + pub fn world_runs(&mut self) -> bool { + if !self.frozen { + return true; + } + if self.step > 0 { + self.step -= 1; + return true; + } + false + } + pub fn rate(&self) -> f32 { + self.rate + } + pub fn set_rate(&mut self, rate: f32) { + self.rate = rate.clamp(1.0, 10000.0); + } + pub fn frozen(&self) -> bool { + self.frozen + } + pub fn set_frozen(&mut self, frozen: bool) { + self.frozen = frozen; + if !frozen { + self.step = 0; + } + } + pub fn sprinting(&self) -> bool { + self.sprint > 0 + } + /// `requestGameToSprint`: true when a sprint was already running. + pub fn start_sprint(&mut self, ticks: u32) -> bool { + let was = self.sprint > 0; + self.sprint = ticks; + was + } + pub fn stop_sprint(&mut self) -> bool { + let was = self.sprint > 0; + self.sprint = 0; + was + } + pub fn stepping(&self) -> bool { + self.step > 0 + } + /// `stepGameIfPaused`: only works while frozen. + pub fn start_step(&mut self, ticks: u32) -> bool { + if !self.frozen { + return false; + } + self.step = ticks; + true + } + pub fn stop_step(&mut self) -> bool { + let was = self.step > 0; + self.step = 0; + was + } + pub fn record(&mut self, took: Duration) { + if self.samples.len() == SAMPLES { + self.samples.remove(0); + } + self.samples.push(took.as_nanos() as u64); + } + pub fn average_nanos(&self) -> u64 { + if self.samples.is_empty() { + return 0; + } + self.samples.iter().sum::() / self.samples.len() as u64 + } + /// The sorted tick times (p50, p95, p99 inputs) and their count. + pub fn sorted_samples(&self) -> Vec { + let mut v = self.samples.clone(); + v.sort_unstable(); + v } } @@ -60,4 +172,35 @@ mod tests { assert_eq!(clock.advance(Duration::from_millis(26)), 0); assert_eq!(clock.advance(Duration::from_millis(24)), 1); } + #[test] + fn rate_changes_the_tick_length() { + let mut clock = FixedStep::default(); + clock.set_rate(40.0); + assert_eq!(clock.advance(Duration::from_millis(100)), 4); + clock.set_rate(5.0); + assert_eq!(clock.advance(Duration::from_millis(400)), 2); + clock.set_rate(1.0e9); + assert_eq!(clock.rate(), 10000.0); + } + #[test] + fn freeze_step_and_sprint() { + let mut clock = FixedStep::default(); + assert!(clock.world_runs()); + assert!(!clock.start_step(3), "stepping needs a frozen game"); + clock.set_frozen(true); + assert!(!clock.world_runs()); + assert!(clock.start_step(2)); + assert!(clock.world_runs() && clock.world_runs() && !clock.world_runs()); + assert!(clock.start_step(5) && clock.stop_step() && !clock.stop_step()); + clock.set_frozen(false); + assert!(!clock.start_sprint(100)); + assert!(clock.sprinting()); + assert_eq!(clock.advance(Duration::ZERO), SPRINT_PER_FRAME); + assert!(clock.stop_sprint() && !clock.sprinting()); + for ns in [3, 1, 2] { + clock.record(Duration::from_nanos(ns)); + } + assert_eq!(clock.average_nanos(), 2); + assert_eq!(clock.sorted_samples(), vec![1, 2, 3]); + } } diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index fbb810109..0e5296d15 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -37,6 +37,13 @@ pub struct Registries { pub functions: Vec, /// `/data ... storage` ids. pub storages: Vec, + /// Boss bar ids and datapack predicate ids. + pub bossbars: Vec, + pub predicates: Vec, + pub schedules: Vec, + pub random_sequences: Vec, + pub datapacks_enabled: Vec, + pub datapacks_disabled: Vec, pub function_tags: Vec, /// The block the source is looking at (relevant coordinates). pub target_block: Option<[i32; 3]>, @@ -147,7 +154,65 @@ pub enum ArgType { NbtPath, /// NbtTagArgument: any SNBT value (kept as text). NbtTag, + /// One of a fixed set of words. + Enum(&'static [&'static str]), + /// A (possibly quoted) name suggested from a registry list. + Name(&'static str), + /// FunctionArgument: `ns:path`, or `#ns:path` for a function tag. + Function, + /// SlotsArgument: a slot name or a wildcard group (`container.*`). + Slots, + /// SlotArgument: one slot (`container.5`, `weapon.mainhand`). + Slot, } + +/// Every slot name a command can address (`SlotRanges`), without wildcards. +pub fn slot_names() -> Vec { + let mut v: Vec = Vec::new(); + let mut range = |prefix: &str, n: usize| { + for i in 0..n { + v.push(format!("{prefix}.{i}")); + } + }; + range("container", 54); + range("hotbar", 9); + range("inventory", 27); + range("enderchest", 27); + range("villager", 8); + range("horse", 15); + range("player.crafting", 4); + for name in [ + "weapon", + "weapon.mainhand", + "weapon.offhand", + "armor.head", + "armor.chest", + "armor.legs", + "armor.feet", + "armor.body", + "saddle", + "horse.saddle", + "horse.chest", + "player.cursor", + "contents", + ] { + v.push(name.to_owned()); + } + v +} +/// The wildcard groups of `slot_names` (`container.*`, `armor.*`, ...). +pub const SLOT_GROUPS: [&str; 10] = [ + "container.*", + "hotbar.*", + "inventory.*", + "enderchest.*", + "villager.*", + "horse.*", + "player.crafting.*", + "armor.*", + "weapon.*", + "player.*", +]; pub fn integer(min: i32) -> ArgType { ArgType::Integer { min, max: i32::MAX } } @@ -1672,6 +1737,38 @@ impl ArgType { Arg::Str(name.to_owned()) } ArgType::IntRange => Arg::IntRange(range_int(reader)?), + ArgType::Name(_) => Arg::Str(reader.read_string()?), + ArgType::Enum(words) => { + let word = reader.read_unquoted_string(); + if !words.contains(&word) { + reader.cursor = start; + return Err(CommandError::tr_at("command.unknown.argument", &[], reader)); + } + Arg::Str(word.to_owned()) + } + ArgType::Function => { + let tag = reader.can_read() && reader.peek() == '#'; + if tag { + reader.skip(); + } + let id = read_id(reader)?; + Arg::Resource(if tag { format!("#{id}") } else { id }) + } + ArgType::Slots | ArgType::Slot => { + let mut end = reader.cursor; + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + end = reader.cursor; + } + let word = &reader.string[start..end]; + let known = slot_names().iter().any(|n| n == word) + || (matches!(self, ArgType::Slots) && SLOT_GROUPS.contains(&word)); + if !known { + reader.cursor = start; + return Err(CommandError::tr_at("slot.unknown", &[&word], reader)); + } + Arg::Str(word.to_owned()) + } ArgType::NbtPath => { let (path, used) = crate::nbt_path::NbtPath::parse_prefix(reader.remaining()) .map_err(|e| { @@ -1747,6 +1844,10 @@ impl ArgType { ArgType::Id(list) => { let values = match *list { "storages" => reg.storages.clone(), + "bossbars" => reg.bossbars.clone(), + "schedules" => reg.schedules.clone(), + "random_sequences" => reg.random_sequences.clone(), + "predicates" => reg.predicates.clone(), "time_markers" => reg.time_markers.clone(), "advancements" => reg.advancements.clone(), _ => Vec::new(), @@ -1809,6 +1910,27 @@ impl ArgType { builder.suggest_matching(slots.iter().map(String::as_str)); } ArgType::Operation => builder.suggest_matching(OPERATIONS), + ArgType::Enum(words) => builder.suggest_matching(words.iter().copied()), + ArgType::Name(list) => { + let names = match *list { + "datapacks_enabled" => reg.datapacks_enabled.clone(), + _ => reg.datapacks_disabled.clone(), + }; + builder.suggest_matching(names.iter().map(String::as_str)); + } + ArgType::Function => { + let functions = reg.functions.clone(); + suggest_resources(builder, &functions, ""); + let tags = reg.function_tags.clone(); + suggest_resources(builder, &tags, "#"); + } + ArgType::Slots | ArgType::Slot => { + let mut names = slot_names(); + if matches!(self, ArgType::Slots) { + names.extend(SLOT_GROUPS.iter().map(|s| (*s).to_owned())); + } + builder.suggest_matching(names.iter().map(String::as_str)); + } ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Swizzle | ArgType::Component => {} diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index d893cf0d7..f852d90b4 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -5,6 +5,8 @@ //! [`args`]; the vanilla command tree in [`vanilla`]. pub mod args; pub mod tree_data; +pub mod tree_execute; +pub mod tree_misc; pub mod tree_scoreboard; pub mod vanilla; diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index f9097cb81..b52bacddf 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -255,3 +255,113 @@ fn data_and_tag_commands_parse() { assert!(run("kill @e[scores={a=1..},team=red,nbt={x:1b},tag=t]").is_ok()); assert!(run("kill @e[scores={a=1..]").is_err()); } + +#[test] +fn smoke_commands_parse() { + for line in [ + "tag @s list", + "random value 1..6", + "team list", + "data get storage a:b", + "scoreboard objectives list", + "function test:a", + "execute store result score #r t run function test:a", + "schedule function test:a 20t", + "datapack list", + "bossbar list", + "item replace entity @s hotbar.0 with minecraft:stone 3", + ] { + assert!(run(line).is_ok(), "{line}: {:?}", run(line).err()); + } +} + +#[test] +fn execute_tree_covers_vanilla_forms() { + for line in [ + "execute as @a at @s run say hi", + "execute store result score @s x run data get entity @s Health", + "execute store success bossbar minecraft:b value run say hi", + "execute store result storage a:b out int 1.5 run time query gametime", + "execute store result entity @s Air short 1 run say hi", + "execute if score @s a = @s b run say hi", + "execute unless score @s a matches ..5 run say hi", + "execute if block ~ ~ ~ minecraft:stone", + "execute if blocks 0 0 0 1 1 1 5 5 5 masked run say hi", + "execute if biome ~ ~ ~ minecraft:plains", + "execute if loaded ~ ~ ~", + "execute if dimension minecraft:overworld", + "execute if data entity @s Inventory[0]", + "execute unless data storage a:b x run say hi", + "execute if predicate a:b", + "execute if function a:b run say hi", + "execute if items entity @s hotbar.* minecraft:stone", + "execute if slots block 0 0 0 container.*", + "execute positioned over world_surface run say hi", + "execute summon minecraft:pig run say hi", + "execute on vehicle run say hi", + "execute on passengers as @s run say hi", + "execute rotated as @s facing entity @s eyes align xyz anchored feet in minecraft:overworld run say hi", + ] { + assert!(run(line).is_ok(), "{line}: {:?}", run(line).err()); + } + assert!(run("execute positioned over nothing run say hi").is_err()); + assert!(run("execute on nobody run say hi").is_err()); + assert!(run("execute store result score @s").is_err()); +} + +#[test] +fn function_and_misc_trees() { + assert_eq!(run("function a:b").unwrap().0, "function"); + assert_eq!(run("function #a:tag {x:1}").unwrap().0, "function"); + assert_eq!( + run("function a:b with storage c:d path.x").unwrap().0, + "function" + ); + assert_eq!(run("return 5").unwrap().0, "return.value"); + assert_eq!(run("return fail").unwrap().0, "return.fail"); + assert_eq!(run("return run say hi").unwrap().0, "say"); + assert_eq!( + run("schedule function a:b 5s append").unwrap().0, + "schedule.function" + ); + assert_eq!(run("schedule clear a:b").unwrap().0, "schedule.clear"); + assert_eq!(run("random roll 1..20").unwrap().0, "random.roll"); + assert_eq!( + run("random reset * 5 true false").unwrap().0, + "random.reset" + ); + assert_eq!(run("teammsg hi there").unwrap().0, "teammsg"); + assert_eq!(run("tm hi").unwrap().0, "teammsg"); + assert_eq!( + run("bossbar set a:b color pink").unwrap().0, + "bossbar.set.color" + ); + assert_eq!( + run("bossbar set a:b players @a").unwrap().0, + "bossbar.set.players" + ); + assert_eq!(run("bossbar get a:b max").unwrap().0, "bossbar.get"); + assert_eq!( + run("item fill block 1 2 3 container.* with minecraft:stone 5") + .unwrap() + .0, + "item" + ); + assert_eq!( + run("item replace entity @s armor.head from block 0 0 0 container.3") + .unwrap() + .0, + "item" + ); + assert_eq!(run("tick rate 40").unwrap().0, "tick.rate"); + assert_eq!(run("tick step 1s").unwrap().0, "tick.step"); + assert_eq!(run("reload").unwrap().0, "reload"); + assert_eq!( + run("datapack enable \"file/x\" after \"file/y\"") + .unwrap() + .0, + "datapack.enable" + ); + assert!(run("bossbar set a:b value -1").is_err()); + assert!(run("item replace entity @s nowhere.0 with minecraft:stone").is_err()); +} diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-client/src/command/tree_execute.rs new file mode 100644 index 000000000..f8b3ae484 --- /dev/null +++ b/crates/horizon-client/src/command/tree_execute.rs @@ -0,0 +1,232 @@ +//! The `/execute` tree (ExecuteCommand): modifiers redirect back to +//! `execute`, `run` to the root; conditions both execute (as a test) and +//! continue the chain; `store` redirects with a result callback. +use super::{ + Dispatcher, + args::{ArgType, Resource}, + vanilla::{ENTITIES, GAMEMASTERS}, +}; + +pub const HEIGHTMAPS: &[&str] = &[ + "world_surface", + "motion_blocking", + "motion_blocking_no_leaves", + "ocean_floor", +]; +pub const RELATIONS: [&str; 8] = [ + "owner", + "leasher", + "target", + "attacker", + "vehicle", + "controller", + "origin", + "passengers", +]; + +/// A conditional's end: it runs as a test and continues the chain. +fn conditional(d: &mut Dispatcher, node: usize, ex: usize) { + d.executes(node, "execute"); + d.redirect(node, ex); +} + +pub fn register(d: &mut Dispatcher, root: usize) { + let ex = d.literal(root, "execute"); + d.requires(ex, GAMEMASTERS); + let run = d.literal(ex, "run"); + d.redirect(run, root); + for name in ["as", "at"] { + let l = d.literal(ex, name); + let t = d.argument(l, "targets", ENTITIES); + d.redirect(t, ex); + } + let positioned = d.literal(ex, "positioned"); + let pos = d.argument(positioned, "pos", ArgType::Vec3 { center: true }); + d.redirect(pos, ex); + let as_ = d.literal(positioned, "as"); + let t = d.argument(as_, "targets", ENTITIES); + d.redirect(t, ex); + let over = d.literal(positioned, "over"); + let hm = d.argument(over, "heightmap", ArgType::Enum(HEIGHTMAPS)); + d.redirect(hm, ex); + let rotated = d.literal(ex, "rotated"); + let rot = d.argument(rotated, "rot", ArgType::Rotation); + d.redirect(rot, ex); + let as_ = d.literal(rotated, "as"); + let t = d.argument(as_, "targets", ENTITIES); + d.redirect(t, ex); + let facing = d.literal(ex, "facing"); + let pos = d.argument(facing, "pos", ArgType::Vec3 { center: true }); + d.redirect(pos, ex); + let entity = d.literal(facing, "entity"); + let t = d.argument(entity, "targets", ENTITIES); + let anchor = d.argument(t, "anchor", ArgType::Anchor); + d.redirect(anchor, ex); + let align = d.literal(ex, "align"); + let axes = d.argument(align, "axes", ArgType::Swizzle); + d.redirect(axes, ex); + let anchored = d.literal(ex, "anchored"); + let anchor = d.argument(anchored, "anchor", ArgType::Anchor); + d.redirect(anchor, ex); + let in_ = d.literal(ex, "in"); + let dim = d.argument(in_, "dimension", ArgType::Dimension); + d.redirect(dim, ex); + let summon = d.literal(ex, "summon"); + let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType)); + d.redirect(e, ex); + let on = d.literal(ex, "on"); + for r in RELATIONS { + let l = d.literal(on, r); + d.redirect(l, ex); + } + store(d, ex); + for mode in ["if", "unless"] { + let m = d.literal(ex, mode); + conditionals(d, m, ex); + } +} + +fn store(d: &mut Dispatcher, ex: usize) { + let store = d.literal(ex, "store"); + for kind in ["result", "success"] { + let k = d.literal(store, kind); + let score = d.literal(k, "score"); + let targets = d.argument(score, "targets", ArgType::ScoreHolder { multiple: true }); + let objective = d.argument(targets, "objective", ArgType::Objective); + d.redirect(objective, ex); + let bossbar = d.literal(k, "bossbar"); + let id = d.argument(bossbar, "id", ArgType::Id("bossbars")); + for what in ["value", "max"] { + let w = d.literal(id, what); + d.redirect(w, ex); + } + for provider in ["entity", "block", "storage"] { + let p = d.literal(k, provider); + let a = match provider { + "entity" => d.argument( + p, + "target", + ArgType::Entity { + single: true, + players: false, + }, + ), + "block" => d.argument(p, "targetPos", ArgType::BlockPos), + _ => d.argument(p, "target", ArgType::Id("storages")), + }; + let path = d.argument(a, "path", ArgType::NbtPath); + for ty in ["int", "float", "short", "long", "double", "byte"] { + let t = d.literal(path, ty); + let scale = d.argument( + t, + "scale", + ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + ); + d.redirect(scale, ex); + } + } + } +} + +fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) { + let block = d.literal(m, "block"); + let pos = d.argument(block, "pos", ArgType::BlockPos); + let predicate = d.argument(pos, "block", ArgType::BlockPredicate); + conditional(d, predicate, ex); + + let biome = d.literal(m, "biome"); + let pos = d.argument(biome, "pos", ArgType::BlockPos); + let b = d.argument(pos, "biome", ArgType::Resource(Resource::Biome)); + conditional(d, b, ex); + + let loaded = d.literal(m, "loaded"); + let pos = d.argument(loaded, "pos", ArgType::BlockPos); + conditional(d, pos, ex); + + let dimension = d.literal(m, "dimension"); + let dim = d.argument(dimension, "dimension", ArgType::Dimension); + conditional(d, dim, ex); + + let score = d.literal(m, "score"); + let target = d.argument(score, "target", ArgType::ScoreHolder { multiple: false }); + let objective = d.argument(target, "targetObjective", ArgType::Objective); + for op in ["=", "<", "<=", ">", ">="] { + let o = d.literal(objective, op); + let source = d.argument(o, "source", ArgType::ScoreHolder { multiple: false }); + let so = d.argument(source, "sourceObjective", ArgType::Objective); + conditional(d, so, ex); + } + let matches = d.literal(objective, "matches"); + let range = d.argument(matches, "range", ArgType::IntRange); + conditional(d, range, ex); + + let blocks = d.literal(m, "blocks"); + let start = d.argument(blocks, "start", ArgType::BlockPos); + let end = d.argument(start, "end", ArgType::BlockPos); + let dest = d.argument(end, "destination", ArgType::BlockPos); + for mode in ["all", "masked"] { + let l = d.literal(dest, mode); + conditional(d, l, ex); + } + + let entity = d.literal(m, "entity"); + let targets = d.argument(entity, "entities", ENTITIES); + conditional(d, targets, ex); + + let predicate = d.literal(m, "predicate"); + let p = d.argument(predicate, "predicate", ArgType::Id("predicates")); + conditional(d, p, ex); + + let function = d.literal(m, "function"); + let name = d.argument(function, "name", ArgType::Function); + conditional(d, name, ex); + + let data = d.literal(m, "data"); + for provider in ["entity", "block", "storage"] { + let p = d.literal(data, provider); + let a = match provider { + "entity" => d.argument( + p, + "source", + ArgType::Entity { + single: true, + players: false, + }, + ), + "block" => d.argument(p, "sourcePos", ArgType::BlockPos), + _ => d.argument(p, "source", ArgType::Id("storages")), + }; + let path = d.argument(a, "path", ArgType::NbtPath); + conditional(d, path, ex); + } + + // items / slots (entity|block) [] + for kind in ["items", "slots"] { + let k = d.literal(m, kind); + for provider in ["entity", "block"] { + let p = d.literal(k, provider); + let a = if provider == "entity" { + d.argument( + p, + "source", + ArgType::Entity { + single: false, + players: false, + }, + ) + } else { + d.argument(p, "sourcePos", ArgType::BlockPos) + }; + let slots = d.argument(a, "slots", ArgType::Slots); + if kind == "items" { + let item = d.argument(slots, "item_predicate", ArgType::ItemPredicate); + conditional(d, item, ex); + } else { + conditional(d, slots, ex); + } + } + } +} diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-client/src/command/tree_misc.rs new file mode 100644 index 000000000..2494acb72 --- /dev/null +++ b/crates/horizon-client/src/command/tree_misc.rs @@ -0,0 +1,257 @@ +//! Smaller command trees: `/bossbar`, `/function`, `/return`, `/schedule`, +//! `/random`, `/tick`, `/teammsg`, `/reload` and `/datapack`. +use super::{ + Dispatcher, + args::ArgType, + vanilla::{ENTITIES, GAMEMASTERS, PLAYERS}, +}; + +fn int() -> ArgType { + ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + } +} +fn int_min(min: i32) -> ArgType { + ArgType::Integer { min, max: i32::MAX } +} +pub const ADMINS: u8 = 3; + +pub fn register(d: &mut Dispatcher, root: usize) { + item(d, root); + bossbar(d, root); + function(d, root); + + // return | fail | run + let ret = d.literal(root, "return"); + d.requires(ret, GAMEMASTERS); + let v = d.argument(ret, "value", int()); + d.executes(v, "return.value"); + let fail = d.literal(ret, "fail"); + d.executes(fail, "return.fail"); + let run = d.literal(ret, "run"); + d.redirect(run, root); + + // schedule function