From 61c44c22efe23f9cbc4ac00ef8c8f20a35b00aa4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:35:12 +0100 Subject: [PATCH] Mod API: capability render (experimental): HUD shapes and camera shake Mods draw through the game's own renderer, never their own shaders: - WIT `render`: set-hud(shapes) with fill, quad (any four corners), sprite (the game's GUI sprites), item (scaled) and text shapes, up to 1024, kept until replaced; gui-size(); shake(strength, seconds). - Drawn over the HUD after the extras, under chat and screens, hidden with F1 (game/mod_render.rs). Colours are 0xAARRGGBB. - shake turns the view, not the player: jolts fade out squared, add up to 1, at most 3 degrees of yaw and 2 of pitch, scaled by Distortion Effects (screenEffectScale; 0 turns it off). - Experimental: the manifest needs experimental = ["render"]. - No mod drawing, no cost: an empty iterator and an is_empty check. - cargo horizon-mod check reports shakes and HUD shapes. The ui test guest gains /render_hud, /render_clear and /render_shake, with a sandbox test; HudBatch gets fill_quad. - Docs: mods.md, stability.md, the changelog, the regenerated reference. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 9 + crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/mod_render.rs | 176 ++++++++++++++++++ crates/horizon-client/src/game/mods.rs | 15 +- crates/horizon-client/src/hud.rs | 6 + crates/horizon-mod-sdk/src/lib.rs | 2 +- crates/horizon-mod-sdk/wit/horizon.wit | 82 ++++++++ crates/horizon-mods/src/manifest.rs | 11 +- crates/horizon-mods/src/runtime.rs | 81 ++++++++ crates/horizon-mods/tests/sandbox.rs | 38 +++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 71 ++++++- docs/api/mods-reference.md | 94 +++++++++- docs/api/mods.md | 2 + docs/api/stability.md | 1 + docs/mods.md | 5 +- 15 files changed, 582 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-client/src/game/mod_render.rs diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 5d4150ab9..dfb9820a2 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -198,6 +198,8 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { game_time: t, day_time: 1000 + t, }), + // The GUI of a 1280 x 720 window at scale 3. + gui_size: (427.0, 240.0), }); mods.tick(t); for _ in 0..FRAMES_PER_TICK { @@ -217,8 +219,15 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), + Output::Shake { strength, seconds } => { + format!("shook the camera: {strength:.2} for {seconds:.1} s") + } }); } + let shapes = mods.hud_shapes().count(); + if shapes > 0 { + report.output.push(format!("drew {shapes} HUD shape(s)")); + } match failed(&mods) { Some(reason) => Err(format!("it stopped: {reason}")), None => Ok(()), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index eabbc22b8..31bfe74b6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -96,6 +96,7 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mod_render; mod mods; mod mount_menu; mod mounts; @@ -4894,6 +4895,7 @@ impl Game<'_> { // Hud: the action bar and titles draw over the hotbar (nextStratum). self.draw_boss_bars(&mut batch); self.draw_extras(&mut batch); + self.draw_mod_shapes(&mut batch); } if show_hud { // Hud.nextContextualInfoState: the jump bar, the experience bar or @@ -9865,6 +9867,7 @@ impl Game<'_> { self.pitch, ), }; + let (view_yaw, view_pitch) = self.shaken_view(view_yaw, view_pitch); self.audio .set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch); let block = [ diff --git a/crates/horizon-client/src/game/mod_render.rs b/crates/horizon-client/src/game/mod_render.rs new file mode 100644 index 000000000..1c3a20621 --- /dev/null +++ b/crates/horizon-client/src/game/mod_render.rs @@ -0,0 +1,176 @@ +//! Capability `render` (docs/mods.md): the shapes mods keep on the HUD, +//! drawn by the game's own HUD renderer, and their camera shakes. Mods +//! never supply shader code. With no mod drawing, each hook here returns +//! after one check. +use super::Game; +use horizon_client::hud::HudBatch; +#[cfg(feature = "mods")] +use { + horizon_client::{hud::rgba, items::ItemStack, text::Text}, + horizon_mods::Shape, + std::time::Instant, +}; + +/// The camera's jolts from `render.shake`, while any is fading. +#[cfg(feature = "mods")] +#[derive(Default)] +pub(super) struct Shake { + jolts: Vec, +} + +#[cfg(feature = "mods")] +struct Jolt { + start: Instant, + strength: f32, + seconds: f32, +} + +/// The HUD batch's colour (ABGR) from a mod's 0xAARRGGBB. +#[cfg(feature = "mods")] +fn argb(color: u32) -> u32 { + let [a, r, g, b] = color.to_be_bytes(); + rgba(r, g, b, a) +} + +/// The view's turn at full strength, in degrees: yaw, then pitch. +#[cfg(feature = "mods")] +const SHAKE_DEGREES: (f32, f32) = (3.0, 2.0); + +#[cfg(feature = "mods")] +impl Shake { + pub(super) fn add(&mut self, strength: f32, seconds: f32) { + self.jolts.push(Jolt { + start: Instant::now(), + strength, + seconds, + }); + } + /// How far the view turns now (yaw, pitch degrees), `scale` being the + /// player's Distortion Effects; fades jolts out and forgets ended ones. + fn offset(&mut self, now: Instant, scale: f32) -> (f32, f32) { + self.jolts + .retain(|j| now.duration_since(j.start).as_secs_f32() < j.seconds); + let mut strength = 0.0; + for j in &self.jolts { + let left = 1.0 - now.duration_since(j.start).as_secs_f32() / j.seconds; + strength += j.strength * left * left; + } + let strength = strength.min(1.0) * scale.clamp(0.0, 1.0); + if strength <= 0.0 { + return (0.0, 0.0); + } + // Smooth noise: sines at unrelated rates, so it never repeats visibly. + let t = self + .jolts + .first() + .map_or(0.0, |j| now.duration_since(j.start).as_secs_f32()); + let wave = |a: f32, b: f32, c: f32| { + ((t * a).sin() * 0.5 + (t * b).sin() * 0.3 + (t * c).sin() * 0.2).clamp(-1.0, 1.0) + }; + ( + strength * SHAKE_DEGREES.0 * wave(23.0, 37.3, 51.7), + strength * SHAKE_DEGREES.1 * wave(29.1, 43.9, 61.3), + ) + } +} + +#[cfg(not(feature = "mods"))] +impl Game<'_> { + pub(super) fn draw_mod_shapes(&self, _batch: &mut HudBatch) {} + pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) { + (yaw, pitch) + } +} + +#[cfg(feature = "mods")] +impl Game<'_> { + /// The running mods' HUD shapes, in order, over the HUD. + pub(super) fn draw_mod_shapes(&self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + for shape in self.mods.mods.hud_shapes() { + match shape { + Shape::Fill(f) => { + let r = f.rect; + batch.fill(atlas, r.x, r.y, r.w, r.h, argb(f.color)); + } + Shape::Quad(q) => { + let (a, b, c, d) = q.corners; + let corners = [[a.x, a.y], [b.x, b.y], [c.x, c.y], [d.x, d.y]]; + batch.fill_quad(atlas, corners, argb(q.color)); + } + Shape::Sprite(s) => { + let r = s.rect; + let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite); + let name = format!("gui/sprites/{name}"); + batch.sprite_scaled(atlas, &name, r.x, r.y, r.w, r.h, argb(s.color)); + } + Shape::Item(i) => { + if self.res.items().get(&i.item).is_none() { + continue; + } + let start = batch.vertices.len(); + let stack = ItemStack::new(i.item.as_str(), 1); + self.draw_item_model(batch, &stack, i.at.x, i.at.y); + batch.scale_since(start, i.at.x, i.at.y, i.scale, i.scale); + } + Shape::Text(t) => { + let text = Text::literal(t.text.clone()); + let x = if t.centered { + t.at.x - (HudBatch::text_width(atlas, &t.text) / 2.0).floor() + } else { + t.at.x + }; + batch.text_styled( + atlas, + &text, + x, + t.at.y, + argb(t.color | 0xFF00_0000), + t.shadow, + ); + } + } + } + } + /// The view's yaw and pitch after the mods' camera shakes; unchanged + /// while none is fading. + pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) { + if self.mods.shake.jolts.is_empty() { + return (yaw, pitch); + } + let scale = self.settings.file.double("screenEffectScale") as f32; + let (dy, dp) = self.mods.shake.offset(Instant::now(), scale); + (yaw + dy, (pitch + dp).clamp(-90.0, 90.0)) + } +} + +#[cfg(all(test, feature = "mods"))] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn a_jolt_fades_out_and_distortion_scales_it() { + let mut shake = Shake::default(); + shake.add(1.0, 2.0); + let start = shake.jolts[0].start; + let at = |s: f32| start + Duration::from_secs_f32(s); + let size = |(y, p): (f32, f32)| y.abs() + p.abs(); + // Off with Distortion Effects at 0, inside the limits otherwise. + assert_eq!(shake.offset(at(0.3), 0.0), (0.0, 0.0)); + let (y, p) = shake.offset(at(0.3), 1.0); + assert!(y.abs() <= SHAKE_DEGREES.0 && p.abs() <= SHAKE_DEGREES.1); + // Fading: the largest turn over a window shrinks. + let mut peak = |from: f32| { + (0..50) + .map(|i| size(shake.offset(at(from + i as f32 * 0.002), 1.0))) + .fold(0.0, f32::max) + }; + let early = peak(0.1); + let late = peak(1.6); + assert!(late < early, "{late} !< {early}"); + // Gone once it ends. + assert_eq!(shake.offset(at(2.1), 1.0), (0.0, 0.0)); + assert!(shake.jolts.is_empty()); + } +} diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 47a3ce07b..2a07cb940 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -33,7 +33,10 @@ use { #[derive(Default)] pub(super) struct ModsState { #[cfg(feature = "mods")] - mods: Mods, + pub(super) mods: Mods, + /// Capability `render`'s camera shakes. + #[cfg(feature = "mods")] + pub(super) shake: super::mod_render::Shake, /// `--dev-mod PATH`: always on, reloaded when rebuilt. pub(super) dev: Vec, /// When dev mods were last checked for a rebuild. @@ -308,7 +311,11 @@ impl Game<'_> { game_time: self.world.game_time.max(0) as u64, day_time: self.world.day_time.max(0) as u64, }); - Snapshot { player, clock } + Snapshot { + player, + clock, + gui_size: self.gui_size(), + } } /// A game tick. pub(super) fn tick_mods(&mut self) { @@ -382,6 +389,10 @@ impl Game<'_> { self.open_mod_screen(owner, false); continue; } + Output::Shake { strength, seconds } => { + self.mods.shake.add(strength, seconds); + continue; + } Output::CloseScreen { owner } => { if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { self.close_mod_screen(false); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 89d1b1c3c..c3a165792 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -835,6 +835,12 @@ impl HudBatch { r.v1 = cv; self.rect_uv(x, y, w, h, r, color); } + /// Any four-cornered shape in one colour, corners in order round it. + pub fn fill_quad(&mut self, atlas: &HudAtlas, corners: [[f32; 2]; 4], color: u32) { + let w = atlas.white; + let uv = [(w.u0 + w.u1) / 2.0, (w.v0 + w.v1) / 2.0]; + self.quad(corners, [uv; 4], color); + } /// GuiGraphics.fillGradient: `top` to `bottom`, down the rectangle. pub fn fill_gradient( &mut self, diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index aea52339f..8708fb5be 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -38,7 +38,7 @@ wit_bindgen::generate!({ pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest; -pub use horizon::mods::{chat, game, hud, log, storage, ui}; +pub use horizon::mods::{chat, game, hud, log, render, storage, ui}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 1e49919c3..64bbac592 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -163,6 +163,82 @@ interface ui-events { settings-opened: func(); } +/// Capability `render` (experimental: the manifest needs +/// `experimental = ["render"]`): shapes the game draws for the mod with its +/// own renderer, kept until the mod replaces them (no call per frame). A mod +/// never supplies shader code. +interface render { + /// A rectangle in GUI pixels: the top left corner and the size. + record rect { + x: f32, + y: f32, + w: f32, + h: f32, + } + /// A point in GUI pixels from the screen's top left. + record point { + x: f32, + y: f32, + } + record fill-shape { + rect: rect, + /// 0xAARRGGBB. + color: u32, + } + /// Any four-cornered shape (a wheel's segment, an arrow): the corners + /// in order round it. + record quad-shape { + corners: tuple, + /// 0xAARRGGBB. + color: u32, + } + record sprite-shape { + /// One of the game's GUI sprites, as `gui/sprites/` names them + /// (`hud/heart/full`, `widget/button`), the resource packs' versions + /// included. An unknown one draws nothing. + sprite: string, + rect: rect, + /// A tint, 0xAARRGGBB: 0xFFFFFFFF draws it as it is. + color: u32, + } + record item-shape { + /// `minecraft:diamond`, `:`; an unknown one draws nothing. + item: string, + /// The icon's top left. + at: point, + /// 1.0 is the hotbar's 16 × 16. + scale: f32, + } + record text-shape { + /// Up to 256 characters, one line. + text: string, + at: point, + /// 0xRRGGBB, as `hud`'s lines. + color: u32, + /// Centred on `at.x` instead of starting there. + centered: bool, + shadow: bool, + } + variant shape { + fill(fill-shape), + quad(quad-shape), + sprite(sprite-shape), + item(item-shape), + text(text-shape), + } + /// Replaces the mod's HUD shapes: up to 1024, drawn every frame in + /// order over the HUD (after the hotbar, under chat and screens), hidden + /// with the HUD (F1). An empty list removes them. + set-hud: func(shapes: list); + /// The screen's size in GUI pixels (width, height), as of this tick. + gui-size: func() -> tuple; + /// Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that + /// fades out over `seconds` (at most 10). Jolts add up to 1. The view + /// turns, the player doesn't, and the player's Distortion Effects option + /// scales it (0 turns it off). + shake: func(strength: f32, seconds: f32); +} + /// What the game calls. Only the hooks `init` asks for are ever called. interface events { record registration { @@ -203,6 +279,7 @@ world horizon-mod { world horizon-ui-mod { include horizon-mod; import ui; + import render; export ui-events; } @@ -211,3 +288,8 @@ world ui-host { import ui; export ui-events; } + +/// The game's side of capability `render` (imports only). +world render-host { + import render; +} diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 6070f99bd..1880b9f3e 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -84,15 +84,19 @@ pub enum Capability { /// A screen the mod owns and a settings page in Options > Mods, drawn /// with the menus' own widgets (interface `ui`, calls `ui-events`). Ui, + /// Shapes on the HUD and the camera's shake, drawn by the game's own + /// renderer (interface `render`). + Render, } impl Capability { - pub const ALL: [Capability; 6] = [ + pub const ALL: [Capability; 7] = [ Capability::GameRead, Capability::Chat, Capability::Hud, Capability::Storage, Capability::Registries, Capability::Ui, + Capability::Render, ]; /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { @@ -103,12 +107,13 @@ impl Capability { Capability::Storage => "storage", Capability::Registries => "registries", Capability::Ui => "ui", + Capability::Render => "render", } } /// May change in any release: a mod uses it only with /// `experimental = [""]` in its manifest. pub fn is_experimental(self) -> bool { - matches!(self, Capability::Ui) + matches!(self, Capability::Ui | Capability::Render) } /// What the player reads before turning the mod on: "May ". pub fn describe(self) -> &'static str { @@ -119,6 +124,7 @@ impl Capability { Capability::Storage => "save its own settings to disk", Capability::Registries => "add blocks and items to your worlds", Capability::Ui => "show its own screens and a settings page", + Capability::Render => "draw on your screen and shake the camera", } } /// The capability a component import needs, `Ok(None)` for one every @@ -150,6 +156,7 @@ impl fmt::Display for Capability { Capability::Storage => "storage", Capability::Registries => "registries", Capability::Ui => "ui", + Capability::Render => "render", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 1b1795037..e19bfbe3f 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -40,6 +40,19 @@ pub use ui_bindings::horizon::mods::ui::{ ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget, }; use ui_bindings::{UiHost, horizon::mods::ui}; +/// Capability `render`'s imports (docs/mods.md): the game draws the shapes. +mod render_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "render-host", + }); +} +/// What capability `render` asks the game to draw (WIT `interface render`). +pub use render_bindings::horizon::mods::render::{ + FillShape, ItemShape, Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape, + TextShape, +}; +use render_bindings::{RenderHost, horizon::mods::render}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -70,6 +83,8 @@ const STORAGE_WRITE_BUDGET: u64 = 1 << 20; pub struct Snapshot { pub player: Option, pub clock: Option, + /// The screen in GUI pixels (capability `render`'s `gui-size`). + pub gui_size: (f32, f32), } /// What mods asked the game to show since the last [`Mods::drain`]. @@ -86,6 +101,8 @@ pub enum Output { OpenScreen { owner: usize }, /// `ui.close-screen`: the mod closed its own screen (no `closed` back). CloseScreen { owner: usize }, + /// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10). + Shake { strength: f32, seconds: f32 }, } /// A mod's text panel, drawn every frame until it changes. @@ -153,6 +170,8 @@ struct State { out: Vec, panel: Option, ui: UiState, + /// Capability `render`'s HUD shapes, drawn until replaced. + shapes: Vec, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, /// Bytes `storage::set` may still write before this hook call ends @@ -231,6 +250,8 @@ impl Mods { .map_err(|e| e.to_string())?; UiHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + RenderHost::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; self.engine = Some((engine, linker)); } Ok(self.engine.as_ref().expect("made above")) @@ -290,6 +311,7 @@ impl Mods { out: Vec::new(), panel: None, ui: UiState::default(), + shapes: Vec::new(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() @@ -481,6 +503,14 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref()) } + /// The running mods' HUD shapes (capability `render`), each mod's in + /// its own order, mods in load order. + pub fn hud_shapes(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()) + .flat_map(|r| &r.store.data().shapes) + } /// The screen mod `i` last pushed with `ui.open-screen`, while it is up. pub fn screen(&self, i: usize) -> Option<&UiScreen> { self.entries @@ -668,6 +698,57 @@ impl chat::Host for State { } } } +/// HUD shapes one mod may keep (capability `render`). +const SHAPES: usize = 1024; +/// The longest jolt `render.shake` makes, in seconds. +const SHAKE_SECONDS: f32 = 10.0; + +impl render::Host for State { + fn set_hud(&mut self, shapes: Vec) { + self.shapes = shapes + .into_iter() + .take(SHAPES) + .map(|shape| match shape { + Shape::Sprite(mut s) => { + s.sprite = clip(s.sprite); + Shape::Sprite(s) + } + Shape::Item(mut i) => { + i.item = clip(i.item); + i.scale = if i.scale.is_finite() { + i.scale.clamp(0.0, 16.0) + } else { + 1.0 + }; + Shape::Item(i) + } + Shape::Text(mut t) => { + t.text = clip(t.text); + t.color &= 0xFF_FFFF; + Shape::Text(t) + } + other => other, + }) + .collect(); + } + fn gui_size(&mut self) -> (f32, f32) { + self.snapshot.gui_size + } + fn shake(&mut self, strength: f32, seconds: f32) { + let ok = |v: f32, max: f32| { + if v.is_finite() { + v.clamp(0.0, max) + } else { + 0.0 + } + }; + let (strength, seconds) = (ok(strength, 1.0), ok(seconds, SHAKE_SECONDS)); + if strength > 0.0 && seconds > 0.0 { + self.out.push(Output::Shake { strength, seconds }); + } + } +} + impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { let lines = lines diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 77f0975f3..dac333fe6 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1,7 +1,7 @@ //! Loads real mods built with the SDK: the coords-hud example 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, + Clock, Corner, Mods, Output, Package, Player, Shape, Snapshot, Status, manifest::componentize, }; use std::{ path::{Path, PathBuf}, @@ -22,8 +22,8 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["chat", "ui"] -experimental = ["ui"] +capabilities = ["chat", "ui", "render"] +experimental = ["ui", "render"] "#; /// Builds both mods once and writes their `.hmod` files; returns the folder. @@ -89,6 +89,7 @@ fn player() -> Snapshot { game_time: 100, day_time: 24000 + 6000, }), + gui_size: (427.0, 240.0), } } @@ -416,6 +417,37 @@ fn ui_screens_settings_and_events() { assert!(mods.screen(0).is_none()); } +#[test] +fn render_shapes_and_shakes() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + mods.set_snapshot(Snapshot { + gui_size: (427.0, 240.0), + ..Snapshot::default() + }); + assert_eq!(mods.hud_shapes().count(), 0); + assert!(mods.command("render_hud")); + let shapes: Vec<_> = mods.hud_shapes().cloned().collect(); + assert_eq!(shapes.len(), 5); + // The guest read `gui-size`; text is clipped to 256 characters. + let Shape::Text(t) = &shapes[4] else { + panic!("{:?}", shapes[4]) + }; + assert!(t.text.starts_with("gui 427x240 "), "{}", t.text); + assert_eq!(t.text.chars().count(), 256); + assert!(mods.command("render_clear")); + assert_eq!(mods.hud_shapes().count(), 0); + // One jolt, clamped; zero and NaN shake nothing. + mods.drain(); + assert!(mods.command("render_shake")); + assert_eq!( + mods.drain(), + [Output::Shake { + strength: 1.0, + seconds: 10.0 + }] + ); +} + #[test] fn content_only_mods_load_without_an_engine() { let manifest = r#" diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 1af3985a1..146ab6f40 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -1,11 +1,61 @@ //! A mod for the runtime's `ui` tests: `/ui_screen` opens a screen with one //! of each widget, `/ui_settings` sets a settings page, `/ui_close` closes //! the screen; the `ui-events` calls answer in chat so the host sees them. +//! `/render_hud`, `/render_clear` and `/render_shake` test `render`. use horizon_mod_sdk::{ Mod, Registration, chat, + render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; +/// One of each shape, the text too long by 44 characters. +fn shapes() -> Vec { + let (w, h) = render::gui_size(); + let p = |x, y| Point { x, y }; + vec![ + Shape::Fill(FillShape { + rect: Rect { + x: 4.0, + y: 4.0, + w: 60.0, + h: 20.0, + }, + color: 0x80FF0000, + }), + Shape::Quad(QuadShape { + corners: ( + p(w / 2.0, 10.0), + p(w / 2.0 + 20.0, 30.0), + p(w / 2.0, 50.0), + p(w / 2.0 - 20.0, 30.0), + ), + color: 0xC000FF00, + }), + Shape::Sprite(SpriteShape { + sprite: "hud/heart/full".into(), + rect: Rect { + x: 70.0, + y: 4.0, + w: 18.0, + h: 18.0, + }, + color: 0xFFFFFFFF, + }), + Shape::Item(ItemShape { + item: "minecraft:diamond".into(), + at: p(92.0, 4.0), + scale: 2.0, + }), + Shape::Text(TextShape { + text: format!("gui {w}x{h} {}", "x".repeat(300)), + at: p(w / 2.0, h / 2.0 - 30.0), + color: 0xFFFF55, + centered: true, + shadow: true, + }), + ] +} + struct Guest; fn widgets() -> Vec { @@ -30,9 +80,16 @@ fn widgets() -> Vec { impl Mod for Guest { fn init() -> Result<(Self, Registration), String> { - let hooks = ["ui_screen", "ui_settings", "ui_close"] - .into_iter() - .fold(Registration::new(), Registration::command); + let hooks = [ + "ui_screen", + "ui_settings", + "ui_close", + "render_hud", + "render_clear", + "render_shake", + ] + .into_iter() + .fold(Registration::new(), Registration::command); Ok((Guest, hooks)) } fn command(&mut self, name: &str, _args: &str) -> Result, String> { @@ -43,6 +100,14 @@ impl Mod for Guest { }), "ui_settings" => ui::set_settings(&widgets()), "ui_close" => ui::close_screen(), + "render_hud" => render::set_hud(&shapes()), + "render_clear" => render::set_hud(&[]), + // Clamped to (1, 10); the two after it shake nothing. + "render_shake" => { + render::shake(2.0, 99.0); + render::shake(0.0, 1.0); + render::shake(f32::NAN, 1.0); + } _ => {} } Ok(None) diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 0812cde54..ef889d599 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -13,6 +13,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `storage` | [`storage`](#storage) | save its own settings to disk | | `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds | | `ui` | [`ui`](#ui) | show its own screens and a settings page | +| `render` | [`render`](#render) | draw on your screen and shake the camera | ## World `horizon-mod` @@ -23,7 +24,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets. -- Imports (what the game offers): `ui`, `log`, `game`, `chat`, `hud`, `storage` +- Imports (what the game offers): `ui`, `render`, `log`, `game`, `chat`, `hud`, `storage` - Exports (what the mod provides): `ui-events`, `events` ## World `ui-host` @@ -33,6 +34,13 @@ The game's side of `horizon-ui-mod` beyond `horizon-mod`. - Imports (what the game offers): `ui` - Exports (what the mod provides): `ui-events` +## World `render-host` + +The game's side of capability `render` (imports only). + +- Imports (what the game offers): `render` +- Exports (what the mod provides): + ## `log` Access: always granted. @@ -205,6 +213,90 @@ What the game calls on a mod that shows widgets (capability `ui`): what the play | `closed` | `func()` | The player left the mod's screen (Esc or Done); not for a screen the mod closed itself or one that went away with the mod. | | `settings-opened` | `func()` | The player opened the mod's settings page in Options > Mods: call `ui::set-settings` now to fill it with fresh widgets. | +## `render` + +Access: capability `render`. + +Capability `render` (experimental: the manifest needs `experimental = ["render"]`): shapes the game draws for the mod with its own renderer, kept until the mod replaces them (no call per frame). A mod never supplies shader code. + +### record `rect` + +A rectangle in GUI pixels: the top left corner and the size. + +| Field | Type | | +| --- | --- | --- | +| `x` | `f32` | | +| `y` | `f32` | | +| `w` | `f32` | | +| `h` | `f32` | | + +### record `point` + +A point in GUI pixels from the screen's top left. + +| Field | Type | | +| --- | --- | --- | +| `x` | `f32` | | +| `y` | `f32` | | + +### record `fill-shape` + +| Field | Type | | +| --- | --- | --- | +| `rect` | `rect` | | +| `color` | `u32` | 0xAARRGGBB. | + +### record `quad-shape` + +Any four-cornered shape (a wheel's segment, an arrow): the corners in order round it. + +| Field | Type | | +| --- | --- | --- | +| `corners` | `tuple` | | +| `color` | `u32` | 0xAARRGGBB. | + +### record `sprite-shape` + +| Field | Type | | +| --- | --- | --- | +| `sprite` | `string` | One of the game's GUI sprites, as `gui/sprites/` names them (`hud/heart/full`, `widget/button`), the resource packs' versions included. An unknown one draws nothing. | +| `rect` | `rect` | | +| `color` | `u32` | A tint, 0xAARRGGBB: 0xFFFFFFFF draws it as it is. | + +### record `item-shape` + +| Field | Type | | +| --- | --- | --- | +| `item` | `string` | `minecraft:diamond`, `:`; an unknown one draws nothing. | +| `at` | `point` | The icon's top left. | +| `scale` | `f32` | 1.0 is the hotbar's 16 × 16. | + +### record `text-shape` + +| Field | Type | | +| --- | --- | --- | +| `text` | `string` | Up to 256 characters, one line. | +| `at` | `point` | | +| `color` | `u32` | 0xRRGGBB, as `hud`'s lines. | +| `centered` | `bool` | Centred on `at.x` instead of starting there. | +| `shadow` | `bool` | | + +### variant `shape` + +| Case | Payload | | +| --- | --- | --- | +| `fill` | `fill-shape` | | +| `quad` | `quad-shape` | | +| `sprite` | `sprite-shape` | | +| `item` | `item-shape` | | +| `text` | `text-shape` | | + +| Function | Signature | What it does | +| --- | --- | --- | +| `set-hud` | `func(shapes: list)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. | +| `gui-size` | `func() -> tuple` | The screen's size in GUI pixels (width, height), as of this tick. | +| `shake` | `func(strength: f32, seconds: f32)` | Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that fades out over `seconds` (at most 10). Jolts add up to 1. The view turns, the player doesn't, and the player's Distortion Effects option scales it (0 turns it off). | + ## `events` Access: exported by the mod: the game calls it. diff --git a/docs/api/mods.md b/docs/api/mods.md index bec03e84e..cda484c31 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -95,5 +95,7 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- Experimental `render` (`experimental = ["render"]`): HUD shapes (fill, quad, sprite, item, text), `gui-size`, camera + `shake`, drawn by the game's own renderer. - API 0.2 (content): data-driven blocks and items, tags, `horizon:add_to`, terrain adaptation. - API 0.1.0: `log`, `game`, `chat`, `hud`, `storage`; `init`, `tick`, `frame`, `command`, `chat`. diff --git a/docs/api/stability.md b/docs/api/stability.md index ffa9d9b11..76c3c4e51 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -88,6 +88,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | --- | --- | --- | | Mod API: `log`, `game`, `chat`, `hud`, `storage`, `events` | preview | 0.1.0 | | Mod API: `ui`, `ui-events` (a mod's screens and settings page) | experimental | manifest `experimental = ["ui"]` | +| Mod API: `render` (HUD shapes, camera shake; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | | Server mods (events, world, server commands) | not started | manifest `api = "0.3"`, experimental first | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | diff --git a/docs/mods.md b/docs/mods.md index 9b3b8aa94..672d6c7fd 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,6 +87,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `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 | | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects. The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | Hook (export) | When | |---|---| @@ -114,7 +115,7 @@ loading. Ordered by what the first native ports need: | `inventory-read` | the player's inventory, held item, open container | AppleSkin, recipe viewers | | `recipes` | the recipe registry and lookups | JEI/EMI-style viewers | | `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics | -| `render` | world-space lines, boxes and ghost blocks in a per-frame budget | Litematica-style placement, waypoints | +| `render` (world) | world-space lines, boxes and billboards, beside the HUD shapes `render` has | Litematica-style placement, waypoints | | `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) | | `server` | world events (block break/place, entity spawn/death, player join), game rules, server commands | runs where the world is simulated | | `net` | a mod's own client↔server channel (custom payloads) | only between the two halves of the same mod | @@ -288,7 +289,7 @@ experimental = [] # experimental capabilities it uses, e.g. ["ui"] ``` Unknown keys are refused, so a typo is an error, not a silently ignored -permission. An experimental capability (today `ui`) may change in any release +permission. An experimental capability (today `ui` and `render`) may change in any release ([stability](api/stability.md)): a mod uses it only by naming it in `experimental` as well, so nobody depends on it by accident.