From 7e4012c83ec859b5fa18f6f5975e49f97719854a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 04:41:12 +0100 Subject: [PATCH 1/5] Mod API: a key widget, so players bind a mod's keys (ui, input) A ui page's key widget shows one of the mod's keys as Key Binds does ("Zoom: Z"). A click waits for the next key or mouse button, which becomes the key; Esc binds none. The game keeps the choice in horizon-mods.txt (key..:key.keyboard.z), applies it when the mods load and to keys registered later, and lets a held key go when it is rebound. register-key's key is now the default. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 7 +- crates/horizon-client/src/game/mods.rs | 123 +++++++++++++++++- crates/horizon-client/src/mod_list.rs | 52 +++++++- crates/horizon-mod-sdk/wit/horizon.wit | 15 ++- crates/horizon-mods/src/runtime.rs | 67 +++++++++- crates/horizon-mods/tests/sandbox.rs | 41 +++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 11 +- docs/api/mods-reference.md | 12 +- docs/mods.md | 2 +- 9 files changed, 312 insertions(+), 18 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3f7450501..bb68dc590 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10451,6 +10451,9 @@ impl Game<'_> { } return Ok(()); } + if self.screen == Screen::Mod && self.mod_screen_key(key) { + return Ok(()); + } if self.sort_key_press(key) { return Ok(()); } @@ -11363,9 +11366,7 @@ 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() - } + Screen::Mod if pressed => self.mod_screen_click(button), _ => {} } } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 6211f43b1..66d00b233 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -29,6 +29,7 @@ use { }, horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, std::time::Instant, + winit::{event::MouseButton, keyboard::KeyCode}, }; #[derive(Default)] @@ -101,6 +102,8 @@ struct ModScreen { under: Screen, /// One scroll per `list` widget, in widget order. scrolls: Vec, + /// A key widget waiting for the key to bind: the mod key's name. + binding: Option, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. @@ -240,7 +243,10 @@ impl Game<'_> { 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_click(&mut self, _button: winit::event::MouseButton) {} + pub(super) fn mod_screen_key(&mut self, _key: winit::keyboard::KeyCode) -> bool { + false + } pub(super) fn mod_screen_scroll(&mut self, _delta: f32) {} } @@ -263,6 +269,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; + let chosen = &self.settings.mods; + self.mods.mods.set_bindings(|id| chosen.keys_of(id)); // Entries were replaced wholesale: a screen's owner index is stale. self.mods.screen = None; self.list_mods(); @@ -429,6 +437,8 @@ impl Game<'_> { { self.mods.checked = Some(Instant::now()); if self.mods.mods.reload_changed(vanilla_command) { + let chosen = &self.settings.mods; + self.mods.mods.set_bindings(|id| chosen.keys_of(id)); self.list_mods(); self.sync_mod_commands(); self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY)); @@ -579,6 +589,72 @@ impl Game<'_> { Some((s.title.as_str(), s.widgets.as_slice())) } } + /// A key widget's label as Key Binds shows one, "Zoom: Z", marked + /// "> Zoom: Z <" in yellow while it waits for the new key. + fn mod_key_label(mods: &Mods, owner: usize, name: &str, waiting: bool) -> Text { + let (label, key) = mods + .keys_of(owner) + .iter() + .find(|k| k.name == name) + .map_or((name, "key.keyboard.unknown"), |k| { + (k.label.as_str(), k.key.as_str()) + }); + let value = format!("{label}: {}", keybinds::display_name(key).plain()); + if waiting { + Text::literal(format!("> {value} <")).with_color(text::YELLOW) + } else { + Text::literal(value) + } + } + /// The player bound the key widget that waited to `key`: the mod's key + /// follows it now and at the next start (`horizon-mods.txt`). + fn bind_mod_key(&mut self, key: String) { + let Some(ms) = self.mods.screen.as_mut() else { + return; + }; + let Some(name) = ms.binding.take() else { + return; + }; + let owner = ms.owner; + if !self.mods.mods.rebind(owner, &name, &key) { + return; + } + let Some(id) = self + .mods + .mods + .entries() + .get(owner) + .and_then(|e| e.manifest.as_ref()) + .map(|m| m.id.clone()) + else { + return; + }; + self.settings + .mods + .keys + .entry(id) + .or_default() + .insert(name, key); + self.settings.save(&Self::options_path()); + } + /// A key while a mod screen is up: true when a key widget waited for + /// it (Key Binds: Escape binds none). + pub(super) fn mod_screen_key(&mut self, key: KeyCode) -> bool { + if self + .mods + .screen + .as_ref() + .is_none_or(|ms| ms.binding.is_none()) + { + return false; + } + let value = match key { + KeyCode::Escape => None, + k => keybinds::key_name(k), + }; + self.bind_mod_key(value.unwrap_or("key.keyboard.unknown").to_owned()); + true + } /// 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(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { @@ -587,7 +663,7 @@ impl Game<'_> { for w in widgets { let wh = match w { UiWidget::Text(_) => 12.0, - UiWidget::Item(_) | UiWidget::Button(_) => 20.0, + UiWidget::Item(_) | UiWidget::Button(_) | UiWidget::Key(_) => 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. @@ -617,6 +693,7 @@ impl Game<'_> { settings, under: self.screen, scrolls: Vec::new(), + binding: None, }); self.screen = Screen::Mod; if self.player.is_some() { @@ -697,6 +774,22 @@ impl Game<'_> { hover, ); } + UiWidget::Key(k) => { + let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0); + let waiting = ms.binding.as_deref() == Some(k.key.as_str()); + let label = Self::mod_key_label(&self.mods.mods, ms.owner, &k.key, waiting); + ui::button( + batch, + atlas, + x, + wy, + MOD_UI_COLUMN, + 20.0, + &label, + true, + hover, + ); + } UiWidget::Text(t) => { let color = if t.color == 0 { u32::MAX @@ -798,7 +891,20 @@ impl Game<'_> { } /// 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) { + pub(super) fn mod_screen_click(&mut self, button: MouseButton) { + // Key Binds: a mouse button pressed while waiting binds it. + if self + .mods + .screen + .as_ref() + .is_some_and(|ms| ms.binding.is_some()) + { + self.bind_mod_key(keybinds::mouse_name(button)); + return; + } + if button != MouseButton::Left { + return; + } 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) { @@ -829,6 +935,17 @@ impl Game<'_> { self.show_mod_output(); return; } + // A key widget waits for the key to bind. + if let UiWidget::Key(k) = w + && ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0) + { + self.audio.play_button_click(); + let name = k.key.clone(); + if let Some(ms) = self.mods.screen.as_mut() { + ms.binding = Some(name); + } + return; + } let UiWidget::List(l) = w else { continue }; let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default(); list_i += 1; diff --git a/crates/horizon-client/src/mod_list.rs b/crates/horizon-client/src/mod_list.rs index db2ea9194..325839738 100644 --- a/crates/horizon-client/src/mod_list.rs +++ b/crates/horizon-client/src/mod_list.rs @@ -1,7 +1,11 @@ //! Which of the installed Horizon mods are on (`docs/mods.md`), kept in //! `horizon-mods.txt` beside `options.txt` as `mod.:true` lines. Every //! mod is off until the player turns it on in Options > Mods. -use std::{collections::BTreeSet, fs, path::Path}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::Path, +}; pub const FILE: &str = "horizon-mods.txt"; /// The folder holding `.hmod` files, beside `options.txt`. @@ -11,6 +15,9 @@ pub const DIR: &str = "horizon-mods"; pub struct ModList { /// Ids of the mods the player turned on. pub enabled: BTreeSet, + /// The keys the player chose for mods' keys, mod id → key name → key + /// (`key..:key.keyboard.x` lines). + pub keys: BTreeMap>, /// What the Mods page shows, filled by the game from the mods it found. pub installed: Vec, } @@ -45,20 +52,41 @@ impl ModList { .filter_map(|(k, _)| k.trim().strip_prefix("mod.")) .map(str::to_owned) .collect(); + let mut keys: BTreeMap> = BTreeMap::new(); + for (k, v) in text.lines().filter_map(|l| l.split_once(':')) { + // Mod ids have no dots; a key's name may. + if let Some((id, name)) = k + .trim() + .strip_prefix("key.") + .and_then(|r| r.split_once('.')) + { + let entry = keys.entry(id.to_owned()).or_default(); + entry.insert(name.to_owned(), v.trim().to_owned()); + } + } Self { enabled, + keys, installed: Vec::new(), } } pub fn serialize(&self) -> String { - self.enabled - .iter() - .map(|id| format!("mod.{id}:true\n")) - .collect() + let on = self.enabled.iter().map(|id| format!("mod.{id}:true\n")); + let keys = self.keys.iter().flat_map(|(id, keys)| { + keys.iter() + .map(move |(name, key)| format!("key.{id}.{name}:{key}\n")) + }); + on.chain(keys).collect() + } + /// Mod `id`'s chosen keys, for `Mods::set_bindings`. + pub fn keys_of(&self, id: &str) -> Vec<(&str, &str)> { + self.keys.get(id).map_or_else(Vec::new, |k| { + k.iter().map(|(n, k)| (n.as_str(), k.as_str())).collect() + }) } pub fn save(&self, dir: &Path) { let path = dir.join(FILE); - if self.enabled.is_empty() && !path.exists() { + if self.enabled.is_empty() && self.keys.is_empty() && !path.exists() { return; } let _ = fs::write(path, self.serialize()); @@ -91,6 +119,18 @@ mod tests { assert_eq!(ModList::default().serialize(), ""); } + #[test] + fn keeps_the_keys_players_chose() { + let text = "mod.zoom:true\nkey.zoom.zoom.in:key.mouse.4\nkey.zoom.out:key.keyboard.x\n"; + let list = ModList::parse(text); + assert_eq!( + list.keys_of("zoom"), + [("out", "key.keyboard.x"), ("zoom.in", "key.mouse.4")] + ); + assert!(list.keys_of("other").is_empty()); + assert_eq!(ModList::parse(&list.serialize()), list); + } + #[test] fn toggles_installed_mods_but_not_dev_ones() { let installed = |id: &str, dev| Installed { diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 820a82483..f9c147cfa 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -137,6 +137,16 @@ interface ui { /// Up to 256 characters. label: string, } + /// One of the mod's keys (`input.register-key`) as Controls shows a + /// binding, "Zoom: Z". A click waits for the next key or mouse button, + /// which becomes the key (Esc: none). The game keeps the player's + /// choice across starts; the mod's `key-down` and `key-up` follow it. + record key-widget { + /// The mod's own name for the widget. + id: u32, + /// The name the mod registered the key under. + key: string, + } variant widget { /// Text the player reads. text(text-widget), @@ -146,6 +156,8 @@ interface ui { item(item-widget), /// Rows the player picks from. %list(list-widget), + /// A key the player binds. + key(key-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. @@ -220,7 +232,8 @@ interface input { claim-items: func(ids: list); /// A key of the mod's: `name` comes back in `key-down` and `key-up`, /// `label` says what it does, `key` is the key as options.txt writes - /// it (`key.keyboard.r`). At most 16; an unknown key is an error. + /// it (`key.keyboard.r`), the default: a key the player chose for it + /// (`ui`'s key widget) wins. At most 16; an unknown key is an error. register-key: func(name: string, label: string, key: string) -> result<_, string>; /// The main hand's stack, as of this tick; none when it is empty. held: func() -> option; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 0e7c079d2..f596db81c 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -37,7 +37,8 @@ use bindings::{ /// 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::{ - ButtonWidget, ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget, + ButtonWidget, ItemWidget, KeyWidget, 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. @@ -564,6 +565,48 @@ impl Mods { d.input.keys.iter().map(move |k| (d.name.as_str(), k)) }) } + /// Mod `i`'s keys, as it registered them (with the player's choices). + pub fn keys_of(&self, i: usize) -> &[ModKey] { + self.entries + .get(i) + .and_then(|e| e.run.as_ref()) + .map_or(&[], |r| r.store.data().input.keys.as_slice()) + } + /// The keys the player chose (`ui`'s key widget), by mod id: each + /// running mod's `name → key`. They replace the defaults registered + /// so far and later ones. Keys that aren't keys are skipped. + pub fn set_bindings<'a>(&mut self, chosen: impl Fn(&str) -> Vec<(&'a str, &'a str)>) { + for e in &mut self.entries { + let (Some(m), Some(run)) = (&e.manifest, e.run.as_mut()) else { + continue; + }; + let input = &mut run.store.data_mut().input; + input.bindings = chosen(&m.id) + .into_iter() + .filter(|(_, key)| key_ok(key)) + .map(|(n, k)| (n.to_owned(), k.to_owned())) + .collect(); + for (name, key) in input.bindings.clone() { + input.rebind(&name, key); + } + } + } + /// The player binds mod `i`'s key `name` to `key` (`key.keyboard.x`, + /// `key.mouse.4`, `key.keyboard.unknown` for none). False when the mod + /// has no such key or `key` isn't one. + pub fn rebind(&mut self, i: usize, name: &str, key: &str) -> bool { + let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) else { + return false; + }; + let input = &mut run.store.data_mut().input; + if !key_ok(key) || !input.keys.iter().any(|k| k.name == name) { + return false; + } + input.bindings.retain(|(n, _)| n != name); + input.bindings.push((name.to_owned(), key.to_owned())); + input.rebind(name, key.to_owned()); + true + } /// The use button went down with `item`: `use-start` to each mod that /// claimed it. pub fn use_start(&mut self, item: &HeldItem) { @@ -813,6 +856,10 @@ fn clip_widgets(widgets: Vec) -> Vec { l.selected = l.selected.filter(|&s| (s as usize) < l.rows.len()); UiWidget::List(l) } + UiWidget::Key(mut k) => { + k.key = clip(k.key); + UiWidget::Key(k) + } }) .collect() } @@ -873,6 +920,9 @@ struct InputState { down: Vec, /// It holds the mouse wheel. wheel: bool, + /// The keys the player chose, `name → key`: they win over + /// `register-key`'s. + bindings: Vec<(String, String)>, } /// Events kept for `poll`, items claimed and keys, per mod. const INPUT_EVENTS: usize = 256; @@ -893,6 +943,17 @@ fn key_ok(key: &str) -> bool { } impl InputState { + /// Key `name` is `key` now; held, it lets go first. + fn rebind(&mut self, name: &str, key: String) { + let Some(k) = self.keys.iter_mut().find(|k| k.name == name) else { + return; + }; + k.key = key; + if let Some(i) = self.down.iter().position(|n| n == name) { + let name = self.down.swap_remove(i); + self.push(InputEvent::KeyUp(name)); + } + } fn push(&mut self, event: InputEvent) { if self.events.len() == INPUT_EVENTS { self.events.pop_front(); @@ -912,6 +973,10 @@ impl input::Host for State { )); } let (name, label) = (clip(name), clip(label)); + let key = match self.input.bindings.iter().find(|(n, _)| *n == name) { + Some((_, chosen)) => chosen.clone(), + None => key, + }; if let Some(k) = self.input.keys.iter_mut().find(|k| k.name == name) { (k.label, k.key) = (label, key); return Ok(()); diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 29577a9c6..793d03db6 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -449,7 +449,7 @@ fn ui_screens_settings_and_events() { 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(), 2); + assert_eq!(mods.settings_widgets(0).len(), 3); // `/ui_close` closes the mod's own screen. assert!(mods.command("ui_close")); assert!(mods.drain().contains(&Output::CloseScreen { owner: 0 })); @@ -553,6 +553,45 @@ fn input_claims_keys_and_events() { assert_eq!(chat(&mut mods), ["key-down wheel", "key-up wheel"]); } +#[test] +fn the_players_key_choice_wins() { + let chat = |mods: &mut Mods| -> Vec { + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect() + }; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + assert!(mods.command("input_claim")); + assert!(matches!( + &mods.settings_widgets(0)[0], + horizon_mods::UiWidget::Key(k) if k.id == 9 && k.key == "wheel" + )); + // Rebinding while held lets the old key go. + mods.key("key.keyboard.r", true); + assert!(mods.rebind(0, "wheel", "key.mouse.4")); + assert_eq!(mods.keys_of(0)[0].key, "key.mouse.4"); + mods.key("key.keyboard.r", false); + mods.key("key.mouse.4", true); + assert!(!mods.rebind(0, "wheel", "R") && !mods.rebind(0, "nope", "key.keyboard.g")); + chat(&mut mods); + assert!(mods.command("input_poll")); + assert_eq!( + chat(&mut mods), + ["key-down wheel", "key-up wheel", "key-down wheel"] + ); + // A choice saved earlier replaces the default, registered before or after. + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + mods.set_bindings(|_| vec![("wheel", "key.keyboard.g"), ("bad", "G")]); + assert!(mods.command("input_claim")); + assert_eq!(mods.keys_of(0)[0].key, "key.keyboard.g"); + mods.set_bindings(|_| vec![("wheel", "key.keyboard.h")]); + assert_eq!(mods.keys_of(0)[0].key, "key.keyboard.h"); +} + #[test] fn input_wheel_is_the_mods_while_claimed() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 9bede11f9..f2765e8da 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -9,7 +9,7 @@ use horizon_mod_sdk::{ Mod, Registration, chat, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, - ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, + ui::{self, ItemWidget, KeyWidget, ListWidget, Screen, TextWidget, Widget}, }; /// One of each shape, the text too long by 44 characters. @@ -162,6 +162,10 @@ impl Mod for Guest { // Not a key: refused. let bad = input::register_key("bad", "Bad", "R").unwrap_err(); chat::show(&format!("claimed; {bad}")); + ui::set_settings(&[Widget::Key(KeyWidget { + id: 9, + key: "wheel".into(), + })]); } "input_poll" => { for event in input::poll() { @@ -225,6 +229,11 @@ impl Mod for Guest { id: 3, label: "Corner: Top Right".into(), }), + // `/input_claim`'s key; drawn as its name until registered. + Widget::Key(KeyWidget { + id: 9, + key: "wheel".into(), + }), ]); chat::show("settings opened"); } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 0deeb0ddd..f525ace89 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -197,6 +197,15 @@ A thing on a mod's screen or settings page. A button as the options pages have t | `id` | `u32` | The mod's own name for the widget. | | `label` | `string` | Up to 256 characters. | +### record `key-widget` + +One of the mod's keys (`input.register-key`) as Controls shows a binding, "Zoom: Z". A click waits for the next key or mouse button, which becomes the key (Esc: none). The game keeps the player's choice across starts; the mod's `key-down` and `key-up` follow it. + +| Field | Type | | +| --- | --- | --- | +| `id` | `u32` | The mod's own name for the widget. | +| `key` | `string` | The name the mod registered the key under. | + ### variant `widget` | Case | Payload | | @@ -205,6 +214,7 @@ A thing on a mod's screen or settings page. A button as the options pages have t | `button` | `button-widget` | A button. | | `item` | `item-widget` | An item's icon and name. | | `list` | `list-widget` | Rows the player picks from. | +| `key` | `key-widget` | A key the player binds. | ### record `screen` @@ -278,7 +288,7 @@ A mapping as the player has bound it. | Function | Signature | What it does | | --- | --- | --- | | `claim-items` | `func(ids: list)` | The items whose use the mod handles instead of the game, by id (at most 64). Replaces the previous list. | -| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`). At most 16; an unknown key is an error. | +| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`), the default: a key the player chose for it (`ui`'s key widget) wins. At most 16; an unknown key is an error. | | `held` | `func() -> option` | The main hand's stack, as of this tick; none when it is empty. | | `poll` | `func() -> list` | The events since the last call, oldest first. | | `claim-wheel` | `func(on: bool)` | Takes the mouse wheel while playing (true) or gives it back: while taken, its steps are the mod's `wheel` events and the hotbar doesn't move. The game gives it back when the mod stops. | diff --git a/docs/mods.md b/docs/mods.md index 235574d6c..108e854be 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,7 +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 | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item, list and key widgets the game lays out and draws with its own menus' code. A key widget binds one of the mod's keys (`input.register-key`) as Key Binds does: click, then press the key or mouse button (Esc: none); the game keeps the choice in `horizon-mods.txt` (`key..:key.keyboard.z`) and the mod's `key-down` follows it. **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; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | From 3e3c0cebb51fa5deb0022ff1c0ca8fa4ba9fc42d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:34:49 +0100 Subject: [PATCH 2/5] Mod keys: rows the game adds to the settings page, not a WIT widget A new case in ui's widget variant stops every ui mod built before it from loading: the runtime links a component only when each imported function's types match exactly ("expected variant of 5 cases, found 4"), so the published FPS Counter and Keystrokes would break. Instead, the game lists a mod's keys first on its page in Options > Mods, as Key Binds rows, and a mod with keys gets a page even without ui. No WIT type changes. docs/api/stability.md said a new case the mod sends isn't breaking; it is, and now says so. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mods.rs | 113 ++++++++++-------- crates/horizon-mod-sdk/wit/horizon.wit | 17 +-- crates/horizon-mods/src/runtime.rs | 17 ++- crates/horizon-mods/tests/sandbox.rs | 8 +- crates/horizon-mods/tests/ui_guest/src/lib.rs | 11 +- docs/api/mods-reference.md | 12 +- docs/api/stability.md | 9 +- docs/mods.md | 4 +- 8 files changed, 86 insertions(+), 105 deletions(-) diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 66d00b233..e55a87d46 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -27,7 +27,7 @@ use { text::{self, Text}, ui, }, - horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, + horizon_mods::{Clock, ModKey, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, std::time::Instant, winit::{event::MouseButton, keyboard::KeyCode}, }; @@ -102,7 +102,7 @@ struct ModScreen { under: Screen, /// One scroll per `list` widget, in widget order. scrolls: Vec, - /// A key widget waiting for the key to bind: the mod key's name. + /// A key row waiting for the key to bind: the mod key's name. binding: Option, } impl ModsState { @@ -575,7 +575,7 @@ impl Game<'_> { fn mod_ui_view<'a>(mods: &'a Mods, ms: &ModScreen) -> Option<(&'a str, &'a [UiWidget])> { if ms.settings { let widgets = mods.settings_widgets(ms.owner); - if widgets.is_empty() { + if widgets.is_empty() && mods.keys_of(ms.owner).is_empty() { return None; } let name = mods @@ -589,24 +589,25 @@ impl Game<'_> { Some((s.title.as_str(), s.widgets.as_slice())) } } - /// A key widget's label as Key Binds shows one, "Zoom: Z", marked + /// The keys a settings page lists first: the mod's own (`input`). + fn mod_page_keys<'a>(mods: &'a Mods, ms: &ModScreen) -> &'a [ModKey] { + if ms.settings { + mods.keys_of(ms.owner) + } else { + &[] + } + } + /// A key row's label as Key Binds shows one, "Zoom: Z", marked /// "> Zoom: Z <" in yellow while it waits for the new key. - fn mod_key_label(mods: &Mods, owner: usize, name: &str, waiting: bool) -> Text { - let (label, key) = mods - .keys_of(owner) - .iter() - .find(|k| k.name == name) - .map_or((name, "key.keyboard.unknown"), |k| { - (k.label.as_str(), k.key.as_str()) - }); - let value = format!("{label}: {}", keybinds::display_name(key).plain()); + fn mod_key_label(k: &ModKey, waiting: bool) -> Text { + let value = format!("{}: {}", k.label, keybinds::display_name(&k.key).plain()); if waiting { Text::literal(format!("> {value} <")).with_color(text::YELLOW) } else { Text::literal(value) } } - /// The player bound the key widget that waited to `key`: the mod's key + /// The player bound the key row that waited to `key`: the mod's key /// follows it now and at the next start (`horizon-mods.txt`). fn bind_mod_key(&mut self, key: String) { let Some(ms) = self.mods.screen.as_mut() else { @@ -637,7 +638,7 @@ impl Game<'_> { .insert(name, key); self.settings.save(&Self::options_path()); } - /// A key while a mod screen is up: true when a key widget waited for + /// A key while a mod screen is up: true when a key row waited for /// it (Key Binds: Escape binds none). pub(super) fn mod_screen_key(&mut self, key: KeyCode) -> bool { if self @@ -657,13 +658,13 @@ impl Game<'_> { } /// 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(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { + fn mod_ui_layout(h: f32, top: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { let mut out = Vec::with_capacity(widgets.len()); - let mut y = MOD_UI_TOP; + let mut y = top; for w in widgets { let wh = match w { UiWidget::Text(_) => 12.0, - UiWidget::Item(_) | UiWidget::Button(_) | UiWidget::Key(_) => 20.0, + UiWidget::Item(_) | UiWidget::Button(_) => 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. @@ -683,7 +684,8 @@ impl Game<'_> { } if settings { self.mods.mods.ui_settings_opened(owner); - if self.mods.mods.settings_widgets(owner).is_empty() { + let keys = self.mods.mods.keys_of(owner); + if self.mods.mods.settings_widgets(owner).is_empty() && keys.is_empty() { self.show_mod_output(); return; } @@ -755,7 +757,27 @@ impl Game<'_> { ); let cx = (batch.width / 2.0).floor(); let x = cx - MOD_UI_COLUMN / 2.0; - let layout = Self::mod_ui_layout(batch.height, widgets); + // A settings page starts with the mod's keys, as Key Binds rows. + let keys = Self::mod_page_keys(&self.mods.mods, ms); + for (i, k) in keys.iter().enumerate() { + let wy = MOD_UI_TOP + i as f32 * MOD_UI_KEY_ROW; + let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0); + let waiting = ms.binding.as_deref() == Some(k.name.as_str()); + let label = Self::mod_key_label(k, waiting); + ui::button( + batch, + atlas, + x, + wy, + MOD_UI_COLUMN, + 20.0, + &label, + true, + hover, + ); + } + let top = MOD_UI_TOP + keys.len() as f32 * MOD_UI_KEY_ROW; + let layout = Self::mod_ui_layout(batch.height, top, widgets); let mut list_i = 0usize; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { match w { @@ -774,22 +796,6 @@ impl Game<'_> { hover, ); } - UiWidget::Key(k) => { - let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0); - let waiting = ms.binding.as_deref() == Some(k.key.as_str()); - let label = Self::mod_key_label(&self.mods.mods, ms.owner, &k.key, waiting); - ui::button( - batch, - atlas, - x, - wy, - MOD_UI_COLUMN, - 20.0, - &label, - true, - hover, - ); - } UiWidget::Text(t) => { let color = if t.color == 0 { u32::MAX @@ -920,7 +926,22 @@ impl Game<'_> { }; let owner = ms.owner; let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; - let layout = Self::mod_ui_layout(h, widgets); + // A key row waits for the key to bind. + let keys = Self::mod_page_keys(&self.mods.mods, ms); + let picked = (0..keys.len()).find(|&i| { + let wy = MOD_UI_TOP + i as f32 * MOD_UI_KEY_ROW; + ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0) + }); + if let Some(i) = picked { + let name = keys[i].name.clone(); + self.audio.play_button_click(); + if let Some(ms) = self.mods.screen.as_mut() { + ms.binding = Some(name); + } + return; + } + let top = MOD_UI_TOP + keys.len() as f32 * MOD_UI_KEY_ROW; + let layout = Self::mod_ui_layout(h, top, widgets); let mut list_i = 0usize; // The `ui_select` call needs `&mut`: find the pick first. let mut hit = None; @@ -935,17 +956,6 @@ impl Game<'_> { self.show_mod_output(); return; } - // A key widget waits for the key to bind. - if let UiWidget::Key(k) = w - && ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0) - { - self.audio.play_button_click(); - let name = k.key.clone(); - if let Some(ms) = self.mods.screen.as_mut() { - ms.binding = Some(name); - } - return; - } let UiWidget::List(l) = w else { continue }; let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default(); list_i += 1; @@ -975,7 +985,9 @@ impl Game<'_> { return; }; let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; - let layout = Self::mod_ui_layout(h, widgets); + let top = + MOD_UI_TOP + Self::mod_page_keys(&self.mods.mods, ms).len() as f32 * MOD_UI_KEY_ROW; + let layout = Self::mod_ui_layout(h, top, widgets); let mut list_i = 0usize; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { let UiWidget::List(l) = w else { continue }; @@ -995,3 +1007,6 @@ impl Game<'_> { const MOD_UI_TOP: f32 = 40.0; #[cfg(feature = "mods")] const MOD_UI_COLUMN: f32 = 200.0; +/// A key row's height with its gap, as the widgets below it space out. +#[cfg(feature = "mods")] +const MOD_UI_KEY_ROW: f32 = 26.0; diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index f9c147cfa..9088c0c39 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -137,16 +137,6 @@ interface ui { /// Up to 256 characters. label: string, } - /// One of the mod's keys (`input.register-key`) as Controls shows a - /// binding, "Zoom: Z". A click waits for the next key or mouse button, - /// which becomes the key (Esc: none). The game keeps the player's - /// choice across starts; the mod's `key-down` and `key-up` follow it. - record key-widget { - /// The mod's own name for the widget. - id: u32, - /// The name the mod registered the key under. - key: string, - } variant widget { /// Text the player reads. text(text-widget), @@ -156,8 +146,6 @@ interface ui { item(item-widget), /// Rows the player picks from. %list(list-widget), - /// A key the player binds. - key(key-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. @@ -232,8 +220,9 @@ interface input { claim-items: func(ids: list); /// A key of the mod's: `name` comes back in `key-down` and `key-up`, /// `label` says what it does, `key` is the key as options.txt writes - /// it (`key.keyboard.r`), the default: a key the player chose for it - /// (`ui`'s key widget) wins. At most 16; an unknown key is an error. + /// it (`key.keyboard.r`), the default: the player can bind another + /// one on the mod's page in Options > Mods, and that one wins. At most + /// 16; an unknown key is an error. register-key: func(name: string, label: string, key: string) -> result<_, string>; /// The main hand's stack, as of this tick; none when it is empty. held: func() -> option; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index f596db81c..0011fa99d 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -37,8 +37,7 @@ use bindings::{ /// 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::{ - ButtonWidget, ItemWidget, KeyWidget, ListWidget, Screen as UiScreen, TextWidget, - Widget as UiWidget, + ButtonWidget, 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. @@ -153,11 +152,13 @@ pub struct Entry { } 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. + /// with `ui.set-settings`, or `input` registered keys the player may + /// bind there): 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()) + self.run.as_ref().is_some_and(|r| { + let d = r.store.data(); + !d.ui.settings.is_empty() || !d.input.keys.is_empty() + }) } } @@ -856,10 +857,6 @@ fn clip_widgets(widgets: Vec) -> Vec { l.selected = l.selected.filter(|&s| (s as usize) < l.rows.len()); UiWidget::List(l) } - UiWidget::Key(mut k) => { - k.key = clip(k.key); - UiWidget::Key(k) - } }) .collect() } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 793d03db6..3b33ab4b2 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -449,7 +449,7 @@ fn ui_screens_settings_and_events() { 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(), 3); + assert_eq!(mods.settings_widgets(0).len(), 2); // `/ui_close` closes the mod's own screen. assert!(mods.command("ui_close")); assert!(mods.drain().contains(&Output::CloseScreen { owner: 0 })); @@ -566,10 +566,8 @@ fn the_players_key_choice_wins() { }; let mut mods = load("horizon_mods_test_ui_guest.hmod"); assert!(mods.command("input_claim")); - assert!(matches!( - &mods.settings_widgets(0)[0], - horizon_mods::UiWidget::Key(k) if k.id == 9 && k.key == "wheel" - )); + // Its keys alone give it a page in Options > Mods, where the game lists them. + assert!(mods.settings_widgets(0).is_empty() && mods.entries()[0].has_ui_settings()); // Rebinding while held lets the old key go. mods.key("key.keyboard.r", true); assert!(mods.rebind(0, "wheel", "key.mouse.4")); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index f2765e8da..9bede11f9 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -9,7 +9,7 @@ use horizon_mod_sdk::{ Mod, Registration, chat, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, - ui::{self, ItemWidget, KeyWidget, ListWidget, Screen, TextWidget, Widget}, + ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; /// One of each shape, the text too long by 44 characters. @@ -162,10 +162,6 @@ impl Mod for Guest { // Not a key: refused. let bad = input::register_key("bad", "Bad", "R").unwrap_err(); chat::show(&format!("claimed; {bad}")); - ui::set_settings(&[Widget::Key(KeyWidget { - id: 9, - key: "wheel".into(), - })]); } "input_poll" => { for event in input::poll() { @@ -229,11 +225,6 @@ impl Mod for Guest { id: 3, label: "Corner: Top Right".into(), }), - // `/input_claim`'s key; drawn as its name until registered. - Widget::Key(KeyWidget { - id: 9, - key: "wheel".into(), - }), ]); chat::show("settings opened"); } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index f525ace89..a51fb904b 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -197,15 +197,6 @@ A thing on a mod's screen or settings page. A button as the options pages have t | `id` | `u32` | The mod's own name for the widget. | | `label` | `string` | Up to 256 characters. | -### record `key-widget` - -One of the mod's keys (`input.register-key`) as Controls shows a binding, "Zoom: Z". A click waits for the next key or mouse button, which becomes the key (Esc: none). The game keeps the player's choice across starts; the mod's `key-down` and `key-up` follow it. - -| Field | Type | | -| --- | --- | --- | -| `id` | `u32` | The mod's own name for the widget. | -| `key` | `string` | The name the mod registered the key under. | - ### variant `widget` | Case | Payload | | @@ -214,7 +205,6 @@ One of the mod's keys (`input.register-key`) as Controls shows a binding, "Zoom: | `button` | `button-widget` | A button. | | `item` | `item-widget` | An item's icon and name. | | `list` | `list-widget` | Rows the player picks from. | -| `key` | `key-widget` | A key the player binds. | ### record `screen` @@ -288,7 +278,7 @@ A mapping as the player has bound it. | Function | Signature | What it does | | --- | --- | --- | | `claim-items` | `func(ids: list)` | The items whose use the mod handles instead of the game, by id (at most 64). Replaces the previous list. | -| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`), the default: a key the player chose for it (`ui`'s key widget) wins. At most 16; an unknown key is an error. | +| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`), the default: the player can bind another one on the mod's page in Options > Mods, and that one wins. At most 16; an unknown key is an error. | | `held` | `func() -> option` | The main hand's stack, as of this tick; none when it is empty. | | `poll` | `func() -> list` | The events since the last call, oldest first. | | `claim-wheel` | `func(on: bool)` | Takes the mouse wheel while playing (true) or gives it back: while taken, its steps are the mod's `wheel` events and the hotbar doesn't move. The game gives it back when the mod stops. | diff --git a/docs/api/stability.md b/docs/api/stability.md index 132c971f9..d5bd0e545 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -26,12 +26,13 @@ promise, how something is deprecated and removed, and the tests that keep old mo ## What counts as a breaking change Breaking: removing or renaming anything; changing a type, a default, a unit or a meaning; making something optional -required; refusing input that was accepted; a new case in a WIT `enum` or `variant` the game sends to mods (an older -component cannot decode it); a JSON field that changes type. +required; refusing input that was accepted; any change to a WIT type a function uses, a new `enum` or `variant` case +included, in either direction (the runtime links a component only when each imported function's types match exactly: +a mod built before the change no longer loads); a JSON field that changes type. Not breaking: a new function, interface, capability, command, endpoint, tool or `server.toml` key; a new optional -argument or JSON field (readers must ignore fields they don't know); a new WIT case the mod *sends* (the game decodes -every case it ever served); faster, or fixing behaviour to what the reference already says. +argument or JSON field (readers must ignore fields they don't know); a new WIT function or type (mods built earlier +don't import it); faster, or fixing behaviour to what the reference already says. ## Stability levels diff --git a/docs/mods.md b/docs/mods.md index 108e854be..a8d8da851 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,9 +87,9 @@ 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 | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item, list and key widgets the game lays out and draws with its own menus' code. A key widget binds one of the mod's keys (`input.register-key`) as Key Binds does: click, then press the key or mouse button (Esc: none); the game keeps the choice in `horizon-mods.txt` (`key..:key.keyboard.z`) and the mod's `key-down` follows it. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, 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; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | -| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | +| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | | Hook (export) | When | |---|---| From 1aa6f21620833327a6c9aeaa7ab95764682c1041 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:27:14 +0100 Subject: [PATCH 3/5] Horizon shader packs: the post stage runs in the game, with hot reload A native pack named by HORIZON_SHADER_PACK (a folder with horizon-shaders.toml or a .hshader in shaderpacks/) is checked, then its post passes run over the world's own target, the one a shaders/ pack reads: no second target and no extra pass, and without a pack the frame only tests one Option. The pack is looked at twice a second; a saved file is checked and rebuilt in place, and a version that fails is refused in the chat while the last good one keeps drawing. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/game.rs | 4 + .../horizon-client/src/game/native_shaders.rs | 110 ++++ .../horizon-client/src/game/shader_packs.rs | 16 +- crates/horizon-client/src/gfx.rs | 59 +- crates/horizon-client/src/gfx/native_post.rs | 509 ++++++++++++++++++ .../packs/golden_hour/post/glow.wgsl | 15 +- crates/horizon-shader-api/src/inputs.rs | 2 +- crates/horizon-shader-api/src/package.rs | 7 + docs/api/shaders-reference.md | 2 +- docs/api/shaders.md | 1 + docs/shaders.md | 16 +- 13 files changed, 723 insertions(+), 21 deletions(-) create mode 100644 crates/horizon-client/src/game/native_shaders.rs create mode 100644 crates/horizon-client/src/gfx/native_post.rs diff --git a/Cargo.lock b/Cargo.lock index 25c1ae15d..201f7c83c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1364,6 +1364,7 @@ dependencies = [ "horizon-mods", "horizon-protocol", "horizon-server-files", + "horizon-shader-api", "horizon-shaders", "horizon-telemetry", "horizon-theme", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 4877c18f2..a585ce19e 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -18,6 +18,8 @@ horizon-protocol = { path = "../horizon-protocol" } horizon-server-files = { path = "../horizon-server-files" } # Shader packs: reading them and turning their GLSL into naga modules. horizon-shaders = { path = "../horizon-shaders" } +# Horizon's own shader packs: the format, the stages and the check (docs/shaders.md). +horizon-shader-api = { path = "../horizon-shader-api" } horizon-friends = { path = "../horizon-friends" } # Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). # Their runtime is the `mods` feature. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9a3503666..4638a4667 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -106,6 +106,7 @@ mod mounts; mod moving_pistons; mod music; mod names; +mod native_shaders; mod natural_spawning; mod nautili; mod net_harness; @@ -1507,6 +1508,8 @@ struct Game<'a> { extras: extras::ExtrasState, /// Horizon mods (`game/mods.rs`), none running unless turned on. mods: mods::ModsState, + /// Horizon's own shader pack, while one is picked (`game/native_shaders.rs`). + native_shaders: native_shaders::NativeShaders, /// Meshed sections waiting for an upload budget (Horizon settings). pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>, /// This frame's view frustum, for culling entities and block entities. @@ -12309,6 +12312,7 @@ impl<'a> Game<'a> { frame_graph: Default::default(), extras: Default::default(), mods: Default::default(), + native_shaders: Default::default(), sky_darken_memo: Default::default(), persist: Default::default(), remote: None, diff --git a/crates/horizon-client/src/game/native_shaders.rs b/crates/horizon-client/src/game/native_shaders.rs new file mode 100644 index 000000000..62aaafc42 --- /dev/null +++ b/crates/horizon-client/src/game/native_shaders.rs @@ -0,0 +1,110 @@ +//! Horizon's own shader packs in the game (docs/shaders.md), for development until the Shader +//! Packs page exists: `HORIZON_SHADER_PACK=` naming one in `shaderpacks/` (a folder with +//! `horizon-shaders.toml`, or a `.hshader`) runs it once it passes `horizon_shader_api::check`. +//! The pack is looked at twice a second: a saved file is checked and the pack rebuilt, and a +//! pack that fails is refused with its problems in the chat while the last good one keeps +//! drawing. + +use std::{ + hash::{Hash, Hasher}, + path::Path, + time::{Duration, Instant}, +}; + +use horizon_client::text::Text; +use horizon_shader_api::{Pack, check}; + +use super::Game; + +const LOOK_EVERY: Duration = Duration::from_millis(500); +const RED: u32 = 0xFF5555; + +#[derive(Default)] +pub(super) struct NativeShaders { + /// The pack's files when it was last read (`fingerprint`). + stamp: Option, + looked: Option, +} + +impl Game<'_> { + /// Builds the pack at `path` when its files changed since it was last read. + pub(super) fn tick_native_shader_pack(&mut self, path: &Path) { + let now = Instant::now(); + let state = &mut self.native_shaders; + if state.looked.is_some_and(|t| now - t < LOOK_EVERY) { + return; + } + state.looked = Some(now); + let stamp = fingerprint(path); + if stamp == state.stamp { + return; + } + let reload = state.stamp.is_some(); + state.stamp = stamp; + let Some(renderer) = &mut self.renderer else { + return; + }; + let result = Pack::read(path).map_err(|e| vec![e]).and_then(|pack| { + let report = check(&pack) + .map_err(|p| p.iter().map(ToString::to_string).collect::>())?; + let constants = pack + .manifest + .options + .iter() + .map(|o| (o.id.clone(), o.kind.default_constant())) + .collect(); + let labels = renderer + .set_native_shader_pack(Some((report, constants))) + .map_err(|e| vec![e])?; + Ok((pack.manifest, labels)) + }); + let name = path.file_name().unwrap_or_default().to_string_lossy(); + match result { + Ok((m, labels)) => { + log::info!( + "shader pack {} {}: {} in {} ms", + m.id, + m.version, + labels.join(", "), + now.elapsed().as_millis() + ); + if reload { + self.system_message(Text::literal(format!("Shader pack {} reloaded", m.name))); + } + } + Err(problems) => { + log::warn!("shader pack {name} refused: {}", problems.join("; ")); + self.system_message(Text::colored(format!("Shader pack {name} refused:"), RED)); + for p in problems { + self.system_message(Text::colored(p, RED)); + } + } + } + } +} + +/// A hash of the pack's file names, sizes and modification times (`None` when unreadable). +fn fingerprint(path: &Path) -> Option { + fn walk(path: &Path, hasher: &mut std::hash::DefaultHasher) -> Option<()> { + let meta = std::fs::metadata(path).ok()?; + path.hash(hasher); + if meta.is_dir() { + let mut entries: Vec<_> = std::fs::read_dir(path) + .ok()? + .flatten() + .map(|e| e.path()) + .collect(); + entries.sort(); + for entry in entries { + walk(&entry, hasher)?; + } + } else { + meta.len().hash(hasher); + meta.modified().ok()?.hash(hasher); + } + Some(()) + } + let mut hasher = std::hash::DefaultHasher::new(); + walk(path, &mut hasher)?; + Some(hasher.finish()) +} diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index f534e8391..ed8ad61b7 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -1,5 +1,6 @@ //! Shader packs, for development until the Shader Packs page exists: `HORIZON_SHADER_PACK=` -//! runs `shaderpacks/` (a folder or a zip beside `options.txt`) over the world. The +//! runs `shaderpacks/` (a folder or a zip beside `options.txt`) over the world; Horizon's +//! own packs go to `game/native_shaders.rs`. The //! programs of the current dimension's folder are loaded when the dimension changes (spec 1.2). use horizon_client::camera::CameraFluid; @@ -41,15 +42,18 @@ impl Game<'_> { Dim::Nether => -1, Dim::End => 1, }; - if let Some(renderer) = &mut self.renderer + let path = std::env::current_dir() + .unwrap_or_default() + .join("shaderpacks") + .join(&name); + if horizon_shader_api::package::is_pack(&path) { + // One of Horizon's own packs (game/native_shaders.rs). + self.tick_native_shader_pack(&path); + } else if let Some(renderer) = &mut self.renderer && renderer.shader_pack_dimension() != Some(dimension) { let name = name.to_string_lossy(); let started = std::time::Instant::now(); - let path = std::env::current_dir() - .unwrap_or_default() - .join("shaderpacks") - .join(&*name); match Pack::open(&path) { Ok(pack) => { let macros = Macros::standard(); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 419f83c4a..5db82b19a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -67,6 +67,7 @@ mod end_sky; mod flat; pub mod lightning; mod lod; +mod native_post; mod occlusion; mod pack_atlas; pub mod pack_draw; @@ -499,6 +500,8 @@ pub struct Renderer { world_post: world_post::Post, /// The shader pack's post-processing, and the dimension (legacy id) it was loaded for. pack_post: Option<(i32, Option)>, + /// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s. + native_post: Option, /// The entity vertices Horizon draws itself while a shader pack draws the others. pack_entity_rest: Vec, /// Set 1 of the cloud pipeline, for a shader pack's `gbuffers_clouds`. @@ -2409,6 +2412,7 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, pack_post: None, + native_post: None, pack_entity_rest: Vec::new(), cloud_bindings, pack_weather: None, @@ -2916,8 +2920,38 @@ impl Renderer { (programs, p.notes.clone()) }); self.pack_post = Some((dimension, post)); + if self.pack_post.as_ref().is_some_and(|p| p.1.is_some()) { + self.native_post = None; + } report } + /// Runs the post passes of one of Horizon's own shader packs over the world from now on + /// (`None`: no pack), with its options' values; replaces a `shaders/` pack. Returns the + /// passes' labels; on an error the passes that ran keep running. + pub fn set_native_shader_pack( + &mut self, + pack: Option<(horizon_shader_api::Report, Vec<(String, f64)>)>, + ) -> std::result::Result, String> { + let stages = pack.map(|(report, constants)| { + let post: Vec<_> = report + .stages + .into_iter() + .filter(|s| s.kind == horizon_shader_api::StageKind::Post) + .collect(); + (post, constants) + }); + let Some((post, constants)) = stages.filter(|(post, _)| !post.is_empty()) else { + self.native_post = None; + return Ok(Vec::new()); + }; + let format = self.config.format.remove_srgb_suffix(); + let post = native_post::NativePost::new(&self.device, post, &constants, format)?; + let labels = post.labels().into_iter().map(str::to_owned).collect(); + self.pack_post = None; + self.pack_atlas = None; + self.native_post = Some(post); + Ok(labels) + } /// What a shader pack's gbuffers programs read from Horizon's geometry: the sky's, and /// terrain's in the pack's block atlas (made here when missing; none when it does not fit). pub fn pack_inputs(&mut self) -> horizon_shaders::GameInputs { @@ -3980,6 +4014,9 @@ impl Renderer { } // The world's targets: the screen, or the scaled target of `post`. let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some()); + // One of Horizon's own packs reads the same world target. + let native_post = !frame.title && self.native_post.is_some(); + let pack_reads_world = pack_post || native_post; // The pack's program reads the vertices this frame's draws bind. let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat; // The shadow camera's lists, drawn by the pack's shadow programs. @@ -4023,7 +4060,7 @@ impl Renderer { let scaled = self.world_post.prepare( &self.device, [self.config.width, self.config.height], - pack_post, + pack_reads_world, ); let (world_view, world_depth) = match &scaled { Some((color, depth)) => (color, depth), @@ -4062,7 +4099,7 @@ impl Renderer { depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), // Phase 2 of occlusion culling draws over it; a shader pack reads it. - store: if cull.is_some() || pack_post { + store: if cull.is_some() || pack_reads_world { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard @@ -4128,7 +4165,7 @@ impl Renderer { &mut encoder, world_view, world_depth, - pack_post, + pack_reads_world, ); pass.set_bind_group(0, &self.group, &[]); pass.set_pipeline(&flat.solid); @@ -4157,7 +4194,7 @@ impl Renderer { &mut encoder, world_view, world_depth, - pack_post, + pack_reads_world, ); pass.set_bind_group(0, &self.group, &[]); pass.set_pipeline(&self.solid); @@ -4427,6 +4464,20 @@ impl Renderer { &mut terrain, ); self.pack_post = Some((dimension, Some(post))); + } else if let Some((color, depth)) = &scaled + && native_post + && let Some(post) = &mut self.native_post + { + let size = self.world_post.size().unwrap_or([1, 1]); + post.run( + &self.device, + &self.queue, + &mut encoder, + (color, depth), + &view_target, + frame, + size, + ); } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } diff --git a/crates/horizon-client/src/gfx/native_post.rs b/crates/horizon-client/src/gfx/native_post.rs new file mode 100644 index 000000000..c4af862d7 --- /dev/null +++ b/crates/horizon-client/src/gfx/native_post.rs @@ -0,0 +1,509 @@ +//! The post stage of Horizon's own shader packs (docs/shaders.md): each `[[post]]` pass is a +//! full-screen pipeline built from its checked naga module (`horizon_shader_api::check`), with +//! the pack's options as pipeline constants. A pass reads bind group 3: the frame, the world's +//! colour and depth, the previous pass's output and two samplers. Passes before the last write +//! half-float targets of the world's size, so values over 1 carry to the next; the last draws +//! onto the screen. + +use glam::{Mat4, Vec3}; +use horizon_shader_api::{Frame as FrameInputs, check::CheckedStage, stages::GROUP}; + +use super::Frame; + +const INTERMEDIATE: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; + +/// The world's colour and depth views a set of bind groups was made for. +type WorldViews = (wgpu::TextureView, wgpu::TextureView); + +pub struct NativePost { + passes: Vec<(String, wgpu::RenderPipeline)>, + layout: wgpu::BindGroupLayout, + frame: wgpu::Buffer, + linear: wgpu::Sampler, + nearest: wgpu::Sampler, + /// Two targets of the world's size, written in turn (none with a single pass). + targets: Option<([u32; 2], [wgpu::TextureView; 2])>, + /// One bind group per pass, for these world views. + groups: Option<(WorldViews, Vec)>, + start: std::time::Instant, + frames: u32, +} + +fn texture_entry(binding: u32, sample_type: wgpu::TextureSampleType) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + } +} + +fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + } +} + +impl NativePost { + /// Pipelines for `stages` (the pack's post passes, in order) with the option values + /// `constants`, drawing onto a screen of `format`. Errors name the pass wgpu refused. + pub fn new( + device: &wgpu::Device, + stages: Vec, + constants: &[(String, f64)], + format: wgpu::TextureFormat, + ) -> Result { + let float = wgpu::TextureSampleType::Float { filterable: true }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Native shader pack post"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(size_of::() as u64), + }, + count: None, + }, + texture_entry(1, float), + texture_entry(2, wgpu::TextureSampleType::Depth), + texture_entry(3, float), + sampler_entry(4), + sampler_entry(5), + ], + }); + let mut groups: [Option<&wgpu::BindGroupLayout>; GROUP as usize + 1] = Default::default(); + groups[GROUP as usize] = Some(&layout); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Native shader pack post"), + bind_group_layouts: &groups, + ..Default::default() + }); + let count = stages.len(); + let mut passes = Vec::with_capacity(count); + for (i, stage) in stages.into_iter().enumerate() { + let present: Vec<(&str, f64)> = constants + .iter() + .filter(|(id, _)| { + stage + .module + .overrides + .iter() + .any(|(_, o)| o.name.as_ref() == Some(id)) + }) + .map(|(id, v)| (id.as_str(), *v)) + .collect(); + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&stage.label), + source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(stage.module)), + }); + let options = wgpu::PipelineCompilationOptions { + constants: &present, + ..Default::default() + }; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&stage.label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("horizon_vs_post"), + compilation_options: options.clone(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("horizon_fs_post"), + compilation_options: options, + targets: &[Some(wgpu::ColorTargetState { + format: if i + 1 == count { format } else { INTERMEDIATE }, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + if let Some(e) = pollster::block_on(scope.pop()) { + return Err(format!("{}: {e}", stage.file)); + } + passes.push((stage.label, pipeline)); + } + let frame = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Native shader pack frame"), + size: size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let sampler = |label, filter| { + device.create_sampler(&wgpu::SamplerDescriptor { + label: Some(label), + mag_filter: filter, + min_filter: filter, + ..Default::default() + }) + }; + Ok(Self { + passes, + layout, + frame, + linear: sampler("Native shader pack linear", wgpu::FilterMode::Linear), + nearest: sampler("Native shader pack nearest", wgpu::FilterMode::Nearest), + targets: None, + groups: None, + start: std::time::Instant::now(), + frames: 0, + }) + } + + /// The passes' labels, in order. + pub fn labels(&self) -> Vec<&str> { + self.passes.iter().map(|(l, _)| l.as_str()).collect() + } + + fn prepare( + &mut self, + device: &wgpu::Device, + world: (&wgpu::TextureView, &wgpu::TextureView), + size: [u32; 2], + ) { + if self.passes.len() > 1 && self.targets.as_ref().is_none_or(|t| t.0 != size) { + let target = |label| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: INTERMEDIATE, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + self.targets = Some(( + size, + [ + target("Native shader pack A"), + target("Native shader pack B"), + ], + )); + self.groups = None; + } + if self + .groups + .as_ref() + .is_some_and(|((color, depth), _)| color == world.0 && depth == world.1) + { + return; + } + let groups = (0..self.passes.len()) + .map(|i| { + // Pass i reads what pass i - 1 wrote: target (i - 1) % 2, the world for the first. + let previous = match (&self.targets, i) { + (Some((_, t)), 1..) => &t[(i - 1) % 2], + _ => world.0, + }; + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Native shader pack post"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: self.frame.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(world.0), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(world.1), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(previous), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&self.linear), + }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::Sampler(&self.nearest), + }, + ], + }) + }) + .collect(); + self.groups = Some(((world.0.clone(), world.1.clone()), groups)); + } + + /// Runs the passes over the world target `world` (colour, depth) of `size`, the last onto + /// `screen`. + pub fn run( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + world: (&wgpu::TextureView, &wgpu::TextureView), + screen: &wgpu::TextureView, + frame: &Frame, + size: [u32; 2], + ) { + let seconds = self.start.elapsed().as_secs_f32() % 3600.0; + let inputs = frame_inputs(frame, size, seconds, self.frames); + self.frames = self.frames.wrapping_add(1); + self.draw(device, queue, encoder, world, screen, &inputs, size); + } + + fn draw( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + world: (&wgpu::TextureView, &wgpu::TextureView), + screen: &wgpu::TextureView, + inputs: &FrameInputs, + size: [u32; 2], + ) { + self.prepare(device, world, size); + queue.write_buffer(&self.frame, 0, bytemuck::bytes_of(inputs)); + let Some((_, groups)) = &self.groups else { + return; + }; + for (i, ((label, pipeline), group)) in self.passes.iter().zip(groups).enumerate() { + let view = match &self.targets { + Some((_, t)) if i + 1 < self.passes.len() => &t[i % 2], + _ => screen, + }; + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(GROUP, group, &[]); + pass.draw(0..3, 0..1); + } + } +} + +/// The frame as packs read it (docs/api/shaders-reference.md), from the renderer's `Frame`. +pub fn frame_inputs(frame: &Frame, size: [u32; 2], seconds: f32, index: u32) -> FrameInputs { + let aspect = size[0] as f32 / size[1].max(1) as f32; + let view = crate::camera::view_matrix(frame.yaw, frame.pitch); + let projection = + super::world_projection(frame.fov_degrees, aspect, frame.depth_far) * frame.bob; + // A celestial body's direction at `angle` degrees (SkyRenderer: Y -90°, then X by the + // angle, of straight up): overhead at 0, rising in the east (+x). + let body = |angle: f32| { + let a = angle.to_radians(); + Vec3::new(-a.sin(), a.cos(), 0.0) + }; + let (fog_color, fog_start, fog_end) = match &frame.fog { + Some(f) => ( + [f.color[0], f.color[1], f.color[2]], + f.environmental_start.min(f.render_distance_start), + f.environmental_end.min(f.render_distance_end), + ), + None => (frame.sky.fog_color, frame.distance * 0.9, frame.distance), + }; + let pack = &frame.pack; + let level = |l: i32| l as f32 / 15.0; + let m = |m: Mat4| m.to_cols_array_2d(); + FrameInputs { + view: m(view), + projection: m(projection), + view_inverse: m(view.inverse()), + projection_inverse: m(projection.inverse()), + camera_position: frame.camera.as_vec3().to_array(), + time: seconds, + sun_direction: body(frame.sky.sun_angle).to_array(), + day_time: pack.day_time.rem_euclid(24000) as f32 / 24000.0, + moon_direction: body(frame.sky.moon_angle).to_array(), + game_time: frame.shader_game_time, + sky_color: frame.sky.sky_color, + rain: pack.rain, + fog_color, + thunder: pack.thunder, + resolution: [size[0] as f32, size[1] as f32], + eye_light: [level(pack.eye_light[0]), level(pack.eye_light[1])], + fog_start, + fog_end, + render_distance: frame.distance, + far: frame.depth_far, + night_vision: frame.night_vision, + blindness: pack.blindness, + darkness: frame.darkness.1.clamp(0.0, 1.0), + brightness: pack.brightness, + eye_in: pack.eye_in as u32, + dimension: if frame.end_sky { + 1 + } else if frame.nether_lighting { + -1 + } else { + 0 + }, + frame_index: index, + hide_gui: u32::from(pack.hide_gui), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_shader_api::{MANIFEST, Pack, check}; + + fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?; + pollster::block_on(adapter.request_device(&Default::default())).ok() + } + + fn texture( + device: &wgpu::Device, + format: wgpu::TextureFormat, + usage: wgpu::TextureUsages, + ) -> wgpu::Texture { + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 4, + height: 4, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + } + + /// Two passes: the first doubles the world's colour (over 1, so the half-float target + /// must keep it) times an option, the second halves it and writes the depth as alpha. + #[test] + fn passes_chain_through_half_float_targets_with_options_and_depth() { + let Some((device, queue)) = device() else { + return; + }; + let manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\ + [[post]]\nfile = \"a.wgsl\"\n[[post]]\nfile = \"b.wgsl\"\n\ + [[options]]\nid = \"gain\"\nname = \"Gain\"\ntype = \"float\"\ndefault = 0.0\nmin = 0.0\nmax = 2.0\n"; + let a = "override gain: f32;\nfn post(input: PostInput) -> vec4 { return vec4(input.color.rgb * 2.0 * gain, 1.0); }\n"; + let b = "fn post(input: PostInput) -> vec4 { return vec4(input.color.rgb * 0.5, input.depth); }\n"; + let files = [(MANIFEST, manifest), ("a.wgsl", a), ("b.wgsl", b)] + .map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec())) + .into(); + let report = check(&Pack::from_files(files).unwrap()).unwrap(); + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut post = + NativePost::new(&device, report.stages, &[("gain".into(), 1.0)], format).unwrap(); + assert_eq!(post.labels(), ["a.wgsl", "b.wgsl"]); + + let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; + let color = texture(&device, format, usage).create_view(&Default::default()); + let depth = texture(&device, wgpu::TextureFormat::Depth32Float, usage) + .create_view(&Default::default()); + let screen = texture( + &device, + format, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + ); + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &color, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.8, + g: 0.4, + b: 0.2, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.5), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + let view = screen.create_view(&Default::default()); + post.draw( + &device, + &queue, + &mut encoder, + (&color, &depth), + &view, + &FrameInputs::default(), + [4, 4], + ); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT * 4), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + encoder.copy_texture_to_buffer( + screen.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), + rows_per_image: Some(4), + }, + }, + screen.size(), + ); + queue.submit([encoder.finish()]); + buffer + .slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let pixel = buffer.slice(..).get_mapped_range().unwrap()[..4].to_vec(); + let near = |got: u8, want: u8| got.abs_diff(want) <= 1; + assert!( + near(pixel[0], 204) && near(pixel[1], 102) && near(pixel[2], 51) && near(pixel[3], 128), + "{pixel:?}" + ); + } +} diff --git a/crates/horizon-shader-api/packs/golden_hour/post/glow.wgsl b/crates/horizon-shader-api/packs/golden_hour/post/glow.wgsl index 4d523c9ef..e27b98244 100644 --- a/crates/horizon-shader-api/packs/golden_hour/post/glow.wgsl +++ b/crates/horizon-shader-api/packs/golden_hour/post/glow.wgsl @@ -1,9 +1,12 @@ -// A soft halo around bright pixels: twelve taps on two rings, scaled with -// the picture's height so it looks the same at any resolution. +// A soft halo around the brightest pixels (the sun, lava, torches at night): twelve taps on two +// rings, scaled with the picture's height so it looks the same at any resolution. The daytime +// sky is bright too, so it glows only a quarter as much. override glow: f32 = 0.35; -fn bright(c: vec3) -> vec3 { - return c * smoothstep(0.7, 1.0, luminance(c)); +fn bright(uv: vec2) -> vec3 { + let c = textureSampleLevel(previous, linear_sampler, uv, 0.0).rgb; + let sky = select(1.0, 0.25, depth_at(uv) == 0.0); + return c * smoothstep(0.8, 1.0, luminance(c)) * sky; } fn post(input: PostInput) -> vec4 { @@ -16,7 +19,7 @@ fn post(input: PostInput) -> vec4 { let angle = f32(i) * 0.5235988; let radius = select(3.0, 7.0, (i & 1) == 1); let offset = vec2(cos(angle), sin(angle)) * radius * step; - sum += bright(textureSampleLevel(previous, linear_sampler, input.uv + offset, 0.0).rgb); + sum += bright(input.uv + offset); } - return vec4(input.color.rgb + sum * (glow / 6.0), input.color.a); + return vec4(input.color.rgb + sum * (glow / 8.0), input.color.a); } diff --git a/crates/horizon-shader-api/src/inputs.rs b/crates/horizon-shader-api/src/inputs.rs index 5bc82fd82..f25fe2847 100644 --- a/crates/horizon-shader-api/src/inputs.rs +++ b/crates/horizon-shader-api/src/inputs.rs @@ -158,7 +158,7 @@ pub const POST_INPUT: Struct = Struct { doc: "One pixel of the picture, for `fn post(input: PostInput) -> vec4`.", fields: fields! { uv: "vec2" = "Where the pixel is, 0..1 from the top left.", - pixel: "vec2" = "The pixel's centre, in pixels from the top left.", + pixel: "vec2" = "The pixel's centre, in pixels from the top left of what the pass draws (the world's size; the window's for the last pass).", color: "vec4" = "The previous pass's colour here (the world's picture for the first pass).", depth: "f32" = "The world's depth here, reversed: 0 is the sky.", }, diff --git a/crates/horizon-shader-api/src/package.rs b/crates/horizon-shader-api/src/package.rs index e2e644a04..b148d95c5 100644 --- a/crates/horizon-shader-api/src/package.rs +++ b/crates/horizon-shader-api/src/package.rs @@ -46,6 +46,13 @@ pub fn plain_path(path: &str) -> bool { }) } +/// Whether `path` is a pack of this format: a folder holding +/// `horizon-shaders.toml`, or a `.hshader` file. +pub fn is_pack(path: &Path) -> bool { + path.join(MANIFEST).is_file() + || (path.is_file() && path.extension().is_some_and(|e| e == EXTENSION)) +} + impl Pack { /// Reads `path`: a `.hshader` file, or a folder (its hidden files and /// folders, such as `.git`, are skipped). diff --git a/docs/api/shaders-reference.md b/docs/api/shaders-reference.md index f9682a1a4..400d5029b 100644 --- a/docs/api/shaders-reference.md +++ b/docs/api/shaders-reference.md @@ -77,7 +77,7 @@ One pixel of the picture, for `fn post(input: PostInput) -> vec4`. | Field | Type | Meaning | | --- | --- | --- | | `uv` | `vec2` | Where the pixel is, 0..1 from the top left. | -| `pixel` | `vec2` | The pixel's centre, in pixels from the top left. | +| `pixel` | `vec2` | The pixel's centre, in pixels from the top left of what the pass draws (the world's size; the window's for the last pass). | | `color` | `vec4` | The previous pass's colour here (the world's picture for the first pass). | | `depth` | `f32` | The world's depth here, reversed: 0 is the sky. | diff --git a/docs/api/shaders.md b/docs/api/shaders.md index 8e9e6919c..675c5e3fc 100644 --- a/docs/api/shaders.md +++ b/docs/api/shaders.md @@ -96,6 +96,7 @@ stages with options and hot reload, then the overlay, lighting, sky and shadow s ## Changelog +- 2026-10-26: the post stage in the game (`HORIZON_SHADER_PACK`, hot reload with the last good pack kept). - 2026-10-25: `horizon-shader` (`new`, `check`, `pack`), three templates, the example pack and the guide. - 2026-10-25: the check (naga validation, signatures, options, budgets, SPIR-V/Metal/HLSL translation). - 2026-10-25: the stages of API 0.1 (sky, material, post), their inputs and the generated reference. diff --git a/docs/shaders.md b/docs/shaders.md index 99a08fa9a..ef8521cfe 100644 --- a/docs/shaders.md +++ b/docs/shaders.md @@ -13,7 +13,8 @@ Horizon's own format. | Authoring tool | `horizon-shader` (same crate) | `new`, `check`, `pack` | | Templates | `crates/horizon-shader-api/templates/` | post, sky, material | | Example pack | `crates/horizon-shader-api/packs/golden_hour` | a warm sky and two post passes | -| In the game, the launcher, the registry | | not yet: the renderer hooks come next | +| In the game: the post stage | `HORIZON_SHADER_PACK=` (for development, until the Shader Packs page) | post passes, hot reload | +| In the game: sky and material; the launcher and the registry | | not yet | ## Quick start @@ -29,9 +30,9 @@ horizon-shader pack my_pack # check, then write my_pack- ``` golden_hour 1.0.0 (shader API 0.1): ok sky Warm horizon 99 expressions, 0 texture reads - post Glow 185 expressions, 3 texture reads + post Glow 192 expressions, 3 texture reads post Colour grade 201 expressions, 2 texture reads - sha256 fd92a294... + sha256 b5e0d98c... ``` or every problem, at its file, line and column: @@ -43,6 +44,15 @@ my_pack 0.1.0 (shader API 0.1): FAILED `--json` prints the same for tools (`ok`, `id`, `version`, `api`, `sha256`, `stages`, `problems`). +## Trying a pack in the game + +Until the Shader Packs page lists them, put the pack folder (or its `.hshader`) in `shaderpacks/` beside `options.txt` +and start the game with `HORIZON_SHADER_PACK=`. The game checks the pack first, and refuses +one that fails, with its problems in the chat. While it runs, the game looks at the pack twice a second: save a file +and the pack is checked and rebuilt in place ("Shader pack ... reloaded"); if the new version fails, the chat says +where and the last good version keeps drawing. The post passes run today; the sky and material stages are checked +but not drawn yet. + ## A pack A folder (or the same files zipped as a `.hshader`) with `horizon-shaders.toml` and WGSL files: From 2c5dac354eb0f5b7c3812803e5d4798f54973c34 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 06:11:01 +0100 Subject: [PATCH 4/5] parity-main: name a merge only when HEAD fails again and the base passes The bisect ended on the newest merge when the failed harnesses pass everywhere now (a flake, or a runner that was missing the sounds), and on the oldest when they fail everywhere (the runner), and commented on that pull request either way. It now reruns them at HEAD and at the base first and names nobody unless HEAD fails and the base passes. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_main.py | 29 +++++++++++++++++++++++++++++ tools/parity_main.py | 17 ++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/tests/test_parity_main.py b/tests/test_parity_main.py index 7a72ecae5..aa58375a6 100644 --- a/tests/test_parity_main.py +++ b/tests/test_parity_main.py @@ -33,6 +33,35 @@ class ParityMainTests(unittest.TestCase): self.assertEqual(parity_main.base(runs=[]), parent, "no green run yet: the last merge") self.assertEqual(parity_main.base(runs=[head]), head) + def test_bisect_names_a_merge_only_when_head_fails_and_the_base_passes(self): + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(parity_main, "ROOT", Path(tmp)): + git = lambda *arguments: parity_main.git(*arguments).stdout.strip() + git("init", "-q") + for n in range(4): + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", + "-m", f"Merge pull request #{n} from x/y") + commits = git("rev-list", "--reverse", "HEAD").split() + last_run = Path(tmp) / ".local/parity-runner/last-run.json" + last_run.parent.mkdir(parents=True) + last_run.write_text('{"failed": ["music"]}') + real_run = parity_main.subprocess.run + for broken_from, blamed in ((None, None), (0, None), (2, "2")): + comments = [] + # git runs for real in the scratch repo; a `gh pr comment` is only recorded, never sent. + fake_run = lambda command, **kwargs: (comments.append(command) if command[0] == "gh" + else real_run(command, **kwargs)) + with mock.patch.object(parity_main, "LAST_RUN", last_run), \ + mock.patch.object(parity_main, "run_harnesses", lambda names, timeout: broken_from is not None + and commits.index(git("rev-parse", "HEAD")) >= broken_from), \ + mock.patch.object(parity_main.subprocess, "run", fake_run), \ + mock.patch("builtins.print") as printed: + parity_main.bisect(commits[0], 60, comment=True) + if blamed: + self.assertEqual([command[3] for command in comments], [blamed]) + else: + self.assertEqual(comments, [], printed.call_args_list[-1]) + self.assertEqual(git("rev-parse", "HEAD"), commits[-1], "HEAD checked out again") + def test_a_harness_a_commit_does_not_have_cannot_fail_there(self): with mock.patch.object(parity_main.subprocess, "run") as run: self.assertFalse(parity_main.run_harnesses(["not_a_harness_yet"], 60)) diff --git a/tools/parity_main.py b/tools/parity_main.py index ff319aed0..76fa49070 100644 --- a/tools/parity_main.py +++ b/tools/parity_main.py @@ -8,7 +8,7 @@ so a run tests every merge since the last green one (`tools/parity.py --changed `), however many landed while the previous run went on. `bisect` reads the harnesses that failed (.local/parity-runner/last-run.json), checks out the first-parent merges between BASE and HEAD by halves and runs only those harnesses, then names the first merge they -fail on (written to $GITHUB_STEP_SUMMARY and, with --comment, on its pull request). HEAD is checked out again at the end. +fail on, once they fail again at HEAD and pass at BASE (written to $GITHUB_STEP_SUMMARY and, with --comment, on its pull request). HEAD is checked out again at the end. """ import argparse @@ -90,7 +90,22 @@ def bisect(since, timeout, comment): git("checkout", "-q", "--detach", commit) return run_harnesses(failed, timeout) + def blame_nobody(why): + line = f"parity-main: {', '.join(failed)} {why}: no merge is named." + print(line) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary: + summary.write(f"### {line}\n") + return 0 + + # A merge is named only when the harnesses fail again at HEAD and pass at the base: otherwise the search would + # end on the newest merge (a flake, or a runner missing files, passes everywhere now) or the oldest one (the + # runner fails at every commit) and blame it for nothing. try: + if not fails(head): + return blame_nobody(f"pass when run again at {head[:9]}: a flake or the runner") + if fails(since): + return blame_nobody(f"fail at the base {since[:9]} too: the runner or a flake") culprit = first_bad(commits, fails) if len(commits) > 1 else commits[0] finally: git("checkout", "-q", "--detach", head) From 130f1dc6a5a83917bd89477414b528e640cefc6f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:13:21 +0100 Subject: [PATCH 5/5] horizon-ctl options-set keeps the mod list options-set rebuilt Settings from options.txt and carried over Horizon's graphics, controller and extras files, but not the mod list: every mod read as off afterwards, and the next save wrote an empty horizon-mods.txt. Settings::with_option now does the rebuild and keeps all four. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/options.rs | 9 +------ crates/horizon-client/src/settings.rs | 30 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 0e385e25c..3a61b0e7a 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -57,14 +57,7 @@ impl Game<'_> { .map(str::trim) .filter(|v| !v.is_empty()) .ok_or("options-set KEY VALUE: missing the value")?; - let mut file = self.settings.to_file(); - file.set_text(key, value)?; - let mut settings = horizon_client::settings::Settings::from_file(file); - // Horizon's own files are not in options.txt. - std::mem::swap(&mut settings.horizon, &mut self.settings.horizon); - std::mem::swap(&mut settings.controller, &mut self.settings.controller); - std::mem::swap(&mut settings.extras, &mut self.settings.extras); - self.settings = settings; + self.settings = self.settings.with_option(key, value)?; // As the options screen applies a change. self.handle_option_events(vec![Event::Changed])?; match *key { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 2a53e1702..ebffc897f 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -538,6 +538,21 @@ impl Settings { } f } + /// These settings with one `options.txt` value changed (`horizon-ctl + /// options-set`, as `OptionsFile::set_text` reads it). Horizon's own + /// files (graphics, controller, extras, the mod list) aren't in + /// `options.txt`, so they stay as they are. + pub fn with_option(&self, key: &str, value: &str) -> Result { + let mut file = self.to_file(); + file.set_text(key, value)?; + Ok(Self { + horizon: self.horizon.clone(), + controller: self.controller.clone(), + extras: self.extras.clone(), + mods: self.mods.clone(), + ..Self::from_file(file) + }) + } /// The `options.txt` text (Options.save). pub fn serialize(&self) -> String { self.to_file().serialize() @@ -592,6 +607,21 @@ impl Settings { mod tests { use super::*; #[test] + fn an_option_set_keeps_horizon_files() { + let mut s = Settings::parse("fov:70\n"); + s.mods.enabled.insert("zoom".into()); + s.extras.minimap = true; + s.horizon.fog = !s.horizon.fog; + s.controller.vibration = !s.controller.vibration; + let set = s.with_option("fov", "90").unwrap(); + assert_eq!(set.fov, 90.0); + assert_eq!(set.mods, s.mods); + assert_eq!(set.extras, s.extras); + assert_eq!(set.horizon, s.horizon); + assert_eq!(set.controller, s.controller); + assert!(s.with_option("fov", "200").is_err()); + } + #[test] fn gui_scale_survives_temporary_small_framebuffer() { for requested in [0, 1, 2, 6] { let settings = Settings::parse(&format!("guiScale:{requested}\n"));