From af7a685b5c5871764b9c7b16d948b04dd2cdb867 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 17:09:25 +0100 Subject: [PATCH 1/4] =?UTF-8?q?Mod=20API:=20capability=20`ui`=20=E2=80=94?= =?UTF-8?q?=20mod-owned=20screens=20and=20settings=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New WIT interface `ui` (text, item and list widgets; open-screen, close-screen, set-settings) plus a `ui-events` export (select, closed, settings-opened), in a second world `horizon-ui-mod` so mods built before it keep loading. The game lays out and draws the widgets with its own menus' code: a screen the mod owns (Esc/Done to leave) and a Settings button on the mod's Options > Mods row that opens its page. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- AGENTS.md | 2 +- Cargo.lock | 7 + Cargo.toml | 2 +- crates/horizon-client/src/game.rs | 11 + crates/horizon-client/src/game/agent.rs | 1 + crates/horizon-client/src/game/control.rs | 1 + crates/horizon-client/src/game/mods.rs | 336 +++++++++++++++++- crates/horizon-client/src/game/options.rs | 1 + crates/horizon-client/src/game/screens.rs | 3 +- .../horizon-client/src/game/startup_menu.rs | 2 + crates/horizon-client/src/mod_list.rs | 4 + crates/horizon-client/src/options_ui.rs | 40 ++- crates/horizon-mod-sdk/src/lib.rs | 36 +- crates/horizon-mod-sdk/wit/horizon.wit | 92 +++++ crates/horizon-mods/src/manifest.rs | 9 +- crates/horizon-mods/src/runtime.rs | 200 ++++++++++- crates/horizon-mods/tests/sandbox.rs | 49 +++ crates/horizon-mods/tests/ui_guest/Cargo.toml | 16 + crates/horizon-mods/tests/ui_guest/src/lib.rs | 66 ++++ docs/api/mods-reference.md | 88 +++++ docs/mods.md | 4 +- 21 files changed, 936 insertions(+), 34 deletions(-) create mode 100644 crates/horizon-mods/tests/ui_guest/Cargo.toml create mode 100644 crates/horizon-mods/tests/ui_guest/src/lib.rs diff --git a/AGENTS.md b/AGENTS.md index a72c6723a..2d883b33b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,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 horizon-mods-test-guest --exclude horizon-mods-test-ui-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): diff --git a/Cargo.lock b/Cargo.lock index 70c3c831c..6945e09cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1352,6 +1352,13 @@ dependencies = [ "horizon-mod-sdk", ] +[[package]] +name = "horizon-mods-test-ui-guest" +version = "0.1.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "horizon-port-pack" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 294e93aa9..4076b9079 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "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-shaders", "crates/horizon-shader-api", "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/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..eabbc22b8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -482,6 +482,9 @@ enum Screen { CommandBlock, /// WinScreen: the end poem and the credits (game/win.rs). Win, + /// A `ui` mod's own screen, or its settings page from Options > Mods + /// (game/mods.rs). + Mod, } struct Mining { pos: [i32; 3], @@ -5047,6 +5050,7 @@ impl Game<'_> { self.draw_creative(&mut batch); } Screen::Chat => self.draw_chat_screen(&mut batch), + Screen::Mod => self.draw_mod_screen(&mut batch), Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_toasts(&mut batch); @@ -10363,6 +10367,7 @@ impl Game<'_> { Screen::CommandBlock => self.close_command_block(), Screen::Chat => self.close_chat(), Screen::Win => self.close_win_screen()?, + Screen::Mod => self.close_mod_screen(true), }, KeyCode::Digit1 | KeyCode::Digit2 @@ -11009,6 +11014,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Options && d != 0.0 { self.options_scroll(d); } + if self.screen == Screen::Mod && d != 0.0 { + self.mod_screen_scroll(d); + } if self.screen == Screen::Creative && d != 0.0 { self.creative_screen.wheel(f64::from(d), &self.pack.names); } @@ -11231,6 +11239,9 @@ impl ApplicationHandler for Game<'_> { .map_or([1, 1], |r| [r.config.width, r.config.height]); self.stats_click(size); } + Screen::Mod if pressed && button == MouseButton::Left => { + self.mod_screen_click() + } _ => {} } } diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index f6b68aa74..bed331c32 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -416,6 +416,7 @@ impl Game<'_> { Screen::Friends => "friends", Screen::CommandBlock => "command-block", Screen::Win => "win", + Screen::Mod => "mod", } } pub(super) fn inventory_counts(&self) -> BTreeMap { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index a0d8987d8..ffe05b518 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -799,6 +799,7 @@ impl Game<'_> { Screen::Friends => "friends", Screen::CommandBlock => "command-block", Screen::Win => "win", + Screen::Mod => "mod", } } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 572f9fe2b..688e29da1 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -20,10 +20,13 @@ use { horizon_client::{ extras::Corner, extras_hud, + items::ItemStack, mod_list::Installed, + options_ui::Page, text::{self, Text}, + ui, }, - horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}, + horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, std::time::Instant, }; @@ -39,6 +42,23 @@ pub(super) struct ModsState { /// The chat's command tree while a running mod owns commands. #[cfg(feature = "mods")] tree: Option, + /// A `ui` mod's screen or settings page while it is up. + #[cfg(feature = "mods")] + screen: Option, +} + +/// A `ui` mod's own screen, or its settings page from Options > Mods: the +/// widgets the mod pushed, laid out and drawn with the menus' own widgets. +#[cfg(feature = "mods")] +struct ModScreen { + /// The running mod's index in `mods.mods.entries()`. + owner: usize, + /// Opened from Options > Mods: Done and Esc return there. + settings: bool, + /// What the mod's screen replaced (Playing, Chat, ...), to restore. + under: Screen, + /// One scroll per `list` widget, in widget order. + scrolls: Vec, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. @@ -166,6 +186,11 @@ impl Game<'_> { } pub(super) fn mods_chat(&mut self, _line: &str) {} pub(super) fn draw_mod_panels(&self, _batch: &mut HudBatch, _corners: &mut Corners) {} + pub(super) fn open_mod_screen(&mut self, _owner: usize, _settings: bool) {} + pub(super) fn close_mod_screen(&mut self, _tell: bool) {} + pub(super) fn draw_mod_screen(&mut self, _batch: &mut HudBatch) {} + pub(super) fn mod_screen_click(&mut self) {} + pub(super) fn mod_screen_scroll(&mut self, _delta: f32) {} } #[cfg(feature = "mods")] @@ -187,6 +212,8 @@ impl Game<'_> { let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id); let mods = Mods::load(&paths, on, vanilla_command); self.mods.mods = mods; + // Entries were replaced wholesale: a screen's owner index is stale. + self.mods.screen = None; self.list_mods(); self.sync_mod_commands(); self.show_mod_output(); @@ -212,6 +239,7 @@ impl Game<'_> { description: String::new(), problem, dev: false, + has_settings: false, }; }; // What it may do first: the row cuts long descriptions. @@ -227,6 +255,7 @@ impl Game<'_> { description: format!("{may} {}", m.description).trim().to_owned(), problem, dev: dev.contains(&e.path), + has_settings: e.has_ui_settings(), } }) .collect(); @@ -343,10 +372,22 @@ impl Game<'_> { Output::Feedback { text, error: false } => Text::literal(text), Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED), Output::Stopped { name, reason } => { + // Its screen goes with it: the entry's run is gone, so + // `mod_ui_view` finds no widgets and the screen closes. self.list_mods(); self.sync_mod_commands(); Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED) } + Output::OpenScreen { owner } => { + self.open_mod_screen(owner, false); + continue; + } + Output::CloseScreen { owner } => { + if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { + self.close_mod_screen(false); + } + continue; + } }; // Not through system_message: a mod must not hear its own lines. let focused = self.screen == Screen::Chat; @@ -376,4 +417,297 @@ impl Game<'_> { extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines); } } + + /// A `ui` screen's title and widgets as the mod last pushed them; None + /// when the surface is gone (the mod stopped or closed it). + fn mod_ui_view(&self) -> Option<(String, Vec)> { + let ms = self.mods.screen.as_ref()?; + if ms.settings { + let widgets = self.mods.mods.settings_widgets(ms.owner); + if widgets.is_empty() { + return None; + } + let name = self + .mods + .mods + .entries() + .get(ms.owner) + .and_then(|e| e.manifest.as_ref()) + .map_or("Mod", |m| m.name.as_str()); + Some((name.to_string(), widgets.to_vec())) + } else { + let s: &UiScreen = self.mods.mods.screen(ms.owner)?; + Some((s.title.clone(), s.widgets.clone())) + } + } + /// The layout the mod screen's widgets get at `h`: (widget, top, + /// height), the column being `COLUMN` wide down the middle. + fn mod_ui_layout(&self, h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { + let mut out = Vec::with_capacity(widgets.len()); + let mut y = MOD_UI_TOP; + for w in widgets { + let wh = match w { + UiWidget::Text(_) => 12.0, + UiWidget::Item(_) => 20.0, + UiWidget::List(l) => (l.rows.len().min(6) as f32 * 12.0) + 8.0, + }; + // Nothing may cover Done; a crowded mod loses what won't fit. + if y + wh > h - 34.0 { + break; + } + out.push((y, wh)); + y += wh + 6.0; + } + out + } + /// A mod pushes its screen (`ui.open-screen`), or Options > Mods opens + /// its settings page (`settings`, the mod's `installed` index). + pub(super) fn open_mod_screen(&mut self, owner: usize, settings: bool) { + if self.title.is_some() { + return; + } + if settings { + self.mods.mods.ui_settings_opened(owner); + if self.mods.mods.settings_widgets(owner).is_empty() { + self.show_mod_output(); + return; + } + } + self.mods.screen = Some(ModScreen { + owner, + settings, + under: self.screen, + scrolls: Vec::new(), + }); + self.screen = Screen::Mod; + if self.player.is_some() { + self.capture(false); + } + self.show_mod_output(); + } + /// Leaves the mod screen: back to Options for a settings page, to what + /// it covered for a mod's own. `tell` is Esc/Done, heard as `closed`. + pub(super) fn close_mod_screen(&mut self, tell: bool) { + let Some(ms) = self.mods.screen.take() else { + return; + }; + if ms.settings { + self.open_options_at(self.options_from_title, Page::Mods); + } else { + self.screen = ms.under; + if self.screen == Screen::Playing && self.player.is_some() { + self.capture(true); + } + } + if tell { + self.mods.mods.ui_closed(ms.owner); + self.show_mod_output(); + } + } + /// The mod's screen or settings page: its title over widgets stacked + /// down the middle, a Done button, Esc to leave (vanilla's menus). + pub(super) fn draw_mod_screen(&mut self, batch: &mut HudBatch) { + if self.mods.screen.is_none() { + self.screen = Screen::Playing; + return; + } + let Some((title, widgets)) = self.mod_ui_view() else { + self.mods.screen = None; + self.screen = Screen::Playing; + return; + }; + // Item icons draw in a second pass: `draw_item` needs `&mut self`, + // so `atlas` may not stay borrowed across it. + let mut items: Vec<(String, f32, f32)> = Vec::new(); + let atlas = &self.gui.atlas; + let in_world = self.player.is_some(); + ui::menu_background(batch, &atlas, 0.0, 0.0, batch.width, batch.height, in_world); + ui::centered_text( + batch, + &atlas, + &Text::literal(title), + 0.0, + 15.0, + batch.width, + u32::MAX, + ); + let cx = (batch.width / 2.0).floor(); + let x = cx - MOD_UI_COLUMN / 2.0; + let layout = self.mod_ui_layout(batch.height, &widgets); + let mut list_i = 0usize; + for (w, &(wy, wh)) in widgets.iter().zip(&layout) { + match w { + UiWidget::Text(t) => { + let color = if t.color == 0 { + u32::MAX + } else { + t.color | 0xFF00_0000 + }; + ui::centered_text( + batch, + &atlas, + &Text::literal(t.text.clone()), + x, + wy + 1.0, + MOD_UI_COLUMN, + color, + ); + } + UiWidget::Item(i) => { + if self.res.items().get(&i.item).is_some() { + items.push((i.item.clone(), x + 2.0, wy + 2.0)); + } else { + batch.text(&atlas, "?", x + 6.0, wy + 6.0, u32::MAX, true); + } + let name = if i.name.is_empty() { + i.item.rsplit(':').next().unwrap_or(&i.item).to_string() + } else { + i.name.clone() + }; + batch.text_styled( + &atlas, + &Text::literal(name), + x + 22.0, + wy + 6.0, + u32::MAX, + true, + ); + } + UiWidget::List(l) => { + let scroll = { + let ms = self.mods.screen.as_mut().expect("checked"); + ms.scrolls.resize_with(list_i + 1, ui::Scroll::default); + ms.scrolls[list_i] + }; + list_i += 1; + let rows_top = wy + 4.0; + let rows_bottom = wy + wh - 4.0; + batch.fill(&atlas, x, wy, MOD_UI_COLUMN, wh, 0x8000_0000); + for (b, yy) in [(x, wy), (x, wy + wh - 1.0)] { + batch.fill(&atlas, b, yy, MOD_UI_COLUMN, 1.0, 0xFF50_5050); + } + for (xx, yy) in [(x, wy), (x + MOD_UI_COLUMN - 1.0, wy)] { + batch.fill(&atlas, xx, yy, 1.0, wh, 0xFF50_5050); + } + let content = l.rows.len() as f32 * 12.0; + let first = (scroll.amount / 12.0) as usize; + let last = (first + ((rows_bottom - rows_top) / 12.0).ceil() as usize + 1) + .min(l.rows.len()); + for (vi, ri) in (first..last).enumerate() { + let ry = rows_top + vi as f32 * 12.0 - (scroll.amount % 12.0); + if ui::hovered(self.cursor, x, ry, MOD_UI_COLUMN - 6.0, 12.0) { + batch.fill(&atlas, x + 1.0, ry, MOD_UI_COLUMN - 8.0, 12.0, 0x20FF_FFFF); + } + if l.selected == Some(ri as u32) { + batch.fill(&atlas, x + 1.0, ry, 3.0, 12.0, 0xFFFF_FFFF); + } + batch.text_styled( + &atlas, + &Text::literal(l.rows[ri].clone()), + x + 6.0, + ry + 2.0, + u32::MAX, + true, + ); + } + ui::scrollbar( + batch, + &atlas, + x + MOD_UI_COLUMN - 5.0, + rows_top, + rows_bottom, + content, + scroll.amount, + ); + } + } + } + let hover = ui::hovered(self.cursor, cx - 100.0, batch.height - 27.0, 200.0, 20.0); + ui::button( + batch, + &atlas, + cx - 100.0, + batch.height - 27.0, + 200.0, + 20.0, + &Text::literal("Done"), + true, + hover, + ); + for (id, ix, iy) in items { + let stack = ItemStack::new(id.as_str(), 1); + self.draw_item(batch, &stack, ix, iy); + } + } + /// A click on the mod screen: Done leaves it, a `list` row is the mod's + /// `ui-events::select`. + pub(super) fn mod_screen_click(&mut self) { + let (w, h) = self.gui_size(); + let cursor = self.cursor; + if ui::hovered(cursor, (w / 2.0).floor() - 100.0, h - 27.0, 200.0, 20.0) { + self.audio.play_button_click(); + self.close_mod_screen(true); + return; + } + let Some((_, widgets)) = self.mod_ui_view() else { + return; + }; + let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; + let layout = self.mod_ui_layout(h, &widgets); + let mut list_i = 0usize; + for (w, &(wy, wh)) in widgets.iter().zip(&layout) { + let UiWidget::List(l) = w else { continue }; + let scroll = self + .mods + .screen + .as_ref() + .and_then(|ms| ms.scrolls.get(list_i).copied()) + .unwrap_or_default(); + list_i += 1; + let row = ((cursor.1 - (wy + 4.0) + scroll.amount) / 12.0) as i64; + if ui::hovered(cursor, x + 1.0, wy + 1.0, MOD_UI_COLUMN - 7.0, wh - 2.0) + && row >= 0 + && (row as usize) < l.rows.len() + { + self.audio.play_button_click(); + self.mods.mods.ui_select( + self.mods.screen.as_ref().map_or(0, |ms| ms.owner), + l.id, + row as u32, + ); + self.show_mod_output(); + return; + } + } + } + /// The wheel over a `list` scrolls it. + pub(super) fn mod_screen_scroll(&mut self, delta: f32) { + let (w, h) = self.gui_size(); + let cursor = self.cursor; + let Some((_, widgets)) = self.mod_ui_view() else { + return; + }; + let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; + let layout = self.mod_ui_layout(h, &widgets); + let mut list_i = 0usize; + for (w, &(wy, wh)) in widgets.iter().zip(&layout) { + let UiWidget::List(l) = w else { continue }; + let over = ui::hovered(cursor, x, wy, MOD_UI_COLUMN, wh); + let Some(ms) = self.mods.screen.as_mut() else { + return; + }; + ms.scrolls.resize_with(list_i + 1, ui::Scroll::default); + if over { + let content = l.rows.len() as f32 * 12.0; + ms.scrolls[list_i].wheel(delta, 12.0, wy + 4.0, wy + wh - 4.0, content); + return; + } + list_i += 1; + } + } } + +#[cfg(feature = "mods")] +const MOD_UI_TOP: f32 = 40.0; +#[cfg(feature = "mods")] +const MOD_UI_COLUMN: f32 = 200.0; diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index d947f91d0..812c9ce07 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -237,6 +237,7 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::ModSettings(i) => self.open_mod_screen(i, true), Event::Credits => self.open_win_screen(false, super::win::Finish::Options), } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index cf1f3269f..44f3fbd51 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -17,7 +17,8 @@ impl Screen { | Self::Stats | Self::Advancements | Self::WorldOptions - | Self::Friends => true, + | Self::Friends + | Self::Mod => true, Self::Playing | Self::GameModeSwitcher | Self::Chat diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index 96af99bbc..94771f9ac 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -381,6 +381,8 @@ impl Loading { self.menu.win = Some((screen, Instant::now())); } } + // Mods' settings pages open only in a running game. + Event::ModSettings(_) => {} // The startup menu runs before the game opens a control socket. Event::ButtonClick | Event::CopyAgentDetails => {} } diff --git a/crates/horizon-client/src/mod_list.rs b/crates/horizon-client/src/mod_list.rs index ba3d93cda..db2ea9194 100644 --- a/crates/horizon-client/src/mod_list.rs +++ b/crates/horizon-client/src/mod_list.rs @@ -26,6 +26,9 @@ pub struct Installed { pub problem: Option, /// Loaded with `--dev-mod`: always on, reloaded when rebuilt. pub dev: bool, + /// The running mod set a page of widgets (capability `ui`): its row + /// gains a Settings button. + pub has_settings: bool, } impl ModList { @@ -96,6 +99,7 @@ mod tests { description: String::new(), problem: None, dev, + has_settings: false, }; let mut list = ModList { installed: vec![installed("a", false), installed("b", true)], diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 0bc1e933d..1d1f099eb 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -893,6 +893,9 @@ enum Act { ResetPadKey(&'static str), ResetPadKeys, ToggleMod(usize), + /// The installed mod's own settings page (capability `ui`), shown as a + /// screen: `Event::ModSettings` has the game open it. + ModSettings(usize), OpenModFolder, /// Credits & Attribution's Credits button (WinScreen without the poem). Credits, @@ -944,6 +947,9 @@ pub enum Event { Packs(Vec), OpenPackFolder, OpenModFolder, + /// Open the mod's own settings page (capability `ui`): the installed + /// mod's index in `mods.installed`. + ModSettings(usize), /// Roll the credits (`CreditsAndAttributionScreen.openCreditsScreen`). Credits, /// Copy how an agent connects (the AI Agent page). @@ -1503,15 +1509,26 @@ impl OptionsUi { } else if installed.dev { label = label.append(" (Dev)"); } - let widget = button(0.0, 0.0, 310.0, label, Act::ToggleMod(i)); - Row::Buttons( - if installed.dev || installed.id.is_empty() { - inactive(widget) - } else { - widget - }, - None, - ) + let dead = installed.dev || installed.id.is_empty(); + // A running mod with a settings page (capability + // `ui`) gets its own button beside the toggle. + if installed.has_settings { + let toggle = button(0.0, 0.0, 150.0, label, Act::ToggleMod(i)); + let settings = button( + 0.0, + 0.0, + 150.0, + Text::literal("Settings"), + Act::ModSettings(i), + ); + Row::Buttons( + if dead { inactive(toggle) } else { toggle }, + Some(settings), + ) + } else { + let widget = button(0.0, 0.0, 310.0, label, Act::ToggleMod(i)); + Row::Buttons(if dead { inactive(widget) } else { widget }, None) + } }) .collect() } @@ -2498,6 +2515,10 @@ impl OptionsUi { s.mods.toggle(i); events.push(Event::Changed); } + Act::ModSettings(i) => { + events.push(Event::ButtonClick); + events.push(Event::ModSettings(i)); + } Act::OpenModFolder => events.push(Event::OpenModFolder), Act::Credits => events.push(Event::Credits), Act::CopyAgentDetails => events.push(Event::CopyAgentDetails), @@ -2988,6 +3009,7 @@ mod tests { description: "May show HUD panels.".into(), problem: id.is_empty().then(|| "Invalid package".into()), dev, + has_settings: false, }); } let (widgets, ..) = ui.layout(&s, size.0, size.1); diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 71c36cf80..aea52339f 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -21,18 +21,24 @@ //! ``` //! //! 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`, `ui`). +//! +//! Widgets (capability `ui`): a mod shows a screen it owns with +//! [`ui::open_screen`] and a page in Options > Mods with +//! [`ui::set_settings`]; what the player does with them comes back as +//! [`Mod::ui_select`], [`Mod::ui_closed`] and [`Mod::ui_settings_opened`]. wit_bindgen::generate!({ path: "wit", - world: "horizon-mod", + world: "horizon-ui-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, storage}; +pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest; +pub use horizon::mods::{chat, game, hud, log, storage, ui}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. @@ -51,6 +57,14 @@ pub trait Mod: Sized + 'static { } /// A chat line the player received, when [`Registration::chat`] is set. fn chat(&mut self, _text: &str) {} + /// A row of one of the mod's `list` widgets was picked (capability + /// `ui`): the widget's `id` and the row. + fn ui_select(&mut self, _id: u32, _row: u32) {} + /// The player left the mod's screen (Esc or Done; capability `ui`). + fn ui_closed(&mut self) {} + /// The player opened the mod's settings page (capability `ui`): call + /// [`ui::set_settings`] for fresh widgets. + fn ui_settings_opened(&mut self) {} } impl Registration { @@ -135,13 +149,27 @@ macro_rules! export_mod { with(|m| $crate::Mod::chat(m, &text)) } } + impl $crate::__UiEventsGuest for Export { + fn select(id: u32, row: u32) { + with(|m| $crate::Mod::ui_select(m, id, row)) + } + fn closed() { + with(|m| $crate::Mod::ui_closed(m)) + } + fn settings_opened() { + with(|m| $crate::Mod::ui_settings_opened(m)) + } + } // Only WebAssembly has the component's exports: a host build (cargo test or // clippy on the workspace) checks the mod without them, which macOS // couldn't link (its exported-symbols list cuts names at the `#`). #[cfg(target_arch = "wasm32")] $crate::__export_horizon_mod!(Export); #[cfg(not(target_arch = "wasm32"))] - let _ = ::init; + let _ = ( + ::init, + ::select, + ); }; }; } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 9f00a12b1..1e49919c3 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -86,6 +86,83 @@ interface storage { delete: func(key: string); } +/// Capability `ui`: widgets the game draws with its own menus' widgets, for +/// a screen the mod owns and a settings page in Options > Mods. Layout and +/// drawing are the game's: a mod says what its widgets hold, never where +/// they sit or how they look, and the game clips everything it is handed. +interface ui { + /// A line of text. + record text-widget { + /// The mod's own name for the widget; `ui-events` calls echo it. + id: u32, + /// Up to 256 characters. + text: string, + /// 0xRRGGBB; 0 is the menus' white. + color: u32, + } + /// An item's icon and a name beside it, as recipe viewers show them. + record item-widget { + /// The mod's own name for the widget. + id: u32, + /// `minecraft:diamond`, `:`; an unknown id draws a "?". + item: string, + /// The name shown beside the icon (empty: the item's own). + name: string, + } + /// Rows the player picks one of, as an options page lists choices: a + /// pick is `ui-events::select`, `selected` is the row to mark now. + record list-widget { + /// The mod's own name for the widget; `ui-events::select` echoes it. + id: u32, + /// The rows' texts, at most 512, each up to 256 characters. + rows: list, + /// The row to mark as the current choice, if any. + selected: option, + } + /// A thing on a mod's screen or settings page. + variant widget { + /// Text the player reads. + text(text-widget), + /// An item's icon and name. + item(item-widget), + /// Rows the player picks from. + %list(list-widget), + } + /// A screen the mod owns: a title over widgets stacked down the middle, + /// the Done button the game adds, and Esc to leave it. + record screen { + /// Its title, up to 256 characters. + title: string, + /// Its widgets, in order, at most 64. + widgets: list, + } + /// Show `screen` over the game; a second call while it is open replaces + /// it. Only the last call of one hook counts. + open-screen: func(screen: screen); + /// Close the mod's screen when it is open (the mod hears no `closed` + /// for this: it was its own doing). + close-screen: func(); + /// The mod's page in Options > Mods, reached from a settings button on + /// its row: the widgets it shows, an empty list for no page. The player + /// opening the page is `ui-events::settings-opened`: push fresh widgets + /// then; later calls update the page while it shows. + set-settings: func(widgets: list); +} + +/// What the game calls on a mod that shows widgets (capability `ui`): +/// what the player did with them. +interface ui-events { + /// A row of one of the mod's `list` widgets was picked: the widget's + /// `id` and the row, on the screen or the settings page that showed it. + select: func(id: u32, row: u32); + /// 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. + closed: func(); + /// The player opened the mod's settings page in Options > Mods: call + /// `ui::set-settings` now to fill it with fresh widgets. + settings-opened: func(); +} + /// What the game calls. Only the hooks `init` asks for are ever called. interface events { record registration { @@ -119,3 +196,18 @@ world horizon-mod { import storage; export events; } + +/// 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. +world horizon-ui-mod { + include horizon-mod; + import ui; + export ui-events; +} + +/// The game's side of `horizon-ui-mod` beyond `horizon-mod`. +world ui-host { + import ui; + export ui-events; +} diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 3a93b2512..f1ac123b1 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -75,14 +75,18 @@ pub enum Capability { /// New blocks and items from the mod's `data/` (API 0.2): no WIT /// interface, the game reads them before the world loads. Registries, + /// A screen the mod owns and a settings page in Options > Mods, drawn + /// with the menus' own widgets (interface `ui`, calls `ui-events`). + Ui, } impl Capability { - pub const ALL: [Capability; 5] = [ + pub const ALL: [Capability; 6] = [ Capability::GameRead, Capability::Chat, Capability::Hud, Capability::Storage, Capability::Registries, + Capability::Ui, ]; /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { @@ -92,6 +96,7 @@ impl Capability { Capability::Hud => "hud", Capability::Storage => "storage", Capability::Registries => "registries", + Capability::Ui => "ui", } } /// What the player reads before turning the mod on: "May ". @@ -102,6 +107,7 @@ impl Capability { Capability::Hud => "draw text on your screen", 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", } } /// The capability a component import needs, `Ok(None)` for one every @@ -132,6 +138,7 @@ impl fmt::Display for Capability { Capability::Hud => "hud", Capability::Storage => "storage", Capability::Registries => "registries", + Capability::Ui => "ui", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 52da641b4..1b1795037 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -16,6 +16,15 @@ mod bindings { world: "horizon-mod", }); } +/// Capability `ui`'s world beyond `horizon-mod` (docs/mods.md): a second +/// world, so mods built before it (no `ui-events` export) still instantiate +/// as `horizon-mod` and simply hear nothing of their widgets. +mod ui_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "ui-host", + }); +} pub use bindings::horizon::mods::{ game::{Clock, Player}, hud::{Corner, Line}, @@ -25,6 +34,12 @@ use bindings::{ exports::horizon::mods::events::Registration, horizon::mods::{chat, game, hud, log as mod_log, storage}, }; +/// The widget model a `ui` screen or settings page shows (WIT `interface +/// ui`), for the game to draw with its menus' own widgets. +pub use ui_bindings::horizon::mods::ui::{ + ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget, +}; +use ui_bindings::{UiHost, horizon::mods::ui}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -66,6 +81,11 @@ pub enum Output { Feedback { text: String, error: bool }, /// The mod was turned off: it trapped, overran or failed to start. Stopped { name: String, reason: String }, + /// `ui.open-screen`: the mod's entry in `entries()`; what it shows is + /// [`Mods::screen`]. + OpenScreen { owner: usize }, + /// `ui.close-screen`: the mod closed its own screen (no `closed` back). + CloseScreen { owner: usize }, } /// A mod's text panel, drawn every frame until it changes. @@ -95,19 +115,44 @@ pub struct Entry { run: Option, modified: Option, } +impl Entry { + /// The running mod has a settings page (capability `ui` set widgets + /// with `ui.set-settings`): its row in Options > Mods gains a button. + pub fn has_ui_settings(&self) -> bool { + self.run + .as_ref() + .is_some_and(|r| !r.store.data().ui.settings.is_empty()) + } +} struct Running { store: Store, exports: HorizonMod, + /// The mod's `ui-events` export; none for a mod built before `ui`. + ui: Option, hooks: Registration, } +/// What capability `ui` pushed since the hooks last ran. +#[derive(Default)] +struct UiState { + /// The screen `ui.open-screen` last pushed, until `ui.close-screen`. + screen: Option, + /// The widgets `ui.set-settings` last pushed (the mod's page in + /// Options > Mods). + settings: Vec, + /// The calls since the last hook ended, for [`Output`]. + open: bool, + close: bool, +} + struct State { name: String, id: String, snapshot: Arc, out: Vec, panel: Option, + ui: UiState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, /// Bytes `storage::set` may still write before this hook call ends @@ -184,6 +229,8 @@ impl Mods { let mut linker = Linker::new(&engine); HorizonMod::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + UiHost::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")) @@ -242,6 +289,7 @@ impl Mods { snapshot, out: Vec::new(), panel: None, + ui: UiState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() @@ -252,8 +300,13 @@ impl Mods { let mut store = Store::new(engine, state); store.limiter(|s| &mut s.limits); store.set_fuel(FUEL_INIT).map_err(|e| e.to_string())?; - let exports = - HorizonMod::instantiate(&mut store, &component, linker).map_err(|e| reason(&e))?; + let instance = linker + .instantiate(&mut store, &component) + .map_err(|e| reason(&e))?; + let exports = HorizonMod::new(&mut store, &instance).map_err(|e| reason(&e))?; + // `ui-events` is a mod built since `ui`'s; older mods have no export + // and stay callable through `events` alone. + let ui = UiHost::new(&mut store, &instance).ok(); let mut hooks = exports .horizon_mods_events() .call_init(&mut store) @@ -269,6 +322,7 @@ impl Mods { Ok(Some(Running { store, exports, + ui, hooks, })) } @@ -290,7 +344,7 @@ impl Mods { &mut self, fuel: u64, wants: impl Fn(&Registration) -> bool, - mut f: impl FnMut(&HorizonMod, &mut Store) -> wasmtime::Result<()>, + mut f: impl FnMut(&mut Running) -> wasmtime::Result<()>, ) { for i in 0..self.entries.len() { if self.entries[i] @@ -308,20 +362,28 @@ impl Mods { &mut self, i: usize, fuel: u64, - f: impl FnOnce(&HorizonMod, &mut Store) -> wasmtime::Result, + f: impl FnOnce(&mut Running) -> wasmtime::Result, ) -> Option { let entry = &mut self.entries[i]; let run = entry.run.as_mut()?; run.store.data_mut().snapshot = self.snapshot.clone(); run.store.data_mut().storage_budget = STORAGE_WRITE_BUDGET; let started = Instant::now(); - let result = run - .store - .set_fuel(fuel) - .and_then(|()| f(&run.exports, &mut run.store)); + let result = run.store.set_fuel(fuel).and_then(|()| f(run)); // An average over about the last 64 calls. entry.cost = (entry.cost * 63 + started.elapsed()) / 64; - self.out.append(&mut run.store.data_mut().out); + let data = run.store.data_mut(); + let (open, close) = ( + std::mem::take(&mut data.ui.open), + std::mem::take(&mut data.ui.close), + ); + self.out.append(&mut data.out); + if open { + self.out.push(Output::OpenScreen { owner: i }); + } + if close { + self.out.push(Output::CloseScreen { owner: i }); + } match result { Ok(r) => Some(r), Err(e) => { @@ -344,7 +406,11 @@ impl Mods { self.each( FUEL_TICK, |h| h.tick, - |m, s| m.horizon_mods_events().call_tick(s, tick), + |run| { + run.exports + .horizon_mods_events() + .call_tick(&mut run.store, tick) + }, ); } /// A rendered frame, `seconds` after the last. @@ -352,7 +418,11 @@ impl Mods { self.each( FUEL_FRAME, |h| h.frame, - |m, s| m.horizon_mods_events().call_frame(s, seconds), + |run| { + run.exports + .horizon_mods_events() + .call_frame(&mut run.store, seconds) + }, ); } /// A chat line the player received, as plain text. @@ -360,7 +430,11 @@ impl Mods { self.each( FUEL_EVENT, |h| h.chat, - |m, s| m.horizon_mods_events().call_chat(s, text), + |run| { + run.exports + .horizon_mods_events() + .call_chat(&mut run.store, text) + }, ); } /// Whether a running mod owns `/name`. @@ -381,8 +455,10 @@ impl Mods { let Some(i) = self.command_owner(name) else { return false; }; - let result = self.call(i, FUEL_EVENT, |m, s| { - m.horizon_mods_events().call_command(s, name, args) + let result = self.call(i, FUEL_EVENT, |run| { + run.exports + .horizon_mods_events() + .call_command(&mut run.store, name, args) }); match result { Some(Ok(Some(text))) => self.out.push(Output::Feedback { text, error: false }), @@ -405,6 +481,60 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref()) } + /// The screen mod `i` last pushed with `ui.open-screen`, while it is up. + pub fn screen(&self, i: usize) -> Option<&UiScreen> { + self.entries + .get(i)? + .run + .as_ref()? + .store + .data() + .ui + .screen + .as_ref() + } + /// The widgets `ui.set-settings` pushed: mod `i`'s page in + /// Options > Mods. Empty while it has none. + pub fn settings_widgets(&self, i: usize) -> &[UiWidget] { + self.entries + .get(i) + .and_then(|e| e.run.as_ref()) + .map_or(&[], |r| &r.store.data().ui.settings) + } + /// A `list` widget's row was picked on a surface of mod `i`. + pub fn ui_select(&mut self, i: usize, id: u32, row: u32) { + self.ui_event(i, |ui, s| { + ui.horizon_mods_ui_events().call_select(s, id, row) + }); + } + /// The player left mod `i`'s screen (Esc or Done). + pub fn ui_closed(&mut self, i: usize) { + self.ui_event(i, |ui, s| ui.horizon_mods_ui_events().call_closed(s)); + } + /// The player opened mod `i`'s settings page. + pub fn ui_settings_opened(&mut self, i: usize) { + self.ui_event(i, |ui, s| { + ui.horizon_mods_ui_events().call_settings_opened(s) + }); + } + /// A `ui-events` call on mod `i`; no export, no call (mods built + /// before `ui` have none). + fn ui_event( + &mut self, + i: usize, + f: impl FnOnce(&UiHost, &mut Store) -> wasmtime::Result<()>, + ) { + let has_ui = self + .entries + .get(i) + .and_then(|e| e.run.as_ref()) + .is_some_and(|r| r.ui.is_some()); + if has_ui { + self.call(i, FUEL_EVENT, |run| { + f(run.ui.as_ref().expect("checked above"), &mut run.store) + }); + } + } /// What mods asked to show since the last call. pub fn drain(&mut self) -> Vec { std::mem::take(&mut self.out) @@ -476,6 +606,33 @@ fn clip(text: String) -> String { } } +/// Widgets on a `ui` screen or settings page, and rows on one `list`. +const WIDGETS: usize = 64; +const LIST_ROWS: usize = 512; + +fn clip_widgets(widgets: Vec) -> Vec { + widgets + .into_iter() + .take(WIDGETS) + .map(|w| match w { + UiWidget::Text(mut t) => { + t.text = clip(t.text); + UiWidget::Text(t) + } + UiWidget::Item(mut i) => { + i.item = clip(i.item); + i.name = clip(i.name); + UiWidget::Item(i) + } + UiWidget::List(mut l) => { + l.rows = l.rows.into_iter().take(LIST_ROWS).map(clip).collect(); + l.selected = l.selected.filter(|&s| (s as usize) < l.rows.len()); + UiWidget::List(l) + } + }) + .collect() +} + impl mod_log::Host for State { fn write(&mut self, level: mod_log::Level, message: String) { let level = match level { @@ -527,6 +684,21 @@ impl hud::Host for State { self.panel = None; } } +impl ui::Host for State { + fn open_screen(&mut self, mut screen: ui::Screen) { + screen.title = clip(screen.title); + screen.widgets = clip_widgets(screen.widgets); + self.ui.screen = Some(screen); + self.ui.open = true; + } + fn close_screen(&mut self) { + self.ui.screen = None; + self.ui.close = true; + } + fn set_settings(&mut self, widgets: Vec) { + self.ui.settings = clip_widgets(widgets); + } +} impl storage::Host for State { fn get(&mut self, key: String) -> Option> { storage_key_ok(&key) diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index a246c07b0..a229f748e 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -17,6 +17,13 @@ version = "0.1.0" api = "0.1" capabilities = ["chat", "storage"] "#; +const UI_MANIFEST: &str = r#" +id = "test_ui_guest" +name = "Test UI Guest" +version = "0.1.0" +api = "0.1" +capabilities = ["chat", "ui"] +"#; /// Builds both mods once and writes their `.hmod` files; returns the folder. fn mods_dir() -> &'static Path { @@ -32,6 +39,8 @@ fn mods_dir() -> &'static Path { "coords-hud", "-p", "horizon-mods-test-guest", + "-p", + "horizon-mods-test-ui-guest", "--target-dir", ]) .arg(&target) @@ -48,6 +57,7 @@ fn mods_dir() -> &'static Path { let mods = [ ("coords_hud", std::fs::read_to_string(example).unwrap()), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), + ("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()), ]; for (name, manifest) in mods { let core = std::fs::read(built.join(format!("{name}.wasm"))).unwrap(); @@ -366,6 +376,45 @@ fn hook_overhead() { ); } +#[test] +fn ui_screens_settings_and_events() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + assert_eq!(mods.entries()[0].status, Status::Running); + assert!(!mods.entries()[0].has_ui_settings()); + // `/ui_screen` pushes the screen; the host clips nothing of this one. + assert!(mods.command("ui_screen")); + assert_eq!(mods.drain(), [Output::OpenScreen { owner: 0 }]); + let screen = mods.screen(0).expect("a pushed screen"); + assert_eq!(screen.title, "Guest's screen"); + assert_eq!(screen.widgets.len(), 3); + // What the player did comes back through `ui-events`. + mods.ui_select(0, 7, 2); + mods.ui_closed(0); + assert_eq!( + mods.drain(), + [ + Output::Chat { + name: "Test UI Guest".into(), + text: "selected 7:2".into(), + }, + Output::Chat { + name: "Test UI Guest".into(), + text: "closed".into(), + }, + ] + ); + // The settings page: empty until the mod fills it, refreshed on open. + assert!(mods.command("ui_settings")); + assert_eq!(mods.settings_widgets(0).len(), 3); + assert!(mods.entries()[0].has_ui_settings()); + mods.ui_settings_opened(0); + assert_eq!(mods.settings_widgets(0).len(), 1); + // `/ui_close` closes the mod's own screen. + assert!(mods.command("ui_close")); + assert!(mods.drain().contains(&Output::CloseScreen { owner: 0 })); + assert!(mods.screen(0).is_none()); +} + #[test] fn content_only_mods_load_without_an_engine() { let manifest = r#" diff --git a/crates/horizon-mods/tests/ui_guest/Cargo.toml b/crates/horizon-mods/tests/ui_guest/Cargo.toml new file mode 100644 index 000000000..ae6e0950e --- /dev/null +++ b/crates/horizon-mods/tests/ui_guest/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "horizon-mods-test-ui-guest" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "A mod that shows widgets, for horizon-mods' sandbox tests" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs new file mode 100644 index 000000000..1af3985a1 --- /dev/null +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -0,0 +1,66 @@ +//! 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. +use horizon_mod_sdk::{ + Mod, Registration, chat, + ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, +}; + +struct Guest; + +fn widgets() -> Vec { + vec![ + Widget::Text(TextWidget { + id: 1, + text: "Pick a row".into(), + color: 0, + }), + Widget::Item(ItemWidget { + id: 2, + item: "minecraft:diamond".into(), + name: String::new(), + }), + Widget::List(ListWidget { + id: 7, + rows: vec!["first".into(), "second".into(), "third".into()], + selected: Some(1), + }), + ] +} + +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); + Ok((Guest, hooks)) + } + fn command(&mut self, name: &str, _args: &str) -> Result, String> { + match name { + "ui_screen" => ui::open_screen(&Screen { + title: "Guest's screen".into(), + widgets: widgets(), + }), + "ui_settings" => ui::set_settings(&widgets()), + "ui_close" => ui::close_screen(), + _ => {} + } + Ok(None) + } + fn ui_select(&mut self, id: u32, row: u32) { + chat::show(&format!("selected {id}:{row}")); + } + fn ui_closed(&mut self) { + chat::show("closed"); + } + fn ui_settings_opened(&mut self) { + ui::set_settings(&[Widget::Text(TextWidget { + id: 1, + text: "fresh".into(), + color: 0x33CC33, + })]); + chat::show("settings opened"); + } +} + +horizon_mod_sdk::export_mod!(Guest); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index ca2fe9d7a..0812cde54 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -12,12 +12,27 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `hud` | [`hud`](#hud) | draw text on your screen | | `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 | ## World `horizon-mod` - Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage` - Exports (what the mod provides): `events` +## World `horizon-ui-mod` + +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` +- Exports (what the mod provides): `ui-events`, `events` + +## World `ui-host` + +The game's side of `horizon-ui-mod` beyond `horizon-mod`. + +- Imports (what the game offers): `ui` +- Exports (what the mod provides): `ui-events` + ## `log` Access: always granted. @@ -117,6 +132,79 @@ Capability `storage`: a per-mod folder of small key/value files, quota'd (docs/m | `set` | `func(key: string, value: list) -> 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. | +## `ui` + +Access: capability `ui`. + +Capability `ui`: widgets the game draws with its own menus' widgets, for a screen the mod owns and a settings page in Options > Mods. Layout and drawing are the game's: a mod says what its widgets hold, never where they sit or how they look, and the game clips everything it is handed. + +### record `text-widget` + +A line of text. + +| Field | Type | | +| --- | --- | --- | +| `id` | `u32` | The mod's own name for the widget; `ui-events` calls echo it. | +| `text` | `string` | Up to 256 characters. | +| `color` | `u32` | 0xRRGGBB; 0 is the menus' white. | + +### record `item-widget` + +An item's icon and a name beside it, as recipe viewers show them. + +| Field | Type | | +| --- | --- | --- | +| `id` | `u32` | The mod's own name for the widget. | +| `item` | `string` | `minecraft:diamond`, `:`; an unknown id draws a "?". | +| `name` | `string` | The name shown beside the icon (empty: the item's own). | + +### record `list-widget` + +Rows the player picks one of, as an options page lists choices: a pick is `ui-events::select`, `selected` is the row to mark now. + +| Field | Type | | +| --- | --- | --- | +| `id` | `u32` | The mod's own name for the widget; `ui-events::select` echoes it. | +| `rows` | `list` | The rows' texts, at most 512, each up to 256 characters. | +| `selected` | `option` | The row to mark as the current choice, if any. | + +### variant `widget` + +A thing on a mod's screen or settings page. + +| Case | Payload | | +| --- | --- | --- | +| `text` | `text-widget` | Text the player reads. | +| `item` | `item-widget` | An item's icon and name. | +| `list` | `list-widget` | Rows the player picks from. | + +### record `screen` + +A screen the mod owns: a title over widgets stacked down the middle, the Done button the game adds, and Esc to leave it. + +| Field | Type | | +| --- | --- | --- | +| `title` | `string` | Its title, up to 256 characters. | +| `widgets` | `list` | Its widgets, in order, at most 64. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `open-screen` | `func(screen: screen)` | Show `screen` over the game; a second call while it is open replaces it. Only the last call of one hook counts. | +| `close-screen` | `func()` | Close the mod's screen when it is open (the mod hears no `closed` for this: it was its own doing). | +| `set-settings` | `func(widgets: list)` | The mod's page in Options > Mods, reached from a settings button on its row: the widgets it shows, an empty list for no page. The player opening the page is `ui-events::settings-opened`: push fresh widgets then; later calls update the page while it shows. | + +## `ui-events` + +Access: exported by the mod: the game calls it. + +What the game calls on a mod that shows widgets (capability `ui`): what the player did with them. + +| Function | Signature | What it does | +| --- | --- | --- | +| `select` | `func(id: u32, row: u32)` | A row of one of the mod's `list` widgets was picked: the widget's `id` and the row, on the screen or the settings page that showed it. | +| `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. | + ## `events` Access: exported by the mod: the game calls it. diff --git a/docs/mods.md b/docs/mods.md index bac207f60..45e5ae02e 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -12,7 +12,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | Part | Where | State | |---|---|---| -| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage; tick, frame, chat and command hooks | +| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, ui; 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` | | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | @@ -86,6 +86,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 | +| `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 | | Hook (export) | When | |---|---| @@ -112,7 +113,6 @@ loading. Ordered by what the first native ports need: | `target` | the crosshair's block or entity, with its state and NBT summary | Jade/WTHIT-style tooltips | | `inventory-read` | the player's inventory, held item, open container | AppleSkin, recipe viewers | | `recipes` | the recipe registry and lookups | JEI/EMI-style viewers | -| `ui` | widgets: text, item icons, lists, a screen the mod owns, a settings page in Options > Mods | built from vanilla's widgets (`ui`) so it matches the menus | | `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 | | `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) | From f2832f83ef4e811e744312ac01117114a098f746 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 17:53:13 +0100 Subject: [PATCH 2/4] check: cover the ui open/close-screen outputs Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/cargo-horizon-mod/src/check.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 0294bec98..5d4150ab9 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -215,6 +215,8 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), + Output::OpenScreen { .. } => "opened a screen".to_string(), + Output::CloseScreen { .. } => "closed its screen".to_string(), }); } match failed(&mods) { From 05396b4edfd63209708ecbf767e0b93eea272272 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:57:10 +0100 Subject: [PATCH 3/4] ui: experimental, opted into with experimental = ["ui"] in the manifest docs/api/stability.md: a new API starts experimental, usable only by opting in with a manifest field naming it. Capability ui now needs experimental = ["ui"] beside capabilities; without it the manifest is refused with that line to add. A capability promoted later stays accepted in the list, so such manifests keep loading. The ui test guest opts in; stability.md gets ui's row; docs/mods.md shows the key. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mods/src/manifest.rs | 38 ++++++++++++++++++++++++++++ crates/horizon-mods/tests/sandbox.rs | 1 + docs/api/stability.md | 1 + docs/mods.md | 7 +++-- 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index f1ac123b1..6070f99bd 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -49,6 +49,12 @@ pub struct Manifest { /// that are on may share one (`content::clash`). #[serde(default)] pub namespaces: Vec, + /// The experimental capabilities the mod opts into (`["ui"]`): each one + /// it lists in `capabilities` must be named here too, since it may change + /// in any release (docs/api/stability.md). One no longer experimental is + /// accepted here, so the manifest keeps loading once it is promoted. + #[serde(default)] + pub experimental: Vec, } #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq)] @@ -99,6 +105,11 @@ impl Capability { Capability::Ui => "ui", } } + /// 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) + } /// What the player reads before turning the mod on: "May ". pub fn describe(self) -> &'static str { match self { @@ -169,6 +180,16 @@ impl Manifest { "{MANIFEST}: capability registries needs api = \"0.2\"" )); } + if let Some(c) = m + .capabilities + .iter() + .find(|c| c.is_experimental() && !m.experimental.contains(c)) + { + return Err(format!( + "{MANIFEST}: capability {c} is experimental and may change in any release: \ + add experimental = [\"{c}\"] to use it" + )); + } if !m.namespaces.is_empty() && !m.capabilities.contains(&Capability::Registries) { return Err(format!( "{MANIFEST}: namespaces are for content, which needs capability registries" @@ -421,4 +442,21 @@ capabilities = ["game-read", "hud"] assert_eq!(p.wasm.as_deref(), Some(&b"\0asm"[..])); std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn experimental_capabilities_need_the_opt_in() { + let base = "id = \"m\"\nname = \"M\"\nversion = \"1\"\napi = \"0.1\"\n"; + let err = Manifest::parse(&format!("{base}capabilities = [\"ui\"]\n")).unwrap_err(); + assert!(err.contains("experimental = [\"ui\"]"), "{err}"); + let m = Manifest::parse(&format!( + "{base}capabilities = [\"ui\"]\nexperimental = [\"ui\"]\n" + )) + .unwrap(); + assert_eq!(m.experimental, [Capability::Ui]); + // A capability that is (or became) stable is fine in the list. + Manifest::parse(&format!( + "{base}capabilities = [\"hud\"]\nexperimental = [\"hud\"]\n" + )) + .unwrap(); + } } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index a229f748e..77f0975f3 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -23,6 +23,7 @@ name = "Test UI Guest" version = "0.1.0" api = "0.1" capabilities = ["chat", "ui"] +experimental = ["ui"] "#; /// Builds both mods once and writes their `.hmod` files; returns the folder. diff --git a/docs/api/stability.md b/docs/api/stability.md index 2d4476fc7..ffa9d9b11 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -87,6 +87,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | Part | Level | Version | | --- | --- | --- | | 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"]` | | 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 45e5ae02e..9b3b8aa94 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -86,7 +86,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 | -| `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 | +| `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"]` | | Hook (export) | When | |---|---| @@ -284,10 +284,13 @@ authors = ["..."] api = "0.1" # the API the SDK targets side = "client" # client | server | both capabilities = ["game-read", "hud", "chat"] +experimental = [] # experimental capabilities it uses, e.g. ["ui"] ``` Unknown keys are refused, so a typo is an error, not a silently ignored -permission. +permission. An experimental capability (today `ui`) 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. ### Content mods (API 0.2) From befec1995f0cb89d11b4fd07354116805f6796a5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:57:10 +0100 Subject: [PATCH 4/4] ui: a Settings button appears when the mod sets its page later has_settings was read once, when the mods loaded, so a mod that called set-settings from a command or a tick never got its Settings button until a reload. The Mods page's rows now follow each mod call's output. Also clippy with --features mods: needless borrows of the atlas in draw_mod_screen. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mods.rs | 32 +++++++++++++++----------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 688e29da1..47a3ce07b 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -395,6 +395,12 @@ impl Game<'_> { .chat .add(&self.gui.atlas, line, None, self.ticks, focused); } + // A mod may set or clear its settings page in any call, not only + // while loading: its row's Settings button follows. + let rows = self.settings.mods.installed.iter_mut(); + for (row, e) in rows.zip(self.mods.mods.entries()) { + row.has_settings = e.has_ui_settings(); + } } /// The mods' HUD panels, stacked with the extras in their corners. pub(super) fn draw_mod_panels(&self, batch: &mut HudBatch, corners: &mut Corners) { @@ -521,10 +527,10 @@ impl Game<'_> { let mut items: Vec<(String, f32, f32)> = Vec::new(); let atlas = &self.gui.atlas; let in_world = self.player.is_some(); - ui::menu_background(batch, &atlas, 0.0, 0.0, batch.width, batch.height, in_world); + ui::menu_background(batch, atlas, 0.0, 0.0, batch.width, batch.height, in_world); ui::centered_text( batch, - &atlas, + atlas, &Text::literal(title), 0.0, 15.0, @@ -545,7 +551,7 @@ impl Game<'_> { }; ui::centered_text( batch, - &atlas, + atlas, &Text::literal(t.text.clone()), x, wy + 1.0, @@ -557,7 +563,7 @@ impl Game<'_> { if self.res.items().get(&i.item).is_some() { items.push((i.item.clone(), x + 2.0, wy + 2.0)); } else { - batch.text(&atlas, "?", x + 6.0, wy + 6.0, u32::MAX, true); + batch.text(atlas, "?", x + 6.0, wy + 6.0, u32::MAX, true); } let name = if i.name.is_empty() { i.item.rsplit(':').next().unwrap_or(&i.item).to_string() @@ -565,7 +571,7 @@ impl Game<'_> { i.name.clone() }; batch.text_styled( - &atlas, + atlas, &Text::literal(name), x + 22.0, wy + 6.0, @@ -582,12 +588,12 @@ impl Game<'_> { list_i += 1; let rows_top = wy + 4.0; let rows_bottom = wy + wh - 4.0; - batch.fill(&atlas, x, wy, MOD_UI_COLUMN, wh, 0x8000_0000); + batch.fill(atlas, x, wy, MOD_UI_COLUMN, wh, 0x8000_0000); for (b, yy) in [(x, wy), (x, wy + wh - 1.0)] { - batch.fill(&atlas, b, yy, MOD_UI_COLUMN, 1.0, 0xFF50_5050); + batch.fill(atlas, b, yy, MOD_UI_COLUMN, 1.0, 0xFF50_5050); } for (xx, yy) in [(x, wy), (x + MOD_UI_COLUMN - 1.0, wy)] { - batch.fill(&atlas, xx, yy, 1.0, wh, 0xFF50_5050); + batch.fill(atlas, xx, yy, 1.0, wh, 0xFF50_5050); } let content = l.rows.len() as f32 * 12.0; let first = (scroll.amount / 12.0) as usize; @@ -596,13 +602,13 @@ impl Game<'_> { for (vi, ri) in (first..last).enumerate() { let ry = rows_top + vi as f32 * 12.0 - (scroll.amount % 12.0); if ui::hovered(self.cursor, x, ry, MOD_UI_COLUMN - 6.0, 12.0) { - batch.fill(&atlas, x + 1.0, ry, MOD_UI_COLUMN - 8.0, 12.0, 0x20FF_FFFF); + batch.fill(atlas, x + 1.0, ry, MOD_UI_COLUMN - 8.0, 12.0, 0x20FF_FFFF); } if l.selected == Some(ri as u32) { - batch.fill(&atlas, x + 1.0, ry, 3.0, 12.0, 0xFFFF_FFFF); + batch.fill(atlas, x + 1.0, ry, 3.0, 12.0, 0xFFFF_FFFF); } batch.text_styled( - &atlas, + atlas, &Text::literal(l.rows[ri].clone()), x + 6.0, ry + 2.0, @@ -612,7 +618,7 @@ impl Game<'_> { } ui::scrollbar( batch, - &atlas, + atlas, x + MOD_UI_COLUMN - 5.0, rows_top, rows_bottom, @@ -625,7 +631,7 @@ impl Game<'_> { let hover = ui::hovered(self.cursor, cx - 100.0, batch.height - 27.0, 200.0, 20.0); ui::button( batch, - &atlas, + atlas, cx - 100.0, batch.height - 27.0, 200.0,