Add mod command capability and Predator Missile example

This commit is contained in:
Simon Dräger
2026-10-24 13:21:23 -07:00
parent fe128948ba
commit d4b2e24535
14 changed files with 300 additions and 12 deletions
+1 -1
View File
@@ -80,7 +80,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it.
- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`).
- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest`.
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude predator-missile --exclude horizon-mods-test-guest`.
Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`).
- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build).
- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game):
Generated
+7
View File
@@ -2620,6 +2620,13 @@ dependencies = [
"zerovec",
]
[[package]]
name = "predator-missile"
version = "0.1.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "presser"
version = "0.3.1"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "xtask"]
resolver = "2"
[workspace.package]
+13
View File
@@ -342,6 +342,19 @@ impl Game<'_> {
}
Output::Feedback { text, error: false } => Text::literal(text),
Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED),
// Vanilla's commands only: a mod running a mod command could loop.
Output::Command { line } => {
let name = line.split(' ').next().unwrap_or_default();
// As handle_chat_input, without the chat history.
if !vanilla_command(name) {
// dropped
} else if self.remote.is_some() {
self.send_chat(&format!("/{line}"));
} else {
self.run_command(&line);
}
continue;
}
Output::Stopped { name, reason } => {
self.list_mods();
self.sync_mod_commands();
@@ -0,0 +1,16 @@
[package]
name = "predator-missile"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish = false
description = "Example Horizon mod: a missile you launch with /missile and steer with the mouse"
[lib]
crate-type = ["cdylib"]
[dependencies]
horizon-mod-sdk = { path = "../.." }
[lints]
workspace = true
@@ -0,0 +1,8 @@
id = "predator_missile"
name = "Predator Missile"
version = "0.1.0"
description = "/missile launches a guided missile 60 blocks above you. Steer it with the mouse; it explodes on whatever it hits. Needs cheats (it runs vanilla commands as you)."
authors = ["Horizon"]
api = "0.1"
side = "client"
capabilities = ["game-read", "hud", "chat", "command"]
@@ -0,0 +1,161 @@
//! Example Horizon mod (`docs/mods.md`): `/missile` turns you into a guided
//! missile 60 blocks up. You fly along your own look, so the mouse steers;
//! on a block or a mob a stack of primed TNT goes off, and you are put back
//! where you launched. Built from vanilla commands (capability `command`),
//! so it needs cheats.
use horizon_mod_sdk::{
Mod, Registration,
command::run,
game::{self, Player},
hud::{self, Corner, Line},
};
/// Blocks per tick (a fired arrow does about 3).
const SPEED: f64 = 1.5;
const ALTITUDE: i32 = 60;
/// Ticks of flight before the missile detonates on its own.
const FUEL: u32 = 30 * 20;
/// Ticks to watch the blast before going back.
const AFTERMATH: u32 = 40;
/// Primed TNT per blast: the stack's explosions add up.
const WARHEAD: usize = 4;
/// What the impact checks print; the mod hears it through the chat hook.
const IMPACT: &str = "Predator: impact";
enum State {
Idle,
Flying { from: Player, ticks: u32 },
Aftermath { from: Player, ticks: u32 },
}
struct Predator {
state: State,
}
fn launch() {
run("gamerule send_command_feedback false");
run("execute if entity @s[gamemode=creative] run tag @s add pm_creative");
run("gamemode spectator");
run(&format!("tp @s ~ ~{ALTITUDE} ~ ~ 60"));
run("effect give @s night_vision 60 0 true");
// The thermal camera: every mob outlined.
run("effect give @e[type=!player,distance=..256] glowing 60 0 true");
}
/// One tick of flight: stop at the surface (the next step would enter a
/// block or a mob), else move one step along the look.
fn fly() {
run(&format!(
"execute at @s unless block ^ ^ ^{SPEED} #minecraft:air run tellraw @s \"{IMPACT}\""
));
run(&format!(
"execute at @s positioned ^ ^ ^{SPEED} if entity @e[type=!player,distance=..2] run tellraw @s \"{IMPACT}\""
));
run(&format!(
"execute at @s if block ^ ^ ^{SPEED} #minecraft:air run tp @s ^ ^ ^{SPEED}"
));
}
fn detonate() {
for _ in 0..WARHEAD {
run("execute at @s run summon tnt ^ ^ ^1 {fuse:0s}");
}
}
fn land(from: &Player) {
run(&format!(
"tp @s {} {} {} {} {}",
from.x, from.y, from.z, from.yaw, from.pitch
));
run("execute if entity @s[tag=pm_creative] run gamemode creative");
run("execute unless entity @s[tag=pm_creative] run gamemode survival");
run("execute if entity @s[tag=pm_creative] run tag @s remove pm_creative");
run("effect clear @s night_vision");
// shortcut: assumes feedback was on before launch, as in a new world.
run("gamerule send_command_feedback true");
}
fn panel(p: &Player, ticks: u32) -> Vec<Line> {
let green = 0x7CFF7C;
let left = (FUEL - ticks.min(FUEL)) / 20;
[
"PREDATOR".to_string(),
format!("ALT {:.0}", p.y),
format!("FUEL {left}s"),
"Mouse to steer, /missile to detonate".to_string(),
]
.into_iter()
.map(|text| Line { text, color: green })
.collect()
}
impl Predator {
fn impact(&mut self) {
if let State::Flying { from, .. } = &self.state {
detonate();
self.state = State::Aftermath {
from: from.clone(),
ticks: 0,
};
}
}
}
impl Mod for Predator {
fn init() -> Result<(Self, Registration), String> {
let hooks = Registration::new().command("missile").on_tick().on_chat();
Ok((Predator { state: State::Idle }, hooks))
}
fn tick(&mut self, _tick: u64) {
match &mut self.state {
State::Idle => {}
State::Flying { ticks, .. } => {
*ticks += 1;
let ticks = *ticks;
if ticks >= FUEL {
return self.impact();
}
// The first tick waits for the launch teleport.
if ticks > 1 {
fly();
}
if let Some(p) = game::get_player() {
hud::set_panel(Corner::TopLeft, &panel(&p, ticks));
}
}
State::Aftermath { from, ticks } => {
*ticks += 1;
if *ticks >= AFTERMATH {
land(from);
hud::clear();
self.state = State::Idle;
}
}
}
}
fn chat(&mut self, text: &str) {
if text.contains(IMPACT) {
self.impact();
}
}
fn command(&mut self, _name: &str, _args: &str) -> Result<Option<String>, String> {
match self.state {
State::Idle => {
let from = game::get_player().ok_or("Not in a world")?;
launch();
self.state = State::Flying { from, ticks: 0 };
Ok(Some("Missile away".into()))
}
State::Flying { .. } => {
self.impact();
Ok(None)
}
State::Aftermath { .. } => Err("Wait for the blast to clear".into()),
}
}
}
horizon_mod_sdk::export_mod!(Predator);
+2 -2
View File
@@ -21,7 +21,7 @@
//! ```
//!
//! Every interface but `log` is a capability: list the ones the mod uses in
//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`).
//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`, `command`).
wit_bindgen::generate!({
path: "wit",
@@ -32,7 +32,7 @@ wit_bindgen::generate!({
});
pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
pub use horizon::mods::{chat, game, hud, log, storage};
pub use horizon::mods::{chat, command, game, hud, log, storage};
/// The game's calls into a mod. Only the hooks [`Registration`] asks for
/// are called; the others may stay as their defaults.
+9
View File
@@ -86,6 +86,14 @@ interface storage {
delete: func(key: string);
}
/// Capability `command`: vanilla commands run as the player, with the
/// player's permissions, after the hook call returns (8 per call). A mod's
/// own commands are not run this way.
interface command {
/// `line` without its slash; its feedback goes to the chat as if typed.
run: func(line: string);
}
/// What the game calls. Only the hooks `init` asks for are ever called.
interface events {
record registration {
@@ -117,5 +125,6 @@ world horizon-mod {
import chat;
import hud;
import storage;
import command;
export events;
}
+11 -1
View File
@@ -69,16 +69,19 @@ pub enum Capability {
Chat,
Hud,
Storage,
/// Runs vanilla commands as the player, with the player's permissions.
Command,
/// New blocks and items from the mod's `data/` (API 0.2): no WIT
/// interface, the game reads them before the world loads.
Registries,
}
impl Capability {
pub const ALL: [Capability; 5] = [
pub const ALL: [Capability; 6] = [
Capability::GameRead,
Capability::Chat,
Capability::Hud,
Capability::Storage,
Capability::Command,
Capability::Registries,
];
/// The WIT interface it grants, in `horizon:mods`.
@@ -88,6 +91,7 @@ impl Capability {
Capability::Chat => "chat",
Capability::Hud => "hud",
Capability::Storage => "storage",
Capability::Command => "command",
Capability::Registries => "registries",
}
}
@@ -98,6 +102,7 @@ impl Capability {
Capability::Chat => "show you chat messages",
Capability::Hud => "draw text on your screen",
Capability::Storage => "save its own settings to disk",
Capability::Command => "run commands as you, with your permissions",
Capability::Registries => "add blocks and items to your worlds",
}
}
@@ -128,6 +133,7 @@ impl fmt::Display for Capability {
Capability::Chat => "chat",
Capability::Hud => "hud",
Capability::Storage => "storage",
Capability::Command => "command",
Capability::Registries => "registries",
};
f.write_str(name)
@@ -366,6 +372,10 @@ capabilities = ["game-read", "hud"]
storage,
Err("uses capability storage, missing from horizon-mod.toml".into())
);
assert_eq!(
m.check_imports(["horizon:mods/command@0.1.0"]),
Err("uses capability command, missing from horizon-mod.toml".into())
);
let with_storage = EXAMPLE.replace("\"hud\"", "\"hud\", \"storage\"");
let m = Manifest::parse(&with_storage).unwrap();
assert_eq!(m.check_imports(["horizon:mods/storage@0.1.0"]), Ok(()));
+16 -1
View File
@@ -23,7 +23,7 @@ pub use bindings::horizon::mods::{
use bindings::{
HorizonMod,
exports::horizon::mods::events::Registration,
horizon::mods::{chat, game, hud, log as mod_log, storage},
horizon::mods::{chat, command, game, hud, log as mod_log, storage},
};
/// A mod's linear memory cap.
@@ -67,6 +67,9 @@ pub enum Output {
Chat { name: String, text: String },
/// A mod command's feedback, red when `error`.
Feedback { text: String, error: bool },
/// `command.run`: a vanilla command line, without its slash, to run as
/// the player.
Command { line: String },
/// The mod was turned off: it trapped, overran or failed to start.
Stopped { name: String, reason: String },
}
@@ -514,6 +517,18 @@ impl chat::Host for State {
}
}
}
impl command::Host for State {
fn run(&mut self, line: String) {
let queued = self
.out
.iter()
.filter(|o| matches!(o, Output::Command { .. }))
.count();
if queued < CHAT_PER_CALL {
self.out.push(Output::Command { line: clip(line) });
}
}
}
impl hud::Host for State {
fn set_panel(&mut self, corner: Corner, lines: Vec<Line>) {
let lines = lines
+41 -4
View File
@@ -1,4 +1,5 @@
//! Loads real mods built with the SDK: the coords-hud example and a guest
//! Loads real mods built with the SDK: the coords-hud and predator-missile
//! examples and a guest
//! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`.
use horizon_mods::{
Clock, Corner, Mods, Output, Package, Player, Snapshot, Status, manifest::componentize,
@@ -18,7 +19,7 @@ api = "0.1"
capabilities = ["chat", "storage"]
"#;
/// Builds both mods once and writes their `.hmod` files; returns the folder.
/// Builds the mods once and writes their `.hmod` files; returns the folder.
fn mods_dir() -> &'static Path {
static DIR: OnceLock<PathBuf> = OnceLock::new();
DIR.get_or_init(|| {
@@ -31,6 +32,8 @@ fn mods_dir() -> &'static Path {
"-p",
"coords-hud",
"-p",
"predator-missile",
"-p",
"horizon-mods-test-guest",
"--target-dir",
])
@@ -44,9 +47,13 @@ fn mods_dir() -> &'static Path {
let built = target.join("wasm32-unknown-unknown/release");
let dir = target.join("mods");
std::fs::create_dir_all(&dir).unwrap();
let example = root.join("crates/horizon-mod-sdk/examples/coords-hud/horizon-mod.toml");
let example = |name: &str| {
let path = format!("crates/horizon-mod-sdk/examples/{name}/horizon-mod.toml");
std::fs::read_to_string(root.join(path)).unwrap()
};
let mods = [
("coords_hud", std::fs::read_to_string(example).unwrap()),
("coords_hud", example("coords-hud")),
("predator_missile", example("predator-missile")),
("horizon_mods_test_guest", GUEST_MANIFEST.to_string()),
];
for (name, manifest) in mods {
@@ -81,6 +88,36 @@ fn player() -> Snapshot {
}
}
/// Capability `command`: `/missile` queues vanilla commands, and the chat
/// line its impact check prints sets off the warhead.
#[test]
fn predator_missile_runs_commands() {
let mut mods = load("predator_missile.hmod");
assert_eq!(mods.entries()[0].status, Status::Running);
mods.set_snapshot(player());
let commands = |mods: &mut Mods| -> Vec<String> {
mods.drain()
.into_iter()
.filter_map(|o| match o {
Output::Command { line } => Some(line),
_ => None,
})
.collect()
};
assert!(mods.command("missile"));
let launch = commands(&mut mods);
assert_eq!(launch.len(), 6);
assert!(launch.contains(&"gamemode spectator".to_string()));
mods.tick(1);
mods.tick(2);
let flight = commands(&mut mods);
assert!(flight.iter().any(|l| l.ends_with("run tp @s ^ ^ ^1.5")));
mods.chat("Predator: impact");
let blast = commands(&mut mods);
assert_eq!(blast.len(), 4);
assert!(blast.iter().all(|l| l.contains("summon tnt")));
}
#[test]
fn coords_hud_draws_and_answers() {
let mut mods = load("coords_hud.hmod");
+12 -1
View File
@@ -11,11 +11,12 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
| `chat` | [`chat`](#chat) | show you chat messages |
| `hud` | [`hud`](#hud) | draw text on your screen |
| `storage` | [`storage`](#storage) | save its own settings to disk |
| `command` | [`command`](#command) | run commands as you, with your permissions |
| `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds |
## World `horizon-mod`
- Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage`
- Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage`, `command`
- Exports (what the mod provides): `events`
## `log`
@@ -117,6 +118,16 @@ Capability `storage`: a per-mod folder of small key/value files, quota'd (docs/m
| `set` | `func(key: string, value: list<u8>) -> result<_, string>` | Errs on a malformed key or over quota (bytes for the whole mod). |
| `delete` | `func(key: string)` | No error if `key` was already absent. |
## `command`
Access: capability `command`.
Capability `command`: vanilla commands run as the player, with the player's permissions, after the hook call returns (8 per call). A mod's own commands are not run this way.
| Function | Signature | What it does |
| --- | --- | --- |
| `run` | `func(line: string)` | `line` without its slash; its feedback goes to the chat as if typed. |
## `events`
Access: exported by the mod: the game calls it.
+2 -1
View File
@@ -13,7 +13,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
|---|---|---|
| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage; tick, frame, chat and command hooks |
| SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 |
| Example mod | `crates/horizon-mod-sdk/examples/coords-hud` | coordinates, facing and time HUD, `/where`, `/coords` |
| Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands |
| Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model |
| Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new / build / run` |
| In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods |
@@ -84,6 +84,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
| `chat` | `chat` | `show(text)`: a line only the local player sees, after the mod's name (8 per call) |
| `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters |
| `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call |
| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run |
| Hook (export) | When |
|---|---|