Merge pull request #1901 from ludovic111/feat/server-mods-commands
🤖 Agent: the parity stop atc5534f0d7was friends_integration, which main broke through #2501 and #2598 fixes, plus remote_fireworks and server_player_sculk (load on the old runner; both pass on main on the Mac mini). None of the three is from this PR. Merged main (fde2dfffe, a clean merge); pr_ready --quick passed: 1357 tests, clippy, launcher.
This commit is contained in:
@@ -200,7 +200,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
return Err(format!("it didn't start: {reason}"));
|
||||
}
|
||||
let client: Vec<String> = mods.commands().map(str::to_owned).collect();
|
||||
let server: Vec<String> = mods.server_commands().map(str::to_owned).collect();
|
||||
let server: Vec<String> = mods.server_commands().map(|c| c.name.clone()).collect();
|
||||
report.commands = [client.clone(), server.clone()].concat();
|
||||
// A server mod plays with one player on, who joins, chats and leaves.
|
||||
let steve = ServerPlayer {
|
||||
|
||||
@@ -371,7 +371,10 @@ impl Game<'_> {
|
||||
}
|
||||
/// The chat's tree after the running mods changed.
|
||||
fn sync_mod_commands(&mut self) {
|
||||
let mut names = self.mods.mods.commands().peekable();
|
||||
// In-frame, the window runs server mods too: their names, free text
|
||||
// here (the server parses their arguments).
|
||||
let server = self.mods.mods.server_commands().map(|c| c.name.as_str());
|
||||
let mut names = self.mods.mods.commands().chain(server).peekable();
|
||||
self.mods.tree = names
|
||||
.peek()
|
||||
.is_some()
|
||||
|
||||
@@ -59,9 +59,12 @@ mod run {
|
||||
lan::data::component_nbt,
|
||||
text::{self, Text},
|
||||
};
|
||||
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
|
||||
use horizon_mods::{
|
||||
ArgumentKind, BlockPos, GameMode, Output, ServerCommand, ServerPlayer, WorldView,
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Blocks queued for levels that don't tick (another dimension, in-frame)
|
||||
/// are kept up to this many; the oldest go first.
|
||||
@@ -98,6 +101,60 @@ mod run {
|
||||
}
|
||||
}
|
||||
|
||||
/// Server mods' commands as a root of the commands report
|
||||
/// (`lan::commands`): a literal per command, then its arguments in a
|
||||
/// chain, each node runnable where only optional arguments follow.
|
||||
fn command_tree<'a>(commands: impl Iterator<Item = &'a ServerCommand>) -> Value {
|
||||
let mut root = serde_json::Map::new();
|
||||
for c in commands {
|
||||
let mut next: Option<(String, Value)> = None;
|
||||
for (i, a) in c.arguments.iter().enumerate().rev() {
|
||||
let executable = c.arguments.get(i + 1).is_none_or(|b| b.optional);
|
||||
let (parser, properties) = match a.kind {
|
||||
ArgumentKind::Word => ("brigadier:string", json!({"type": "word"})),
|
||||
ArgumentKind::Text => ("brigadier:string", json!({"type": "greedy"})),
|
||||
ArgumentKind::Integer((min, max)) => {
|
||||
let mut p = serde_json::Map::new();
|
||||
if let Some(min) = min {
|
||||
p.insert("min".into(), min.into());
|
||||
}
|
||||
if let Some(max) = max {
|
||||
p.insert("max".into(), max.into());
|
||||
}
|
||||
("brigadier:integer", Value::Object(p))
|
||||
}
|
||||
ArgumentKind::Number => ("brigadier:double", Value::Null),
|
||||
ArgumentKind::Boolean => ("brigadier:bool", Value::Null),
|
||||
ArgumentKind::Player => (
|
||||
"minecraft:entity",
|
||||
json!({"amount": "single", "type": "players"}),
|
||||
),
|
||||
ArgumentKind::BlockPos => ("minecraft:block_pos", Value::Null),
|
||||
};
|
||||
let mut node = json!({
|
||||
"type": "argument",
|
||||
"parser": parser,
|
||||
"properties": properties,
|
||||
"executable": executable,
|
||||
});
|
||||
if let Some((name, child)) = next.take() {
|
||||
node["children"] = json!({ name: child });
|
||||
}
|
||||
next = Some((a.name.clone(), node));
|
||||
}
|
||||
let executable = c.arguments.first().is_none_or(|a| a.optional);
|
||||
let mut literal = json!({"type": "literal", "executable": executable});
|
||||
if let Some((name, child)) = next {
|
||||
literal["children"] = json!({ name: child });
|
||||
}
|
||||
root.insert(c.name.clone(), literal);
|
||||
}
|
||||
if root.is_empty() {
|
||||
return Value::Null;
|
||||
}
|
||||
json!({"type": "root", "children": root})
|
||||
}
|
||||
|
||||
/// `minecraft:oak_log[axis=y]`.
|
||||
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
|
||||
let Some(s) = registry.state(state) else {
|
||||
@@ -191,6 +248,7 @@ mod run {
|
||||
// A server has no frames to check its dev mods in.
|
||||
self.reload_dev_mods();
|
||||
}
|
||||
self.send_server_mod_commands();
|
||||
if !self.mods.server {
|
||||
return;
|
||||
}
|
||||
@@ -257,6 +315,20 @@ mod run {
|
||||
self.apply_mod_block_writes();
|
||||
}
|
||||
|
||||
/// Players' command trees list the running server mods' commands
|
||||
/// after vanilla's, whenever they change (or a hub opens).
|
||||
fn send_server_mod_commands(&mut self) {
|
||||
let key = self.mods.mods.generation();
|
||||
let Some(host) = self.lan.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if host.hub.mod_commands_key() == Some(key) {
|
||||
return;
|
||||
}
|
||||
let tree = command_tree(self.mods.mods.server_commands());
|
||||
host.hub.set_mod_commands(key, tree);
|
||||
}
|
||||
|
||||
/// Lends the levels' chunks to capability `world` for the calls up to
|
||||
/// [`Game::return_world`], when a running server mod has it.
|
||||
fn lend_world(&mut self) {
|
||||
|
||||
@@ -86,6 +86,18 @@ impl CommandTree {
|
||||
|
||||
/// The ClientboundCommandsPacket for a player with `level` permissions.
|
||||
pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands {
|
||||
self.packet_with(level, dedicated, builtin, &Value::Null)
|
||||
}
|
||||
|
||||
/// [`CommandTree::packet`] with more commands after vanilla's: `extra`
|
||||
/// is a root in the report's format (server mods' commands).
|
||||
pub fn packet_with(
|
||||
&self,
|
||||
level: u8,
|
||||
dedicated: bool,
|
||||
builtin: &Builtin,
|
||||
extra: &Value,
|
||||
) -> Commands {
|
||||
let mut nodes = vec![Node {
|
||||
name: String::new(),
|
||||
kind: 0,
|
||||
@@ -99,16 +111,18 @@ impl CommandTree {
|
||||
let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect();
|
||||
let mut paths: HashMap<Vec<String>, usize> = HashMap::new();
|
||||
paths.insert(Vec::new(), 0);
|
||||
fill(
|
||||
&self.root,
|
||||
0,
|
||||
&mut Vec::new(),
|
||||
level,
|
||||
dedicated,
|
||||
&suggestions,
|
||||
&mut nodes,
|
||||
&mut paths,
|
||||
);
|
||||
for root in [&self.root, extra] {
|
||||
fill(
|
||||
root,
|
||||
0,
|
||||
&mut Vec::new(),
|
||||
level,
|
||||
dedicated,
|
||||
&suggestions,
|
||||
&mut nodes,
|
||||
&mut paths,
|
||||
);
|
||||
}
|
||||
// enumerateNodes: breadth first from the root, each node's children
|
||||
// (in registration order) then its redirect target.
|
||||
let mut ids = vec![None; nodes.len()];
|
||||
@@ -365,4 +379,33 @@ mod tests {
|
||||
);
|
||||
assert!(op.nodes[3].restricted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_mods_commands_follow_vanillas() {
|
||||
let report: Value = serde_json::from_str(
|
||||
r#"{"type":"root","children":{"me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mods: Value = serde_json::from_str(
|
||||
r#"{"type":"root","children":{"beacon":{"type":"literal","executable":true,"children":{
|
||||
"height":{"type":"argument","parser":"brigadier:integer","properties":{"min":1,"max":64},"executable":true}}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let tree = CommandTree { root: report };
|
||||
let packet = tree.packet_with(0, true, &Builtin::default(), &mods);
|
||||
let names: Vec<_> = packet.nodes.iter().map(|n| n.name.as_str()).collect();
|
||||
assert_eq!(names, ["", "me", "beacon", "action", "height"]);
|
||||
let beacon = &packet.nodes[2];
|
||||
assert!(beacon.executable && !beacon.restricted);
|
||||
assert_eq!(beacon.children, [4]);
|
||||
let height = packet.nodes[4].parser.as_ref().unwrap();
|
||||
assert_eq!(height.1, vec![3, 0, 0, 0, 1, 0, 0, 0, 64]);
|
||||
// No mods: vanilla's tree as it is.
|
||||
assert_eq!(
|
||||
tree.packet_with(0, true, &Builtin::default(), &Value::Null)
|
||||
.nodes
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +177,9 @@ pub struct Hub {
|
||||
entities: std::collections::HashMap<String, Entities>,
|
||||
/// What one tick of entity tracking sends each guest, kept between ticks.
|
||||
entity_out: Vec<Vec<Vec<u8>>>,
|
||||
/// Server mods' commands, a root in the commands report's format, sent
|
||||
/// after vanilla's; the key the game last set them for.
|
||||
mod_commands: (serde_json::Value, Option<u64>),
|
||||
}
|
||||
|
||||
fn string(s: &str) -> Tag {
|
||||
@@ -341,6 +344,7 @@ impl Hub {
|
||||
entity_types: Default::default(),
|
||||
entities: Default::default(),
|
||||
entity_out: Vec::new(),
|
||||
mod_commands: (serde_json::Value::Null, None),
|
||||
teams: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -849,13 +853,36 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
|
||||
/// The key [`Hub::set_mod_commands`] last had: the game compares it
|
||||
/// with its server mods' each tick.
|
||||
pub fn mod_commands_key(&self) -> Option<u64> {
|
||||
self.mod_commands.1
|
||||
}
|
||||
/// Server mods' commands changed: every player gets their tree again.
|
||||
pub fn set_mod_commands(&mut self, key: u64, commands: serde_json::Value) {
|
||||
let resend = self.mod_commands.0 != commands;
|
||||
self.mod_commands = (commands, Some(key));
|
||||
if resend {
|
||||
for i in 0..self.guests.len() {
|
||||
if self.guests[i].placed {
|
||||
self.send_commands(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands.sendCommands: the command tree for this player.
|
||||
fn send_commands(&self, i: usize) {
|
||||
let g = &self.guests[i];
|
||||
let packet = match &self.sync.commands {
|
||||
Some(tree) => {
|
||||
let dedicated = self.config.dedicated && !self.config.integrated;
|
||||
tree.packet(g.permission, dedicated, &self.sync.builtin)
|
||||
tree.packet_with(
|
||||
g.permission,
|
||||
dedicated,
|
||||
&self.sync.builtin,
|
||||
&self.mod_commands.0,
|
||||
)
|
||||
}
|
||||
None => play::Commands {
|
||||
nodes: vec![play::CommandNode {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
id = "beacons"
|
||||
name = "Beacons"
|
||||
version = "0.1.0"
|
||||
description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome."
|
||||
description = "/beacon [height] lights a pillar of glowstone beside you; /ground [pos] says what you are standing on (or what is at pos), and in which biome."
|
||||
authors = ["Horizon"]
|
||||
api = "0.3"
|
||||
side = "server"
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
//! Example Horizon server mod (`docs/mods.md`, "Server mods") with
|
||||
//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east
|
||||
//! of the player, `/ground` reads the block under their feet and the biome.
|
||||
use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world};
|
||||
//! capability `world` and typed commands: `/beacon [height]` lights a
|
||||
//! pillar of glowstone two blocks east of the player, `/ground [pos]` reads
|
||||
//! the block under their feet (or at `pos`) and its biome.
|
||||
use horizon_mod_sdk::server::{
|
||||
Args, Argument, BlockChange, Player, Registration, ServerMod, players, world,
|
||||
};
|
||||
|
||||
/// How tall `/beacon` builds.
|
||||
/// How tall `/beacon` builds when no height is given.
|
||||
const HEIGHT: i32 = 4;
|
||||
|
||||
struct Beacons;
|
||||
@@ -17,10 +20,10 @@ fn feet(player: &Player) -> (i32, i32, i32) {
|
||||
)
|
||||
}
|
||||
|
||||
/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up.
|
||||
fn pillar(player: &Player) -> Vec<BlockChange> {
|
||||
/// The pillar beside `player`: `height` blocks of glowstone, from their feet up.
|
||||
fn pillar(player: &Player, height: i32) -> Vec<BlockChange> {
|
||||
let (x, y, z) = feet(player);
|
||||
(0..HEIGHT)
|
||||
(0..height)
|
||||
.map(|dy| BlockChange {
|
||||
x: x + 2,
|
||||
y: y + dy,
|
||||
@@ -34,7 +37,12 @@ impl ServerMod for Beacons {
|
||||
fn init() -> Result<(Self, Registration), String> {
|
||||
Ok((
|
||||
Beacons,
|
||||
Registration::new().command("beacon").command("ground"),
|
||||
Registration::new()
|
||||
.command_with(
|
||||
"beacon",
|
||||
[Argument::integer("height", Some(1), Some(64)).optional()],
|
||||
)
|
||||
.command_with("ground", [Argument::block_pos("pos").optional()]),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -42,11 +50,12 @@ impl ServerMod for Beacons {
|
||||
&mut self,
|
||||
player: &Player,
|
||||
name: &str,
|
||||
_args: &str,
|
||||
args: &Args,
|
||||
) -> Result<Option<String>, String> {
|
||||
let (x, y, z) = feet(player);
|
||||
if name == "beacon" {
|
||||
world::set_blocks(&player.dimension, &pillar(player))?;
|
||||
let height = args.integer("height").unwrap_or(HEIGHT);
|
||||
world::set_blocks(&player.dimension, &pillar(player, height))?;
|
||||
players::broadcast(&format!(
|
||||
"{} lit a beacon at {} {y} {z}",
|
||||
player.name,
|
||||
@@ -54,10 +63,17 @@ impl ServerMod for Beacons {
|
||||
));
|
||||
return Ok(None);
|
||||
}
|
||||
let below = world::get_block(&player.dimension, x, y - 1, z)
|
||||
.ok_or("The ground under you isn't loaded")?;
|
||||
let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default();
|
||||
Ok(Some(format!("You are standing on {below} in {biome}")))
|
||||
let (bx, by, bz) = match args.block_pos("pos") {
|
||||
Some(p) => (p.x, p.y, p.z),
|
||||
None => (x, y - 1, z),
|
||||
};
|
||||
let block =
|
||||
world::get_block(&player.dimension, bx, by, bz).ok_or("That block isn't loaded")?;
|
||||
let biome = world::get_biome(&player.dimension, bx, by, bz).unwrap_or_default();
|
||||
if args.block_pos("pos").is_some() {
|
||||
return Ok(Some(format!("{bx} {by} {bz} is {block} in {biome}")));
|
||||
}
|
||||
Ok(Some(format!("You are standing on {block} in {biome}")))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +95,7 @@ mod tests {
|
||||
game_mode: horizon_mod_sdk::server::GameMode::Survival,
|
||||
health: 20.0,
|
||||
};
|
||||
let blocks = pillar(&p);
|
||||
let blocks = pillar(&p, HEIGHT);
|
||||
assert_eq!(blocks.len(), HEIGHT as usize);
|
||||
assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3));
|
||||
assert_eq!(blocks[3].y, 67);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east.
|
||||
# /ground [pos] reads the block under the player (or at pos) and the biome; /beacon [height] sets glowstone two to the east.
|
||||
|
||||
[[step]]
|
||||
join = "Alex"
|
||||
@@ -20,3 +20,20 @@ expect.blocks = [
|
||||
player = { x = 10.5, z = 10.5 }
|
||||
command = "ground"
|
||||
expect.feedback = "You are standing on minecraft:air in minecraft:plains"
|
||||
|
||||
# Typed arguments: a height, a position relative to the player.
|
||||
[[step]]
|
||||
player = { x = 5.5, y = 64.0, z = 5.5 }
|
||||
command = "beacon 2"
|
||||
expect.blocks = [
|
||||
{ x = 7, y = 65, z = 5, state = "minecraft:glowstone" },
|
||||
{ x = 7, y = 66, z = 5, state = "minecraft:air" },
|
||||
]
|
||||
|
||||
[[step]]
|
||||
command = "beacon 65"
|
||||
expect.error = "Integer must not be more than 64, found 65"
|
||||
|
||||
[[step]]
|
||||
command = "ground ~2 ~1 ~"
|
||||
expect.feedback = "7 65 5 is minecraft:glowstone in minecraft:plains"
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each
|
||||
//! player who joins, announces a newcomer to everyone (the players it has
|
||||
//! seen are kept in `storage`), `/online` lists who is on and where, and
|
||||
//! `/mined` counts the blocks the player broke since the server started.
|
||||
//! `/mined [player]` counts the blocks a player broke since the server
|
||||
//! started (typed arguments: the chat box completes the player's name).
|
||||
use horizon_mod_sdk::{
|
||||
server::{BlockPos, Player, Registration, ServerMod, players},
|
||||
server::{Args, Argument, BlockPos, Player, Registration, ServerMod, players},
|
||||
storage,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
@@ -25,8 +26,8 @@ impl ServerMod for Welcome {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let hooks = Registration::new()
|
||||
.command("online")
|
||||
.command("mined")
|
||||
.command_with("online", [])
|
||||
.command_with("mined", [Argument::player("player").optional()])
|
||||
.on_joins()
|
||||
.on_blocks();
|
||||
Ok((
|
||||
@@ -55,7 +56,7 @@ impl ServerMod for Welcome {
|
||||
&mut self,
|
||||
player: &Player,
|
||||
name: &str,
|
||||
_args: &str,
|
||||
args: &Args,
|
||||
) -> Result<Option<String>, String> {
|
||||
Ok(Some(match name {
|
||||
"online" => players::online()
|
||||
@@ -69,10 +70,16 @@ impl ServerMod for Welcome {
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
_ => {
|
||||
let n = self.mined.get(&player.id).copied().unwrap_or(0);
|
||||
format!("You broke {n} block(s)")
|
||||
}
|
||||
_ => match args.player("player") {
|
||||
Some(other) if other.id != player.id => {
|
||||
let n = self.mined.get(&other.id).copied().unwrap_or(0);
|
||||
format!("{} broke {n} block(s)", other.name)
|
||||
}
|
||||
_ => {
|
||||
let n = self.mined.get(&player.id).copied().unwrap_or(0);
|
||||
format!("You broke {n} block(s)")
|
||||
}
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# /online lists the players and their dimension; /mined counts the acting player's blocks.
|
||||
# /online lists the players and their dimension; /mined [player] counts a player's blocks.
|
||||
|
||||
[[step]]
|
||||
join = "Alex"
|
||||
@@ -29,3 +29,18 @@ expect.feedback = "You broke 2 block(s)"
|
||||
as = "Steve"
|
||||
command = "mined"
|
||||
expect.feedback = "You broke 0 block(s)"
|
||||
|
||||
[[step]]
|
||||
as = "Steve"
|
||||
command = "mined alex"
|
||||
expect.feedback = "Alex broke 2 block(s)"
|
||||
|
||||
# The server parses the arguments before the mod: vanilla's errors.
|
||||
[[step]]
|
||||
as = "Steve"
|
||||
command = "mined Herobrine"
|
||||
expect.error = "No player was found"
|
||||
|
||||
[[step]]
|
||||
command = "online now"
|
||||
expect.error = "Incorrect argument for command"
|
||||
|
||||
@@ -194,7 +194,10 @@ pub mod server {
|
||||
},
|
||||
});
|
||||
|
||||
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
|
||||
pub use exports::horizon::mods::server_events::{
|
||||
Argument, ArgumentKind, ArgumentValue, BlockPos, Guest as __Guest, Registration,
|
||||
ServerCommand,
|
||||
};
|
||||
pub use horizon::mods::players::{self, GameMode, Player};
|
||||
pub use horizon::mods::world::{self, BlockChange};
|
||||
|
||||
@@ -211,13 +214,14 @@ pub mod server {
|
||||
fn player_left(&mut self, _player: &Player) {}
|
||||
/// A chat message a player sent, when [`Registration::chat`] is set.
|
||||
fn chat(&mut self, _player: &Player, _text: &str) {}
|
||||
/// `/name args` typed by `player`. `Ok(Some(text))` is their
|
||||
/// feedback, `Err(text)` their error in red.
|
||||
/// `/name args` typed by `player`, parsed as the command's
|
||||
/// arguments say ([`Registration::command_with`]). `Ok(Some(text))`
|
||||
/// is their feedback, `Err(text)` their error in red.
|
||||
fn command(
|
||||
&mut self,
|
||||
_player: &Player,
|
||||
_name: &str,
|
||||
_args: &str,
|
||||
_args: &Args,
|
||||
) -> Result<Option<String>, String> {
|
||||
Err("This command does nothing".into())
|
||||
}
|
||||
@@ -237,9 +241,23 @@ pub mod server {
|
||||
blocks: false,
|
||||
}
|
||||
}
|
||||
/// Adds `/name`.
|
||||
pub fn command(mut self, name: &str) -> Self {
|
||||
self.commands.push(name.into());
|
||||
/// Adds `/name`, taking free text ([`Args::text`]): one optional
|
||||
/// `text` argument named `args`.
|
||||
pub fn command(self, name: &str) -> Self {
|
||||
self.command_with(name, [Argument::text("args").optional()])
|
||||
}
|
||||
/// Adds `/name` with typed arguments (none: nothing after the name):
|
||||
/// players' chat boxes complete and check them, and the server
|
||||
/// parses them into [`Args`].
|
||||
pub fn command_with(
|
||||
mut self,
|
||||
name: &str,
|
||||
arguments: impl IntoIterator<Item = Argument>,
|
||||
) -> Self {
|
||||
self.commands.push(ServerCommand {
|
||||
name: name.into(),
|
||||
arguments: arguments.into_iter().collect(),
|
||||
});
|
||||
self
|
||||
}
|
||||
pub fn on_tick(mut self) -> Self {
|
||||
@@ -264,6 +282,105 @@ pub mod server {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Argument {
|
||||
fn of(name: &str, kind: ArgumentKind) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
kind,
|
||||
optional: false,
|
||||
}
|
||||
}
|
||||
/// One word: letters, digits and `_ - . +`.
|
||||
pub fn word(name: &str) -> Self {
|
||||
Self::of(name, ArgumentKind::Word)
|
||||
}
|
||||
/// The rest of the line: only last.
|
||||
pub fn text(name: &str) -> Self {
|
||||
Self::of(name, ArgumentKind::Text)
|
||||
}
|
||||
/// A whole number, at least `min` and at most `max` when given.
|
||||
pub fn integer(name: &str, min: Option<i32>, max: Option<i32>) -> Self {
|
||||
Self::of(name, ArgumentKind::Integer((min, max)))
|
||||
}
|
||||
pub fn number(name: &str) -> Self {
|
||||
Self::of(name, ArgumentKind::Number)
|
||||
}
|
||||
pub fn boolean(name: &str) -> Self {
|
||||
Self::of(name, ArgumentKind::Boolean)
|
||||
}
|
||||
/// One online player: a name, `@s` or `@p`.
|
||||
pub fn player(name: &str) -> Self {
|
||||
Self::of(name, ArgumentKind::Player)
|
||||
}
|
||||
/// `x y z`, each one also `~` or `~n`.
|
||||
pub fn block_pos(name: &str) -> Self {
|
||||
Self::of(name, ArgumentKind::BlockPos)
|
||||
}
|
||||
/// May be left out; optional arguments come after the required ones.
|
||||
pub fn optional(mut self) -> Self {
|
||||
self.optional = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A command's arguments: the line as typed, and the values the server
|
||||
/// parsed from it, by argument name.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Args {
|
||||
text: String,
|
||||
values: Vec<(String, ArgumentValue)>,
|
||||
}
|
||||
impl Args {
|
||||
pub fn new(text: String, values: Vec<(String, ArgumentValue)>) -> Self {
|
||||
Self { text, values }
|
||||
}
|
||||
/// The line after the command's name, as typed.
|
||||
pub fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
/// The value of argument `name`; `None` when it was left out.
|
||||
pub fn get(&self, name: &str) -> Option<&ArgumentValue> {
|
||||
self.values.iter().find(|(n, _)| n == name).map(|(_, v)| v)
|
||||
}
|
||||
pub fn integer(&self, name: &str) -> Option<i32> {
|
||||
match self.get(name)? {
|
||||
ArgumentValue::Integer(n) => Some(*n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn number(&self, name: &str) -> Option<f64> {
|
||||
match self.get(name)? {
|
||||
ArgumentValue::Number(n) => Some(*n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A `word` or `text` argument.
|
||||
pub fn string(&self, name: &str) -> Option<&str> {
|
||||
match self.get(name)? {
|
||||
ArgumentValue::Word(s) | ArgumentValue::Text(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn boolean(&self, name: &str) -> Option<bool> {
|
||||
match self.get(name)? {
|
||||
ArgumentValue::Boolean(b) => Some(*b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn player(&self, name: &str) -> Option<&Player> {
|
||||
match self.get(name)? {
|
||||
ArgumentValue::Player(p) => Some(p),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn block_pos(&self, name: &str) -> Option<BlockPos> {
|
||||
match self.get(name)? {
|
||||
ArgumentValue::BlockPos(p) => Some(*p),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports a [`ServerMod`](server::ServerMod) as the component's
|
||||
@@ -273,7 +390,7 @@ macro_rules! export_server_mod {
|
||||
($t:ty) => {
|
||||
const _: () = {
|
||||
use ::std::cell::RefCell;
|
||||
use $crate::server::{BlockPos, Player, Registration, ServerMod};
|
||||
use $crate::server::{Args, ArgumentValue, BlockPos, Player, Registration, ServerMod};
|
||||
::std::thread_local! {
|
||||
static STATE: RefCell<Option<$t>> = const { RefCell::new(None) };
|
||||
}
|
||||
@@ -307,8 +424,10 @@ macro_rules! export_server_mod {
|
||||
player: Player,
|
||||
name: String,
|
||||
args: String,
|
||||
values: Vec<(String, ArgumentValue)>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let mut out = Err("The mod is not running".to_string());
|
||||
let args = Args::new(args, values);
|
||||
with(|m| out = m.command(&player, &name, &args));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -680,10 +680,61 @@ interface %world {
|
||||
interface server-events {
|
||||
use players.{player};
|
||||
|
||||
record block-pos {
|
||||
x: s32,
|
||||
y: s32,
|
||||
z: s32,
|
||||
}
|
||||
/// What an argument of a command takes. The server sends each command
|
||||
/// and its arguments to players' games, whose chat box completes and
|
||||
/// colours them as vanilla's; the server parses them before the mod's
|
||||
/// `command` hook gets their values.
|
||||
variant argument-kind {
|
||||
/// One word: letters, digits and `_ - . +`.
|
||||
word,
|
||||
/// The rest of the line, spaces included: only last.
|
||||
text,
|
||||
/// A whole number, within the bounds given.
|
||||
integer(tuple<option<s32>, option<s32>>),
|
||||
/// A number with or without decimals.
|
||||
number,
|
||||
/// `true` or `false`.
|
||||
boolean,
|
||||
/// One online player: a name, or `@s` or `@p` (whoever typed it,
|
||||
/// as vanilla picks for a player).
|
||||
player,
|
||||
/// A block position: three whole numbers, each one also `~` or
|
||||
/// `~n`, relative to whoever typed it.
|
||||
block-pos,
|
||||
}
|
||||
record argument {
|
||||
/// Shown in the chat box's hint (`<height>`) and the key of its value.
|
||||
name: string,
|
||||
kind: argument-kind,
|
||||
/// Optional arguments come after every required one.
|
||||
optional: bool,
|
||||
}
|
||||
record server-command {
|
||||
/// Without the slash. A name vanilla already uses is refused
|
||||
/// (vanilla's command runs).
|
||||
name: string,
|
||||
/// In order; none: the command takes nothing after its name. Free
|
||||
/// text is one optional `text` argument.
|
||||
arguments: list<argument>,
|
||||
}
|
||||
/// An argument's value, parsed as its kind says.
|
||||
variant argument-value {
|
||||
word(string),
|
||||
text(string),
|
||||
integer(s32),
|
||||
number(f64),
|
||||
boolean(bool),
|
||||
player(player),
|
||||
block-pos(block-pos),
|
||||
}
|
||||
record registration {
|
||||
/// Commands players may type, without the slash. A name vanilla
|
||||
/// already uses is refused (vanilla's command runs).
|
||||
commands: list<string>,
|
||||
/// Commands players may type.
|
||||
commands: list<server-command>,
|
||||
/// Call `tick` every server tick (20 per second).
|
||||
tick: bool,
|
||||
/// Call `player-joined` and `player-left`.
|
||||
@@ -693,11 +744,6 @@ interface server-events {
|
||||
/// Call `block-broken` and `block-placed`.
|
||||
blocks: bool,
|
||||
}
|
||||
record block-pos {
|
||||
x: s32,
|
||||
y: s32,
|
||||
z: s32,
|
||||
}
|
||||
/// Once, after loading. An error keeps the mod off and is logged.
|
||||
init: func() -> result<registration, string>;
|
||||
/// Each server tick, with the server's tick counter.
|
||||
@@ -709,8 +755,10 @@ interface server-events {
|
||||
/// A chat message a player sent, as plain text.
|
||||
chat: func(player: player, text: string);
|
||||
/// `/name args` typed by `player`: ok(some(text)) is their feedback,
|
||||
/// err(text) their error in red.
|
||||
command: func(player: player, name: string, args: string) -> result<option<string>, string>;
|
||||
/// err(text) their error in red. `values` holds each argument given, by
|
||||
/// name, in order (an optional one left out isn't there); a line that
|
||||
/// doesn't parse never reaches the mod: the player gets vanilla's error.
|
||||
command: func(player: player, name: string, args: string, values: list<tuple<string, argument-value>>) -> result<option<string>, string>;
|
||||
/// A player broke the block at `pos` in their dimension: `state` is what
|
||||
/// was there, as `minecraft:oak_log[axis=y]`.
|
||||
block-broken: func(player: player, pos: block-pos, state: string);
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Server mods' typed commands: an argument line parsed as the command's
|
||||
//! arguments say, the way vanilla's Brigadier parsers read them, with
|
||||
//! vanilla's error messages. The game sends the same arguments to players'
|
||||
//! command trees, so their chat box checks them before the server does.
|
||||
use crate::runtime::{Argument, ArgumentKind, ArgumentValue, BlockPos, ServerPlayer};
|
||||
|
||||
/// The values of `args`, typed by `player`, for `arguments` (in order;
|
||||
/// optional ones left out aren't there), or the error the player reads.
|
||||
pub fn parse(
|
||||
arguments: &[Argument],
|
||||
args: &str,
|
||||
player: &ServerPlayer,
|
||||
online: &[ServerPlayer],
|
||||
) -> Result<Vec<(String, ArgumentValue)>, String> {
|
||||
let mut values = Vec::new();
|
||||
let mut rest = args;
|
||||
for (i, argument) in arguments.iter().enumerate() {
|
||||
if i > 0 && !rest.is_empty() {
|
||||
rest = rest.strip_prefix(' ').ok_or(
|
||||
"Expected whitespace to end one argument, but found trailing data".to_string(),
|
||||
)?;
|
||||
}
|
||||
if rest.is_empty() {
|
||||
if argument.optional {
|
||||
break;
|
||||
}
|
||||
return Err("Unknown or incomplete command, see below for error".into());
|
||||
}
|
||||
let (value, after) = one(&argument.kind, rest, player, online)?;
|
||||
values.push((argument.name.clone(), value));
|
||||
rest = after;
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
return Err("Incorrect argument for command".into());
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// StringReader.isAllowedInUnquotedString.
|
||||
fn unquoted(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+')
|
||||
}
|
||||
|
||||
/// The unquoted string at the start of `s`, and what follows it.
|
||||
fn word(s: &str) -> (&str, &str) {
|
||||
let end = s.find(|c: char| !unquoted(c)).unwrap_or(s.len());
|
||||
s.split_at(end)
|
||||
}
|
||||
|
||||
/// One argument from the start of `s`, and what follows it.
|
||||
fn one<'a>(
|
||||
kind: &ArgumentKind,
|
||||
s: &'a str,
|
||||
player: &ServerPlayer,
|
||||
online: &[ServerPlayer],
|
||||
) -> Result<(ArgumentValue, &'a str), String> {
|
||||
Ok(match kind {
|
||||
ArgumentKind::Word => {
|
||||
let (w, rest) = word(s);
|
||||
if w.is_empty() {
|
||||
return Err("Expected string".into());
|
||||
}
|
||||
(ArgumentValue::Word(w.into()), rest)
|
||||
}
|
||||
ArgumentKind::Text => (ArgumentValue::Text(s.into()), ""),
|
||||
ArgumentKind::Integer((min, max)) => {
|
||||
let (n, rest) = integer(s)?;
|
||||
if let Some(min) = min.filter(|m| n < *m) {
|
||||
return Err(format!("Integer must not be less than {min}, found {n}"));
|
||||
}
|
||||
if let Some(max) = max.filter(|m| n > *m) {
|
||||
return Err(format!("Integer must not be more than {max}, found {n}"));
|
||||
}
|
||||
(ArgumentValue::Integer(n), rest)
|
||||
}
|
||||
ArgumentKind::Number => {
|
||||
let (n, rest) = double(s)?;
|
||||
(ArgumentValue::Number(n), rest)
|
||||
}
|
||||
ArgumentKind::Boolean => {
|
||||
let (w, rest) = word(s);
|
||||
let b = match w {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
"" => return Err("Expected bool".into()),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"Invalid boolean, expected 'true' or 'false' but found '{w}'"
|
||||
));
|
||||
}
|
||||
};
|
||||
(ArgumentValue::Boolean(b), rest)
|
||||
}
|
||||
ArgumentKind::Player => {
|
||||
if let Some(selector) = s.strip_prefix('@') {
|
||||
let (kind, rest) = word(selector);
|
||||
return match kind {
|
||||
// A player's @p is themselves (the nearest to where they are).
|
||||
"s" | "p" => Ok((ArgumentValue::Player(player.clone()), rest)),
|
||||
"a" | "e" | "r" | "n" => {
|
||||
Err("Only one player is allowed, but the provided selector allows more than one".into())
|
||||
}
|
||||
_ => Err(format!("Unknown selector type '@{kind}'")),
|
||||
};
|
||||
}
|
||||
let (name, rest) = word(s);
|
||||
if name.is_empty() {
|
||||
return Err("Invalid name or UUID".into());
|
||||
}
|
||||
let found = online
|
||||
.iter()
|
||||
.find(|p| p.name.eq_ignore_ascii_case(name))
|
||||
.ok_or("No player was found")?;
|
||||
(ArgumentValue::Player(found.clone()), rest)
|
||||
}
|
||||
ArgumentKind::BlockPos => {
|
||||
let (x, rest) = coordinate(s, player.x)?;
|
||||
let rest = rest
|
||||
.strip_prefix(' ')
|
||||
.ok_or("Incomplete (expected 3 coordinates)")?;
|
||||
let (y, rest) = coordinate(rest, player.y)?;
|
||||
let rest = rest
|
||||
.strip_prefix(' ')
|
||||
.ok_or("Incomplete (expected 3 coordinates)")?;
|
||||
let (z, rest) = coordinate(rest, player.z)?;
|
||||
(ArgumentValue::BlockPos(BlockPos { x, y, z }), rest)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// StringReader.readInt.
|
||||
fn integer(s: &str) -> Result<(i32, &str), String> {
|
||||
let end = s
|
||||
.find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.'))
|
||||
.unwrap_or(s.len());
|
||||
let (n, rest) = s.split_at(end);
|
||||
if n.is_empty() {
|
||||
return Err("Expected integer".into());
|
||||
}
|
||||
let n = n.parse().map_err(|_| format!("Invalid integer '{n}'"))?;
|
||||
Ok((n, rest))
|
||||
}
|
||||
|
||||
/// StringReader.readDouble.
|
||||
fn double(s: &str) -> Result<(f64, &str), String> {
|
||||
let end = s
|
||||
.find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.'))
|
||||
.unwrap_or(s.len());
|
||||
let (n, rest) = s.split_at(end);
|
||||
if n.is_empty() {
|
||||
return Err("Expected double".into());
|
||||
}
|
||||
let n = n.parse().map_err(|_| format!("Invalid double '{n}'"))?;
|
||||
Ok((n, rest))
|
||||
}
|
||||
|
||||
/// WorldCoordinate.parseInt, then BlockPos.containing: `~` and `~n` from
|
||||
/// `base`, a whole number as it is.
|
||||
fn coordinate(s: &str, base: f64) -> Result<(i32, &str), String> {
|
||||
if s.starts_with('^') {
|
||||
return Err(
|
||||
"Cannot mix world & local coordinates (everything must either use ^ or not)".into(),
|
||||
);
|
||||
}
|
||||
if let Some(offset) = s.strip_prefix('~') {
|
||||
if offset.is_empty() || offset.starts_with(' ') {
|
||||
return Ok((base.floor() as i32, offset));
|
||||
}
|
||||
let (n, rest) = double(offset)?;
|
||||
return Ok(((base + n).floor() as i32, rest));
|
||||
}
|
||||
integer(s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::runtime::GameMode;
|
||||
|
||||
fn player(name: &str) -> ServerPlayer {
|
||||
ServerPlayer {
|
||||
id: format!("id-{name}"),
|
||||
name: name.into(),
|
||||
x: 10.7,
|
||||
y: 64.0,
|
||||
z: -3.2,
|
||||
dimension: "minecraft:overworld".into(),
|
||||
game_mode: GameMode::Survival,
|
||||
health: 20.0,
|
||||
}
|
||||
}
|
||||
fn arg(name: &str, kind: ArgumentKind, optional: bool) -> Argument {
|
||||
Argument {
|
||||
name: name.into(),
|
||||
kind,
|
||||
optional,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_in_order_and_optional_ones_left_out() {
|
||||
let alex = player("Alex");
|
||||
let online = [alex.clone(), player("Steve")];
|
||||
let args = [
|
||||
arg("who", ArgumentKind::Player, false),
|
||||
arg("height", ArgumentKind::Integer((Some(1), Some(64))), true),
|
||||
arg("note", ArgumentKind::Text, true),
|
||||
];
|
||||
let v = parse(&args, "steve 5 hello there", &alex, &online).unwrap();
|
||||
assert_eq!(v[0].0, "who");
|
||||
assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Steve"));
|
||||
assert_eq!(v[1], ("height".into(), ArgumentValue::Integer(5)));
|
||||
assert_eq!(
|
||||
v[2],
|
||||
("note".into(), ArgumentValue::Text("hello there".into()))
|
||||
);
|
||||
let v = parse(&args, "@s", &alex, &online).unwrap();
|
||||
assert_eq!(v.len(), 1);
|
||||
assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Alex"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vanilla_errors() {
|
||||
let alex = player("Alex");
|
||||
let online = [alex.clone()];
|
||||
let height = [arg(
|
||||
"height",
|
||||
ArgumentKind::Integer((Some(1), Some(64))),
|
||||
false,
|
||||
)];
|
||||
let err = |a: &[Argument], s| parse(a, s, &alex, &online).unwrap_err();
|
||||
assert_eq!(
|
||||
err(&height, "0"),
|
||||
"Integer must not be less than 1, found 0"
|
||||
);
|
||||
assert_eq!(
|
||||
err(&height, "65"),
|
||||
"Integer must not be more than 64, found 65"
|
||||
);
|
||||
assert_eq!(err(&height, "x"), "Expected integer");
|
||||
assert_eq!(err(&height, "1.5"), "Invalid integer '1.5'");
|
||||
assert_eq!(
|
||||
err(&height, ""),
|
||||
"Unknown or incomplete command, see below for error"
|
||||
);
|
||||
assert_eq!(err(&height, "3 4"), "Incorrect argument for command");
|
||||
let who = [arg("who", ArgumentKind::Player, false)];
|
||||
assert_eq!(err(&who, "Herobrine"), "No player was found");
|
||||
assert_eq!(err(&who, "@q"), "Unknown selector type '@q'");
|
||||
let flag = [arg("on", ArgumentKind::Boolean, false)];
|
||||
assert_eq!(
|
||||
err(&flag, "yes"),
|
||||
"Invalid boolean, expected 'true' or 'false' but found 'yes'"
|
||||
);
|
||||
let pos = [arg("at", ArgumentKind::BlockPos, false)];
|
||||
assert_eq!(err(&pos, "1 2"), "Incomplete (expected 3 coordinates)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_positions_relative_to_the_player() {
|
||||
let alex = player("Alex");
|
||||
let pos = [arg("at", ArgumentKind::BlockPos, false)];
|
||||
let v = parse(&pos, "~ ~1 ~-0.5", &alex, &[]).unwrap();
|
||||
assert_eq!(
|
||||
v[0].1,
|
||||
ArgumentValue::BlockPos(BlockPos {
|
||||
x: 10,
|
||||
y: 65,
|
||||
z: -4
|
||||
})
|
||||
);
|
||||
let v = parse(&pos, "-5 70 ~", &alex, &[]).unwrap();
|
||||
assert_eq!(
|
||||
v[0].1,
|
||||
ArgumentValue::BlockPos(BlockPos {
|
||||
x: -5,
|
||||
y: 70,
|
||||
z: -4
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_text_is_an_optional_text_argument() {
|
||||
let alex = player("Alex");
|
||||
let free = [arg("args", ArgumentKind::Text, true)];
|
||||
assert_eq!(parse(&free, "", &alex, &[]), Ok(Vec::new()));
|
||||
assert_eq!(
|
||||
parse(&free, "anything at all", &alex, &[]),
|
||||
Ok(vec![(
|
||||
"args".into(),
|
||||
ArgumentValue::Text("anything at all".into())
|
||||
)])
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&[], "more", &alex, &[]),
|
||||
Err("Incorrect argument for command".into())
|
||||
);
|
||||
assert_eq!(parse(&[], "", &alex, &[]), Ok(Vec::new()));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@
|
||||
//! Nothing here runs unless a mod is installed and turned on: an empty
|
||||
//! [`Mods`] makes no engine and every hook returns at once.
|
||||
pub mod api_level;
|
||||
#[cfg(feature = "runtime")]
|
||||
pub mod commands;
|
||||
pub mod content;
|
||||
#[cfg(feature = "index")]
|
||||
pub mod index;
|
||||
|
||||
@@ -52,7 +52,9 @@ use bindings::{
|
||||
horizon::mods::{chat, command, game, hud, log as mod_log, storage},
|
||||
};
|
||||
pub use server_bindings::{
|
||||
exports::horizon::mods::server_events::BlockPos,
|
||||
exports::horizon::mods::server_events::{
|
||||
Argument, ArgumentKind, ArgumentValue, BlockPos, ServerCommand,
|
||||
},
|
||||
horizon::mods::players::{GameMode, Player as ServerPlayer},
|
||||
horizon::mods::world::BlockChange,
|
||||
};
|
||||
@@ -336,10 +338,10 @@ impl Hooks {
|
||||
Hooks::Client(..) => None,
|
||||
}
|
||||
}
|
||||
fn commands(&self) -> &[String] {
|
||||
fn commands(&self) -> Vec<&str> {
|
||||
match self {
|
||||
Hooks::Client(_, r) => &r.commands,
|
||||
Hooks::Server(_, r) => &r.commands,
|
||||
Hooks::Client(_, r) => r.commands.iter().map(String::as_str).collect(),
|
||||
Hooks::Server(_, r) => r.commands.iter().map(|c| c.name.as_str()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -434,9 +436,16 @@ pub struct Mods {
|
||||
snapshot: Arc<Snapshot>,
|
||||
out: Vec<Output>,
|
||||
world: WorldSlot,
|
||||
/// Moves on whenever a mod starts or stops: the game resends the server
|
||||
/// mods' commands to players when it changes.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl Mods {
|
||||
/// Changes whenever the running mods (so their commands) change.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
/// Whether a running mod may use capability `world`: only then is a
|
||||
/// view worth lending.
|
||||
pub fn wants_world(&self) -> bool {
|
||||
@@ -571,7 +580,8 @@ impl Mods {
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref())
|
||||
.filter(|r| r.hooks.server().is_some() == server)
|
||||
.flat_map(|r| r.hooks.commands().iter().cloned())
|
||||
.flat_map(|r| r.hooks.commands())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let snapshot = self.snapshot.clone();
|
||||
let world = self.world.clone();
|
||||
@@ -640,17 +650,30 @@ impl Mods {
|
||||
.map_err(|e| reason(&e))??;
|
||||
(Hooks::Client(exports, r), ui)
|
||||
};
|
||||
let commands = match &mut hooks {
|
||||
Hooks::Client(_, r) => &mut r.commands,
|
||||
Hooks::Server(_, r) => &mut r.commands,
|
||||
};
|
||||
commands.retain(|c| {
|
||||
let free = !reserved(c) && !taken.contains(c);
|
||||
let free = |c: &str| {
|
||||
let free = !reserved(c) && !taken.iter().any(|t| t == c);
|
||||
if !free {
|
||||
log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id);
|
||||
}
|
||||
free
|
||||
});
|
||||
};
|
||||
match &mut hooks {
|
||||
Hooks::Client(_, r) => r.commands.retain(|c| free(c)),
|
||||
Hooks::Server(_, r) => {
|
||||
r.commands.retain(|c| free(&c.name));
|
||||
for c in &mut r.commands {
|
||||
if let Err(e) = check_arguments(&c.arguments) {
|
||||
log::warn!(
|
||||
"Horizon: mod {}'s /{}: {e}; it takes free text",
|
||||
m.id,
|
||||
c.name
|
||||
);
|
||||
c.arguments.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.generation += 1;
|
||||
self.out.append(&mut store.data_mut().out);
|
||||
Ok(Some(Running {
|
||||
store,
|
||||
@@ -768,6 +791,7 @@ impl Mods {
|
||||
});
|
||||
entry.status = Status::Failed(reason);
|
||||
entry.run = None;
|
||||
self.generation += 1;
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -792,7 +816,7 @@ impl Mods {
|
||||
fn command_owner(&self, server: bool, name: &str) -> Option<usize> {
|
||||
self.entries.iter().position(|e| {
|
||||
e.run.as_ref().is_some_and(|r| {
|
||||
r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name)
|
||||
r.hooks.server().is_some() == server && r.hooks.commands().contains(&name)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -825,7 +849,7 @@ impl Mods {
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref())
|
||||
.filter(move |r| r.hooks.server().is_some() == server)
|
||||
.flat_map(|r| r.hooks.commands().iter().map(String::as_str))
|
||||
.flat_map(|r| r.hooks.commands())
|
||||
}
|
||||
|
||||
/// A server tick.
|
||||
@@ -868,9 +892,13 @@ impl Mods {
|
||||
|m, s| m.call_block_placed(s, player, pos, state),
|
||||
);
|
||||
}
|
||||
/// The commands running server mods own, for the server's command tree.
|
||||
pub fn server_commands(&self) -> impl Iterator<Item = &str> {
|
||||
self.owned_commands(true)
|
||||
/// The commands running server mods own and their arguments, for the
|
||||
/// server's command tree.
|
||||
pub fn server_commands(&self) -> impl Iterator<Item = &ServerCommand> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.hooks.server())
|
||||
.flat_map(|r| r.commands.iter())
|
||||
}
|
||||
/// Runs `line` (without its slash), typed by `player`, if a server mod
|
||||
/// owns its command; its feedback is an [`Output::Reply`]. False when
|
||||
@@ -880,18 +908,35 @@ impl Mods {
|
||||
let Some(i) = self.command_owner(true, name) else {
|
||||
return false;
|
||||
};
|
||||
let result = self.call(i, FUEL_EVENT, |run| match &run.hooks {
|
||||
Hooks::Server(m, _) => {
|
||||
m.horizon_mods_server_events()
|
||||
.call_command(&mut run.store, player, name, args)
|
||||
}
|
||||
Hooks::Client(..) => Ok(Ok(None)),
|
||||
});
|
||||
let reply = |text, error| Output::Reply {
|
||||
player: player.id.clone(),
|
||||
text,
|
||||
error,
|
||||
};
|
||||
let arguments = self.entries[i]
|
||||
.run
|
||||
.as_ref()
|
||||
.and_then(|r| r.hooks.server())
|
||||
.and_then(|r| r.commands.iter().find(|c| c.name == name))
|
||||
.map(|c| c.arguments.as_slice())
|
||||
.unwrap_or_default();
|
||||
let values = match crate::commands::parse(arguments, args, player, &self.snapshot.players) {
|
||||
Ok(values) => values,
|
||||
Err(e) => {
|
||||
self.out.push(reply(e, true));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
let result = self.call(i, FUEL_EVENT, |run| match &run.hooks {
|
||||
Hooks::Server(m, _) => m.horizon_mods_server_events().call_command(
|
||||
&mut run.store,
|
||||
player,
|
||||
name,
|
||||
args,
|
||||
&values,
|
||||
),
|
||||
Hooks::Client(..) => Ok(Ok(None)),
|
||||
});
|
||||
match result {
|
||||
Some(Ok(Some(text))) => self.out.push(reply(text, false)),
|
||||
Some(Err(text)) => self.out.push(reply(text, true)),
|
||||
@@ -1217,6 +1262,7 @@ impl Mods {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
self.generation += 1;
|
||||
self.entries[i].modified = now;
|
||||
self.entries[i].run = None;
|
||||
let path = self.entries[i].path.clone();
|
||||
@@ -1242,6 +1288,34 @@ impl Mods {
|
||||
}
|
||||
}
|
||||
|
||||
/// A command's arguments are well formed: names given and distinct,
|
||||
/// optional ones last, free text only last.
|
||||
fn check_arguments(arguments: &[Argument]) -> Result<(), String> {
|
||||
for (i, a) in arguments.iter().enumerate() {
|
||||
if a.name.is_empty()
|
||||
|| !a
|
||||
.name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
{
|
||||
return Err(format!("argument name '{}' isn't [A-Za-z0-9_]+", a.name));
|
||||
}
|
||||
if arguments[..i].iter().any(|b| b.name == a.name) {
|
||||
return Err(format!("two arguments are named {}", a.name));
|
||||
}
|
||||
if i > 0 && arguments[i - 1].optional && !a.optional {
|
||||
return Err(format!("{} is required after an optional argument", a.name));
|
||||
}
|
||||
if a.kind == ArgumentKind::Text && i + 1 < arguments.len() {
|
||||
return Err(format!(
|
||||
"{} takes the rest of the line, so it must be last",
|
||||
a.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn modified(path: &Path) -> Option<SystemTime> {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
if meta.is_dir() {
|
||||
|
||||
@@ -253,7 +253,7 @@ impl TestGame {
|
||||
}
|
||||
/// The commands the mod registered.
|
||||
pub fn commands(&self) -> Vec<String> {
|
||||
let server = self.mods.server_commands();
|
||||
let server = self.mods.server_commands().map(|c| c.name.as_str());
|
||||
self.mods
|
||||
.commands()
|
||||
.chain(server)
|
||||
|
||||
@@ -900,7 +900,7 @@ fn a_server_mod_without_a_world_reads_nothing() {
|
||||
assert!(
|
||||
out.iter()
|
||||
.any(|o| matches!(o, Output::Reply { text, error: true, .. }
|
||||
if text == "The ground under you isn't loaded")),
|
||||
if text == "That block isn't loaded")),
|
||||
"{out:?}"
|
||||
);
|
||||
}
|
||||
@@ -999,10 +999,12 @@ fn a_server_mod_runs_only_where_the_world_does() {
|
||||
|
||||
let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give");
|
||||
assert!(mods.runs_server());
|
||||
assert_eq!(
|
||||
mods.server_commands().collect::<Vec<_>>(),
|
||||
["online", "mined"]
|
||||
);
|
||||
let commands: Vec<_> = mods.server_commands().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(commands, ["online", "mined"]);
|
||||
// `/mined [player]`: its argument travels with it, for the command tree.
|
||||
let mined = mods.server_commands().nth(1).unwrap();
|
||||
assert_eq!(mined.arguments[0].kind, horizon_mods::ArgumentKind::Player);
|
||||
assert!(mined.arguments[0].optional);
|
||||
assert_eq!(mods.commands().count(), 0, "not the window's chat commands");
|
||||
let alex = alex();
|
||||
mods.set_snapshot(Snapshot {
|
||||
|
||||
+54
-11
@@ -689,16 +689,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On
|
||||
|
||||
`type player = player`
|
||||
|
||||
### record `registration`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `commands` | `list<string>` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). |
|
||||
| `tick` | `bool` | Call `tick` every server tick (20 per second). |
|
||||
| `joins` | `bool` | Call `player-joined` and `player-left`. |
|
||||
| `chat` | `bool` | Call `chat` for each chat message a player sends. |
|
||||
| `blocks` | `bool` | Call `block-broken` and `block-placed`. |
|
||||
|
||||
### record `block-pos`
|
||||
|
||||
| Field | Type | |
|
||||
@@ -707,6 +697,59 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On
|
||||
| `y` | `s32` | |
|
||||
| `z` | `s32` | |
|
||||
|
||||
### variant `argument-kind`
|
||||
|
||||
What an argument of a command takes. The server sends each command and its arguments to players' games, whose chat box completes and colours them as vanilla's; the server parses them before the mod's `command` hook gets their values.
|
||||
|
||||
| Case | Payload | |
|
||||
| --- | --- | --- |
|
||||
| `word` | | One word: letters, digits and `_ - . +`. |
|
||||
| `text` | | The rest of the line, spaces included: only last. |
|
||||
| `integer` | `tuple<option<s32>, option<s32>>` | A whole number, within the bounds given. |
|
||||
| `number` | | A number with or without decimals. |
|
||||
| `boolean` | | `true` or `false`. |
|
||||
| `player` | | One online player: a name, or `@s` or `@p` (whoever typed it, as vanilla picks for a player). |
|
||||
| `block-pos` | | A block position: three whole numbers, each one also `~` or `~n`, relative to whoever typed it. |
|
||||
|
||||
### record `argument`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `name` | `string` | Shown in the chat box's hint (`<height>`) and the key of its value. |
|
||||
| `kind` | `argument-kind` | |
|
||||
| `optional` | `bool` | Optional arguments come after every required one. |
|
||||
|
||||
### record `server-command`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `name` | `string` | Without the slash. A name vanilla already uses is refused (vanilla's command runs). |
|
||||
| `arguments` | `list<argument>` | In order; none: the command takes nothing after its name. Free text is one optional `text` argument. |
|
||||
|
||||
### variant `argument-value`
|
||||
|
||||
An argument's value, parsed as its kind says.
|
||||
|
||||
| Case | Payload | |
|
||||
| --- | --- | --- |
|
||||
| `word` | `string` | |
|
||||
| `text` | `string` | |
|
||||
| `integer` | `s32` | |
|
||||
| `number` | `f64` | |
|
||||
| `boolean` | `bool` | |
|
||||
| `player` | `player` | |
|
||||
| `block-pos` | `block-pos` | |
|
||||
|
||||
### record `registration`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `commands` | `list<server-command>` | Commands players may type. |
|
||||
| `tick` | `bool` | Call `tick` every server tick (20 per second). |
|
||||
| `joins` | `bool` | Call `player-joined` and `player-left`. |
|
||||
| `chat` | `bool` | Call `chat` for each chat message a player sends. |
|
||||
| `blocks` | `bool` | Call `block-broken` and `block-placed`. |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `init` | `func() -> result<registration, string>` | Once, after loading. An error keeps the mod off and is logged. |
|
||||
@@ -714,6 +757,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On
|
||||
| `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. |
|
||||
| `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. |
|
||||
| `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. |
|
||||
| `command` | `func(player: player, name: string, args: string) -> result<option<string>, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. |
|
||||
| `command` | `func(player: player, name: string, args: string, values: list<tuple<string, argument-value>>) -> result<option<string>, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. `values` holds each argument given, by name, in order (an optional one left out isn't there); a line that doesn't parse never reaches the mod: the player gets vanilla's error. |
|
||||
| `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. |
|
||||
| `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. |
|
||||
|
||||
+7
-4
@@ -18,7 +18,7 @@ the player before the mod is turned on, and checked against the component's real
|
||||
| Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` |
|
||||
| Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` |
|
||||
| Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) |
|
||||
| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` |
|
||||
| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (6 builders), `server::Argument`, `server::Args`, `export_server_mod!` |
|
||||
| `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `test`, `check` |
|
||||
| Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) |
|
||||
|
||||
@@ -88,9 +88,9 @@ release.
|
||||
What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
- **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run
|
||||
on the server thread, a LAN host and the dedicated server today, with joins, chat, commands, players' block
|
||||
breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` does); next entity events, game rules,
|
||||
server commands with typed arguments sent to clients' command trees.
|
||||
on the server thread, a LAN host and the dedicated server today, with joins, chat, typed commands in players'
|
||||
command trees, players' block breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock`
|
||||
does); next entity events, game rules, entity, item and block-state arguments.
|
||||
- **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities,
|
||||
and `world` for client mods (raycasts, single player and LAN hosts).
|
||||
- **Items and inventories**: the player's inventory, held item and open container; item stacks with components.
|
||||
@@ -106,6 +106,9 @@ What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
## Changelog
|
||||
|
||||
- API 0.3: typed server commands: `registration.commands` lists each command's arguments (`argument-kind`: word,
|
||||
text, integer, number, boolean, player, block-pos), sent in players' command trees and parsed by the server;
|
||||
`command` gets their values. SDK `Registration::command_with`, `Argument`, `Args`.
|
||||
- API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and
|
||||
`expect.blocks`.
|
||||
- Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server.
|
||||
|
||||
@@ -108,7 +108,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel
|
||||
| Mod API: `render` (HUD shapes, camera shake and zoom; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` |
|
||||
| Mod API: `input` (claimed items' use, the mod's keys, the mouse wheel) | experimental | manifest `experimental = ["input"]` |
|
||||
| Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` |
|
||||
| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` |
|
||||
| Server mods: world `horizon-server-mod`, `players`, `server-events`, `world`, typed `server-command`s | experimental | manifest `api = "0.3"` |
|
||||
| Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | |
|
||||
| `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 |
|
||||
| Shader API | not started | |
|
||||
|
||||
+31
-5
@@ -488,7 +488,7 @@ its component targets the WIT world `horizon-server-mod` instead of
|
||||
| `tick(tick)` | each server tick |
|
||||
| `player-joined(player)`, `player-left(player)` | `registration.joins` |
|
||||
| `chat(player, text)` | `registration.chat`: each chat message a player sends |
|
||||
| `command(player, name, args)` | `/name args` typed by a player, for a command it registered; `ok(some)` is that player's feedback, `err` their red error |
|
||||
| `command(player, name, args, values)` | `/name args` typed by a player, for a command it registered, with its arguments' values (below); `ok(some)` is that player's feedback, `err` their red error |
|
||||
| `block-broken(player, pos, state)`, `block-placed(player, pos, state)` | `registration.blocks`, with the state as `minecraft:oak_log[axis=y]` |
|
||||
|
||||
Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for
|
||||
@@ -497,6 +497,31 @@ horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is
|
||||
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with
|
||||
`world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs).
|
||||
|
||||
**Typed commands.** Each command in `registration.commands` lists its
|
||||
arguments, in order: a name and a kind, required or optional (optional ones
|
||||
last). The server adds them to the command tree every player receives, after
|
||||
vanilla's commands, so a player's chat box completes and colours them as it
|
||||
does vanilla's (player names, coordinates, bounds); when a player sends one,
|
||||
the server parses the line the way vanilla's parsers do and gives the mod the
|
||||
values, by argument name, or answers with vanilla's error (`Integer must not
|
||||
be more than 64, found 65`, `No player was found`) without calling the mod.
|
||||
|
||||
| Kind | Takes | Value | Chat box parser |
|
||||
|---|---|---|---|
|
||||
| `word` | one word: letters, digits, `_ - . +` | `word(string)` | `brigadier:string` (word) |
|
||||
| `text` | the rest of the line, only last | `text(string)` | `brigadier:string` (greedy) |
|
||||
| `integer(min, max)` | a whole number within the bounds given | `integer(s32)` | `brigadier:integer` |
|
||||
| `number` | a number | `number(f64)` | `brigadier:double` |
|
||||
| `boolean` | `true` or `false` | `boolean(bool)` | `brigadier:bool` |
|
||||
| `player` | an online player's name, `@s` or `@p` (whoever typed it) | `player(player)` | `minecraft:entity` (one player) |
|
||||
| `block-pos` | `x y z`, each a whole number, `~` or `~n` (from whoever typed it) | `block-pos(block-pos)` | `minecraft:block_pos` |
|
||||
|
||||
A command with no arguments takes nothing after its name. In Rust,
|
||||
`Registration::command_with("beacon", [Argument::integer("height", Some(1),
|
||||
Some(64)).optional()])`, read with `args.integer("height")`; `command(name)`
|
||||
alone takes free text, an optional `text` argument named `args`
|
||||
(`args.text()` is the line as typed either way).
|
||||
|
||||
**Capability `world`.** Reads are of the server's loaded chunks as they are
|
||||
during the call: the game lends a server mod's call the levels' chunk maps
|
||||
(moved, not copied, and only while a running mod has `world`), so a read
|
||||
@@ -537,10 +562,11 @@ chat for the in-frame player and a system message for a connection;
|
||||
on, each of these points costs one branch (measured in the PR that added
|
||||
them).
|
||||
|
||||
**Not yet.** Clients aren't sent server mods' commands with vanilla's
|
||||
command tree, so a player's chat box doesn't complete or colour them; typing
|
||||
them works. Block events are a player's own breaking and placing, not
|
||||
explosions, pistons or other mods.
|
||||
**Not yet.** Block events are a player's own breaking and placing, not
|
||||
explosions, pistons or other mods. Command arguments don't take entities,
|
||||
items or block states yet, and `^` coordinates; in-frame single player's chat
|
||||
box lists server mods' commands by name only (the server still parses their
|
||||
arguments).
|
||||
|
||||
## Publish your mod
|
||||
|
||||
|
||||
Reference in New Issue
Block a user