Merge pull request #327 from ludovic111/feat/mod-sdk

Horizon mod SDK: the WIT contract, a Rust SDK and an example mod
This commit is contained in:
Ludovic Marie
2026-10-15 18:02:34 +02:00
committed by GitHub
8 changed files with 573 additions and 1 deletions
Generated
+173
View File
@@ -118,6 +118,12 @@ dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arbitrary"
version = "1.5.0"
@@ -415,6 +421,13 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "coords-hud"
version = "0.1.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -959,6 +972,12 @@ dependencies = [
"foldhash 0.2.0",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.3"
@@ -1060,6 +1079,13 @@ dependencies = [
"spake2",
]
[[package]]
name = "horizon-mod-sdk"
version = "0.1.0"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "horizon-prepare"
version = "0.1.0"
@@ -1224,6 +1250,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "idna"
version = "1.1.0"
@@ -1263,6 +1295,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
"serde",
"serde_core",
]
[[package]]
@@ -1401,6 +1435,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libc"
version = "0.2.190"
@@ -2218,6 +2258,16 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -3011,6 +3061,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -3167,6 +3223,40 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-encoder"
version = "0.247.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30b6733b8b91d010a6ac5b0fb237dc46a19650bc4c67db66857e2e787d437204"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.247.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "665fe59e56cc9b419ca6fcca56673e3421d1a5011e3b65caf6b726fd9e041d10"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.247.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e6fb4c2bee46c5ea4d40f8cdb5c131725cd976718ec56f1c8e82fbde5fa2a80"
dependencies = [
"bitflags 2.13.2",
"hashbrown 0.17.1",
"indexmap",
"semver",
]
[[package]]
name = "wayland-backend"
version = "0.3.17"
@@ -3844,6 +3934,89 @@ name = "wit-bindgen"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
dependencies = [
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02dee27a2dc20d1008016c742ec9fc6ea498492994ba3750be7454cbc97ff04c"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5007dae772945b7a5003d69d90a3a4a78929d41f19d004e980c4259a6af4484"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn 2.0.119",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af9237d678e3513ad24e96fe98beacdc0db6405284ba2a2400418cf0d42caa89"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn 2.0.119",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.247.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d567162a6b9843080e5e0053f696623ff694bae8ae017c9ec536d1873bbe3d8"
dependencies = [
"anyhow",
"bitflags 2.13.2",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.247.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ffe4064318cdf3c08cb99343b44c039fcefe61ccdf58aa9975285f13d74d1fc"
dependencies = [
"anyhow",
"hashbrown 0.17.1",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "wl-clipboard-rs"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server"]
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "xtask"]
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "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-mod-sdk/examples/coords-hud", "xtask"]
resolver = "2"
[workspace.package]
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "horizon-mod-sdk"
version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.85"
description = "Write Horizon mods in Rust: WebAssembly components for the horizon:mod world (docs/mods.md)"
[dependencies]
wit-bindgen = { version = "0.57.1", default-features = false, features = ["macros", "realloc"] }
[lints]
workspace = true
@@ -0,0 +1,16 @@
[package]
name = "coords-hud"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish = false
description = "Example Horizon mod: coordinates, facing and the time of day on the HUD, and /where"
[lib]
crate-type = ["cdylib"]
[dependencies]
horizon-mod-sdk = { path = "../.." }
[lints]
workspace = true
@@ -0,0 +1,8 @@
id = "coords_hud"
name = "Coordinates HUD"
version = "0.1.0"
description = "Your coordinates, facing and the time of day in a corner of the screen. /where puts them in chat, /coords hides or shows the panel."
authors = ["Horizon"]
api = "0.1"
side = "client"
capabilities = ["game-read", "hud", "chat"]
@@ -0,0 +1,124 @@
//! Example Horizon mod (`docs/mods.md`): coordinates, facing and the time of
//! day in the top-left corner, `/where` to put them in chat and `/coords`
//! to hide or show the panel.
use horizon_mod_sdk::{
Mod, Registration, chat,
game::{self, Clock, Player},
hud::{self, Corner, Line},
};
struct CoordsHud {
shown: bool,
/// The panel last sent, so an unchanged one costs no call.
last: Vec<String>,
}
/// Direction.fromYRot: yaw 0 faces south, 90 west.
fn facing(yaw: f32) -> &'static str {
let i = (yaw / 90.0 + 0.5).floor() as i32 & 3;
["South (+Z)", "West (-X)", "North (-Z)", "East (+X)"][i as usize]
}
/// `Day 3, 14:05`: day time 0 is 6:00 on day 1.
fn time_of_day(clock: &Clock) -> String {
let day = clock.day_time / 24000 + 1;
let ticks = clock.day_time % 24000;
let hours = (ticks / 1000 + 6) % 24;
let minutes = ticks % 1000 * 60 / 1000;
format!("Day {day}, {hours:02}:{minutes:02}")
}
fn lines(p: &Player, clock: Option<&Clock>) -> Vec<String> {
let mut lines = vec![
format!("XYZ {:.1} / {:.1} / {:.1}", p.x, p.y, p.z),
format!("Facing {}", facing(p.yaw)),
];
lines.extend(clock.map(time_of_day));
lines
}
impl Mod for CoordsHud {
fn init() -> Result<(Self, Registration), String> {
let hooks = Registration::new()
.command("where")
.command("coords")
.on_tick();
let state = CoordsHud {
shown: true,
last: Vec::new(),
};
Ok((state, hooks))
}
fn tick(&mut self, _tick: u64) {
let Some(p) = game::get_player().filter(|_| self.shown) else {
if !self.last.is_empty() {
hud::clear();
self.last.clear();
}
return;
};
let now = lines(&p, game::get_clock().as_ref());
if now != self.last {
let panel: Vec<Line> = now
.iter()
.map(|text| Line {
text: text.clone(),
color: 0xFFFFFF,
})
.collect();
hud::set_panel(Corner::TopLeft, &panel);
self.last = now;
}
}
fn command(&mut self, name: &str, _args: &str) -> Result<Option<String>, String> {
match name {
"coords" => {
self.shown = !self.shown;
let state = if self.shown { "shown" } else { "hidden" };
Ok(Some(format!("Coordinates panel {state}")))
}
_ => {
let p = game::get_player().ok_or("Not in a world")?;
chat::show(&format!(
"{:.0}, {:.0}, {:.0} in {}",
p.x.floor(),
p.y.floor(),
p.z.floor(),
p.dimension
));
Ok(None)
}
}
}
}
horizon_mod_sdk::export_mod!(CoordsHud);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn facing_follows_vanilla_yaw() {
assert_eq!(facing(0.0), "South (+Z)");
assert_eq!(facing(90.0), "West (-X)");
assert_eq!(facing(-180.0), "North (-Z)");
assert_eq!(facing(-90.0), "East (+X)");
assert_eq!(facing(314.0), "East (+X)");
}
#[test]
fn day_time_reads_as_a_clock() {
let at = |day_time| {
time_of_day(&Clock {
game_time: 0,
day_time,
})
};
assert_eq!(at(0), "Day 1, 06:00");
assert_eq!(at(18000), "Day 1, 00:00");
assert_eq!(at(24000 * 2 + 8083), "Day 3, 14:04");
}
}
+141
View File
@@ -0,0 +1,141 @@
//! Write Horizon mods in Rust (`docs/mods.md`).
//!
//! A mod is a type implementing [`Mod`], exported with [`export_mod!`] from
//! a `cdylib` crate built for `wasm32-unknown-unknown`;
//! `cargo horizon-mod build` turns it into the component the game loads.
//!
//! ```ignore
//! use horizon_mod_sdk::{Mod, Registration, chat};
//!
//! struct Hello;
//! impl Mod for Hello {
//! fn init() -> Result<(Self, Registration), String> {
//! Ok((Hello, Registration::new().command("hello")))
//! }
//! fn command(&mut self, _name: &str, _args: &str) -> Result<Option<String>, String> {
//! chat::show("Hello from a mod!");
//! Ok(None)
//! }
//! }
//! horizon_mod_sdk::export_mod!(Hello);
//! ```
//!
//! Every interface but `log` is a capability: list the ones the mod uses in
//! `horizon-mod.toml` (`game-read`, `chat`, `hud`).
wit_bindgen::generate!({
path: "wit",
world: "horizon-mod",
pub_export_macro: true,
export_macro_name: "__export_horizon_mod",
default_bindings_module: "horizon_mod_sdk",
});
pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
pub use horizon::mods::{chat, game, hud, log};
/// The game's calls into a mod. Only the hooks [`Registration`] asks for
/// are called; the others may stay as their defaults.
pub trait Mod: Sized + 'static {
/// Once, after loading: the mod's state and the hooks it wants. An error
/// keeps the mod off and is shown to the player.
fn init() -> Result<(Self, Registration), String>;
/// Every game tick, when [`Registration::tick`] is set.
fn tick(&mut self, _tick: u64) {}
/// Every rendered frame, when [`Registration::frame`] is set.
fn frame(&mut self, _seconds: f32) {}
/// `/name args` for a command the mod registered. `Ok(Some(text))` is
/// shown as feedback, `Err(text)` in red.
fn command(&mut self, _name: &str, _args: &str) -> Result<Option<String>, String> {
Err("This command does nothing".into())
}
/// A chat line the player received, when [`Registration::chat`] is set.
fn chat(&mut self, _text: &str) {}
}
impl Registration {
/// No commands and no hooks.
pub fn new() -> Self {
Self {
commands: Vec::new(),
tick: false,
frame: false,
chat: false,
}
}
/// Adds `/name`.
pub fn command(mut self, name: &str) -> Self {
self.commands.push(name.into());
self
}
pub fn on_tick(mut self) -> Self {
self.tick = true;
self
}
pub fn on_frame(mut self) -> Self {
self.frame = true;
self
}
pub fn on_chat(mut self) -> Self {
self.chat = true;
self
}
}
impl Default for Registration {
fn default() -> Self {
Self::new()
}
}
/// `log::write` at info level.
pub fn info(message: &str) {
log::write(log::Level::Info, message);
}
/// `log::write` at warn level.
pub fn warn(message: &str) {
log::write(log::Level::Warn, message);
}
/// Exports a [`Mod`] as the component's `events` interface. The state lives
/// in a thread local: a mod instance is single-threaded.
#[macro_export]
macro_rules! export_mod {
($t:ty) => {
const _: () = {
use ::std::cell::RefCell;
::std::thread_local! {
static STATE: RefCell<Option<$t>> = const { RefCell::new(None) };
}
fn with(f: impl FnOnce(&mut $t)) {
STATE.with(|s| {
if let Some(m) = s.borrow_mut().as_mut() {
f(m)
}
})
}
struct Export;
impl $crate::__Guest for Export {
fn init() -> Result<$crate::Registration, String> {
let (m, registration) = <$t as $crate::Mod>::init()?;
STATE.with(|s| *s.borrow_mut() = Some(m));
Ok(registration)
}
fn tick(tick: u64) {
with(|m| $crate::Mod::tick(m, tick))
}
fn frame(seconds: f32) {
with(|m| $crate::Mod::frame(m, seconds))
}
fn command(name: String, args: String) -> Result<Option<String>, String> {
let mut out = Err("The mod is not running".to_string());
with(|m| out = $crate::Mod::command(m, &name, &args));
out
}
fn chat(text: String) {
with(|m| $crate::Mod::chat(m, &text))
}
}
$crate::__export_horizon_mod!(Export);
};
};
}
+97
View File
@@ -0,0 +1,97 @@
/// The contract between Horizon and its mods (docs/mods.md).
///
/// A mod is a WebAssembly component targeting the `mod` world. Each imported
/// interface but `log` is a capability: the mod's manifest lists the ones it
/// uses, the player sees them before turning the mod on, and the game refuses
/// a component that imports one its manifest does not declare.
package horizon:mods@0.1.0;
/// The mod's log, in the game's log under the mod's id. Always granted.
interface log {
enum level {
debug,
info,
warn,
error,
}
write: func(level: level, message: string);
}
/// Capability `game-read`: the local player and the world clock.
interface game {
record player {
x: f64,
y: f64,
z: f64,
/// Degrees, as F3 shows them.
yaw: f32,
pitch: f32,
health: f32,
food: u32,
/// `minecraft:overworld`, `minecraft:the_nether`, ...
dimension: string,
}
record clock {
/// Ticks since the world was created.
game-time: u64,
/// 24000 ticks per day; 0 is 6:00 on the first day.
day-time: u64,
}
/// None on the title screen.
get-player: func() -> option<player>;
get-clock: func() -> option<clock>;
}
/// Capability `chat`: messages only the local player sees.
interface chat {
/// Shown in chat after the mod's name, like a system message.
show: func(text: string);
}
/// Capability `hud`: one panel of text lines per mod, drawn by the game
/// every frame until the mod changes or clears it (no call per frame).
interface hud {
enum corner {
top-left,
top-right,
bottom-left,
bottom-right,
}
record line {
text: string,
/// 0xRRGGBB.
color: u32,
}
set-panel: func(corner: corner, lines: list<line>);
clear: func();
}
/// What the game calls. Only the hooks `init` asks for are ever called.
interface events {
record registration {
/// Chat commands, without the slash. A name vanilla already uses is
/// refused (vanilla's command runs).
commands: list<string>,
/// Call `tick` every game tick (20 per second while playing).
tick: bool,
/// Call `frame` every rendered frame. Budget: 0.1 ms.
frame: bool,
/// Call `chat` for each chat line the player receives.
chat: bool,
}
/// Once, after loading. An error keeps the mod off and is shown.
init: func() -> result<registration, string>;
tick: func(tick: u64);
frame: func(seconds: f32);
/// `/name args`: ok(some(text)) is shown as feedback, err(text) in red.
command: func(name: string, args: string) -> result<option<string>, string>;
chat: func(text: string);
}
world horizon-mod {
import log;
import game;
import chat;
import hud;
export events;
}