Merge pull request #1944 from ludovic111/feat/mod-input
🤖 Agent: Mod API capability input (experimental): claimed items' use and the mod's keys. Main merged in beside command and render (9 capabilities). Verified: horizon-mods tests (sandbox, API reference), clippy with and without mods, horizon-client tests (1121 lib), earlier pr_ready and in-game runs in both modes.
This commit is contained in:
@@ -210,6 +210,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
}),
|
||||
// The GUI of a 1280 x 720 window at scale 3.
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
});
|
||||
mods.tick(t);
|
||||
for _ in 0..FRAMES_PER_TICK {
|
||||
|
||||
@@ -97,6 +97,7 @@ mod maps;
|
||||
mod minecarts;
|
||||
mod mob_blocks;
|
||||
mod mob_gear;
|
||||
mod mod_input;
|
||||
mod mod_render;
|
||||
mod mods;
|
||||
mod mount_menu;
|
||||
@@ -10628,6 +10629,10 @@ impl Game<'_> {
|
||||
}
|
||||
/// A mouse button while playing (window or control socket).
|
||||
fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
|
||||
// A mod's claimed item takes the use button (capability `input`).
|
||||
if self.mod_use(button, pressed) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.sleeping.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -11546,6 +11551,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
return Ok(());
|
||||
};
|
||||
self.extras_key(key, event.state == ElementState::Pressed, event.repeat);
|
||||
self.mod_key(key, event.state == ElementState::Pressed, event.repeat);
|
||||
// key.smoothCamera toggles the cinematic camera.
|
||||
if self.screen == Screen::Playing
|
||||
&& event.state == ElementState::Pressed
|
||||
|
||||
@@ -294,6 +294,11 @@ impl Game<'_> {
|
||||
if action == "tap" {
|
||||
self.extras_key(physical, false, false);
|
||||
}
|
||||
// So do mods' keys (capability `input`).
|
||||
self.mod_key(physical, action != "up", action == "repeat");
|
||||
if action == "tap" {
|
||||
self.mod_key(physical, false, false);
|
||||
}
|
||||
// Text screens consume raw presses; releases follow key binds.
|
||||
let typing = matches!(self.screen, Screen::Chat | Screen::Options);
|
||||
let key = if typing && arg(2)? != "up" {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Capability `input` (docs/mods.md): the use button on items a mod claims,
|
||||
//! and the mod's own keys. With no mod claiming items or keys, each hook
|
||||
//! here returns after one check.
|
||||
use super::Game;
|
||||
use winit::{event::MouseButton, keyboard::KeyCode};
|
||||
#[cfg(feature = "mods")]
|
||||
use {super::Screen, horizon_mods::HeldItem};
|
||||
|
||||
/// A claimed item's use while the button is down.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) struct ModUse {
|
||||
item: HeldItem,
|
||||
/// `Game::ticks` when it started.
|
||||
since: u64,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mods"))]
|
||||
impl Game<'_> {
|
||||
pub(super) fn mod_use(&mut self, _button: MouseButton, _pressed: bool) -> bool {
|
||||
false
|
||||
}
|
||||
pub(super) fn mod_key(&mut self, _key: KeyCode, _pressed: bool, _repeat: bool) {}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
impl Game<'_> {
|
||||
/// The main hand's stack as `input` shows it; none when it is empty.
|
||||
pub(super) fn mod_held(&self) -> Option<HeldItem> {
|
||||
let stack = self.inventory.get(self.selected)?.as_ref()?;
|
||||
Some(HeldItem {
|
||||
id: stack.item.to_string(),
|
||||
count: stack.count,
|
||||
slot: self.selected as u32,
|
||||
})
|
||||
}
|
||||
/// The use button while playing: true when a mod claimed the held item,
|
||||
/// so the game does nothing else with it (no placing, eating, swing).
|
||||
pub(super) fn mod_use(&mut self, button: MouseButton, pressed: bool) -> bool {
|
||||
if button != MouseButton::Right || !self.mods.mods.claims_any() {
|
||||
return false;
|
||||
}
|
||||
if !pressed {
|
||||
return self.stop_mod_use();
|
||||
}
|
||||
let Some(item) = self.mod_held().filter(|h| self.mods.mods.claims(&h.id)) else {
|
||||
return false;
|
||||
};
|
||||
self.mods.mods.use_start(&item);
|
||||
self.mods.using = Some(ModUse {
|
||||
item,
|
||||
since: self.ticks,
|
||||
});
|
||||
true
|
||||
}
|
||||
/// Ends a claimed use: the button came up, the player switched slots,
|
||||
/// or a screen opened. False when none was going.
|
||||
pub(super) fn stop_mod_use(&mut self) -> bool {
|
||||
let Some(u) = self.mods.using.take() else {
|
||||
return false;
|
||||
};
|
||||
let ticks = self.ticks.saturating_sub(u.since).min(u64::from(u32::MAX)) as u32;
|
||||
self.mods.mods.use_stop(&u.item, ticks);
|
||||
true
|
||||
}
|
||||
/// Once a tick: a claimed use stops when its item leaves the hand or a
|
||||
/// screen opens, as vanilla's `releaseUsingItem`.
|
||||
pub(super) fn tick_mod_use(&mut self) {
|
||||
let Some(u) = &self.mods.using else {
|
||||
return;
|
||||
};
|
||||
let still = self
|
||||
.mod_held()
|
||||
.is_some_and(|h| h.id == u.item.id && h.slot == u.item.slot);
|
||||
if !still || self.screen != Screen::Playing {
|
||||
self.stop_mod_use();
|
||||
}
|
||||
}
|
||||
/// A key went down or up: a mod's registered key while playing (no
|
||||
/// screen) is its `key-down` / `key-up`. Vanilla's mapping on the same
|
||||
/// key still runs.
|
||||
pub(super) fn mod_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) {
|
||||
if repeat || !self.mods.mods.has_keys() {
|
||||
return;
|
||||
}
|
||||
if pressed && (self.screen != Screen::Playing || self.title.is_some()) {
|
||||
return;
|
||||
}
|
||||
if let Some(name) = horizon_client::keybinds::key_name(key) {
|
||||
self.mods.mods.key(name, pressed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,9 @@ use {
|
||||
pub(super) struct ModsState {
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) mods: Mods,
|
||||
/// Capability `input`: a claimed item's use while the button is down.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) using: Option<super::mod_input::ModUse>,
|
||||
/// Capability `render`'s camera shakes.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) shake: super::mod_render::Shake,
|
||||
@@ -345,6 +348,7 @@ impl Game<'_> {
|
||||
player,
|
||||
clock,
|
||||
gui_size: self.gui_size(),
|
||||
held: self.mod_held(),
|
||||
}
|
||||
}
|
||||
/// A game tick.
|
||||
@@ -357,6 +361,7 @@ impl Game<'_> {
|
||||
if !self.mods.mods.is_running() {
|
||||
return;
|
||||
}
|
||||
self.tick_mod_use();
|
||||
let snapshot = self.mod_snapshot();
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
self.mods.mods.tick(self.ticks);
|
||||
|
||||
@@ -38,7 +38,7 @@ wit_bindgen::generate!({
|
||||
|
||||
pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
|
||||
pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest;
|
||||
pub use horizon::mods::{chat, command, game, hud, log, render, storage, ui};
|
||||
pub use horizon::mods::{chat, command, game, hud, input, log, render, storage, ui};
|
||||
|
||||
/// The game's calls into a mod. Only the hooks [`Registration`] asks for
|
||||
/// are called; the others may stay as their defaults.
|
||||
|
||||
@@ -171,6 +171,48 @@ interface ui-events {
|
||||
settings-opened: func();
|
||||
}
|
||||
|
||||
/// Capability `input` (experimental: the manifest needs
|
||||
/// `experimental = ["input"]`): the use button on items the mod claims, and
|
||||
/// the mod's own keys. Events wait for `poll`, at most 256.
|
||||
interface input {
|
||||
/// The main hand's stack.
|
||||
record held-item {
|
||||
/// `minecraft:spyglass`, `<mod>:<path>`.
|
||||
id: string,
|
||||
count: u32,
|
||||
/// The hotbar slot, 0 to 8.
|
||||
slot: u32,
|
||||
}
|
||||
record item-use {
|
||||
item: held-item,
|
||||
/// Game ticks the button was held (0 on `use-start`).
|
||||
ticks: u32,
|
||||
}
|
||||
variant event {
|
||||
/// The use button went down with a claimed item in the main hand.
|
||||
/// The game does nothing else with the click: no placing, no eating,
|
||||
/// no swing.
|
||||
use-start(item-use),
|
||||
/// It came up again, or the item left the hand, or a screen opened.
|
||||
use-stop(item-use),
|
||||
/// A key `register-key` named went down or up while playing (no
|
||||
/// screen open). The game's own mapping on that key still runs.
|
||||
key-down(string),
|
||||
key-up(string),
|
||||
}
|
||||
/// The items whose use the mod handles instead of the game, by id (at
|
||||
/// most 64). Replaces the previous list.
|
||||
claim-items: func(ids: list<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>;
|
||||
/// The main hand's stack, as of this tick; none when it is empty.
|
||||
held: func() -> option<held-item>;
|
||||
/// The events since the last call, oldest first.
|
||||
poll: func() -> list<event>;
|
||||
}
|
||||
|
||||
/// Capability `render` (experimental: the manifest needs
|
||||
/// `experimental = ["render"]`): shapes the game draws for the mod with its
|
||||
/// own renderer, kept until the mod replaces them (no call per frame). A mod
|
||||
@@ -289,6 +331,7 @@ world horizon-ui-mod {
|
||||
include horizon-mod;
|
||||
import ui;
|
||||
import render;
|
||||
import input;
|
||||
export ui-events;
|
||||
}
|
||||
|
||||
@@ -301,4 +344,5 @@ world ui-host {
|
||||
/// The game's side of capability `render` (imports only).
|
||||
world render-host {
|
||||
import render;
|
||||
import input;
|
||||
}
|
||||
|
||||
@@ -89,9 +89,12 @@ pub enum Capability {
|
||||
/// Shapes on the HUD and the camera's shake, drawn by the game's own
|
||||
/// renderer (interface `render`).
|
||||
Render,
|
||||
/// The use button on items the mod claims, and its own keys
|
||||
/// (interface `input`).
|
||||
Input,
|
||||
}
|
||||
impl Capability {
|
||||
pub const ALL: [Capability; 8] = [
|
||||
pub const ALL: [Capability; 9] = [
|
||||
Capability::GameRead,
|
||||
Capability::Chat,
|
||||
Capability::Hud,
|
||||
@@ -100,6 +103,7 @@ impl Capability {
|
||||
Capability::Registries,
|
||||
Capability::Ui,
|
||||
Capability::Render,
|
||||
Capability::Input,
|
||||
];
|
||||
/// The WIT interface it grants, in `horizon:mods`.
|
||||
pub fn interface(self) -> &'static str {
|
||||
@@ -112,12 +116,16 @@ impl Capability {
|
||||
Capability::Registries => "registries",
|
||||
Capability::Ui => "ui",
|
||||
Capability::Render => "render",
|
||||
Capability::Input => "input",
|
||||
}
|
||||
}
|
||||
/// May change in any release: a mod uses it only with
|
||||
/// `experimental = ["<name>"]` in its manifest.
|
||||
pub fn is_experimental(self) -> bool {
|
||||
matches!(self, Capability::Ui | Capability::Render)
|
||||
matches!(
|
||||
self,
|
||||
Capability::Ui | Capability::Render | Capability::Input
|
||||
)
|
||||
}
|
||||
/// What the player reads before turning the mod on: "May <this>".
|
||||
pub fn describe(self) -> &'static str {
|
||||
@@ -130,6 +138,7 @@ impl Capability {
|
||||
Capability::Registries => "add blocks and items to your worlds",
|
||||
Capability::Ui => "show its own screens and a settings page",
|
||||
Capability::Render => "draw on your screen and shake the camera",
|
||||
Capability::Input => "take over the use button on its own items, and add keys",
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
@@ -163,6 +172,7 @@ impl fmt::Display for Capability {
|
||||
Capability::Registries => "registries",
|
||||
Capability::Ui => "ui",
|
||||
Capability::Render => "render",
|
||||
Capability::Input => "input",
|
||||
};
|
||||
f.write_str(name)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ mod render_bindings {
|
||||
world: "render-host",
|
||||
});
|
||||
}
|
||||
use render_bindings::horizon::mods::input;
|
||||
/// Capability `input`'s records (WIT `interface input`).
|
||||
pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, ItemUse};
|
||||
/// What capability `render` asks the game to draw (WIT `interface render`).
|
||||
pub use render_bindings::horizon::mods::render::{
|
||||
FillShape, ItemShape, Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape,
|
||||
@@ -85,6 +88,8 @@ pub struct Snapshot {
|
||||
pub clock: Option<Clock>,
|
||||
/// The screen in GUI pixels (capability `render`'s `gui-size`).
|
||||
pub gui_size: (f32, f32),
|
||||
/// The main hand's stack (capability `input`'s `held`).
|
||||
pub held: Option<HeldItem>,
|
||||
}
|
||||
|
||||
/// What mods asked the game to show since the last [`Mods::drain`].
|
||||
@@ -175,6 +180,7 @@ struct State {
|
||||
ui: UiState,
|
||||
/// Capability `render`'s HUD shapes, drawn until replaced.
|
||||
shapes: Vec<Shape>,
|
||||
input: InputState,
|
||||
/// Capability `storage`'s folder; made on first `set`.
|
||||
data_dir: PathBuf,
|
||||
/// Bytes `storage::set` may still write before this hook call ends
|
||||
@@ -315,6 +321,7 @@ impl Mods {
|
||||
panel: None,
|
||||
ui: UiState::default(),
|
||||
shapes: Vec::new(),
|
||||
input: InputState::default(),
|
||||
data_dir,
|
||||
storage_budget: STORAGE_WRITE_BUDGET,
|
||||
limits: StoreLimitsBuilder::new()
|
||||
@@ -506,6 +513,78 @@ impl Mods {
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref())
|
||||
}
|
||||
/// Some running mod claimed items (capability `input`).
|
||||
pub fn claims_any(&self) -> bool {
|
||||
self.inputs().any(|i| !i.claimed.is_empty())
|
||||
}
|
||||
/// Some running mod claimed the item `id`.
|
||||
pub fn claims(&self, id: &str) -> bool {
|
||||
self.inputs().any(|i| i.claimed.iter().any(|c| c == id))
|
||||
}
|
||||
/// Some running mod registered a key.
|
||||
pub fn has_keys(&self) -> bool {
|
||||
self.inputs().any(|i| !i.keys.is_empty())
|
||||
}
|
||||
/// The mods' keys: (mod name, key name, label, key), for Controls.
|
||||
pub fn mod_keys(&self) -> impl Iterator<Item = (&str, &ModKey)> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref())
|
||||
.flat_map(|r| {
|
||||
let d = r.store.data();
|
||||
d.input.keys.iter().map(move |k| (d.name.as_str(), k))
|
||||
})
|
||||
}
|
||||
/// The use button went down with `item`: `use-start` to each mod that
|
||||
/// claimed it.
|
||||
pub fn use_start(&mut self, item: &HeldItem) {
|
||||
let event = InputEvent::UseStart(ItemUse {
|
||||
item: item.clone(),
|
||||
ticks: 0,
|
||||
});
|
||||
self.push_input(|i| i.claimed.contains(&item.id), &event);
|
||||
}
|
||||
/// The claimed use ended after `ticks`.
|
||||
pub fn use_stop(&mut self, item: &HeldItem, ticks: u32) {
|
||||
let event = InputEvent::UseStop(ItemUse {
|
||||
item: item.clone(),
|
||||
ticks,
|
||||
});
|
||||
self.push_input(|i| i.claimed.contains(&item.id), &event);
|
||||
}
|
||||
/// The key `key` (`key.keyboard.r`) went down or up: each mod with a
|
||||
/// key on it hears its own name for it.
|
||||
pub fn key(&mut self, key: &str, down: bool) {
|
||||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||||
let input = &mut run.store.data_mut().input;
|
||||
let names: Vec<String> = input
|
||||
.keys
|
||||
.iter()
|
||||
.filter(|k| k.key == key)
|
||||
.map(|k| k.name.clone())
|
||||
.collect();
|
||||
for name in names {
|
||||
input.push(if down {
|
||||
InputEvent::KeyDown(name)
|
||||
} else {
|
||||
InputEvent::KeyUp(name)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
fn inputs(&self) -> impl Iterator<Item = &InputState> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|e| Some(&e.run.as_ref()?.store.data().input))
|
||||
}
|
||||
fn push_input(&mut self, to: impl Fn(&InputState) -> bool, event: &InputEvent) {
|
||||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||||
let input = &mut run.store.data_mut().input;
|
||||
if to(input) {
|
||||
input.push(event.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The running mods' HUD shapes (capability `render`), each mod's in
|
||||
/// its own order, mods in load order.
|
||||
pub fn hud_shapes(&self) -> impl Iterator<Item = &Shape> {
|
||||
@@ -701,6 +780,80 @@ impl chat::Host for State {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A key a mod registered (capability `input`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ModKey {
|
||||
/// The mod's own name for it, echoed in `key-down`.
|
||||
pub name: String,
|
||||
/// What it does, for Controls.
|
||||
pub label: String,
|
||||
/// `key.keyboard.r`.
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
/// What capability `input` holds for one mod.
|
||||
#[derive(Default)]
|
||||
struct InputState {
|
||||
claimed: Vec<String>,
|
||||
keys: Vec<ModKey>,
|
||||
events: std::collections::VecDeque<InputEvent>,
|
||||
}
|
||||
/// Events kept for `poll`, items claimed and keys, per mod.
|
||||
const INPUT_EVENTS: usize = 256;
|
||||
const CLAIMS: usize = 64;
|
||||
const KEYS: usize = 16;
|
||||
|
||||
/// `key.keyboard.<name>` or `key.mouse.<name>`, as options.txt writes keys;
|
||||
/// the game knows which names exist and ignores a key it has none for.
|
||||
fn key_ok(key: &str) -> bool {
|
||||
let rest = key
|
||||
.strip_prefix("key.keyboard.")
|
||||
.or_else(|| key.strip_prefix("key.mouse."));
|
||||
rest.is_some_and(|r| {
|
||||
(1..=32).contains(&r.len())
|
||||
&& r.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.')
|
||||
})
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
fn push(&mut self, event: InputEvent) {
|
||||
if self.events.len() == INPUT_EVENTS {
|
||||
self.events.pop_front();
|
||||
}
|
||||
self.events.push_back(event);
|
||||
}
|
||||
}
|
||||
|
||||
impl input::Host for State {
|
||||
fn claim_items(&mut self, ids: Vec<String>) {
|
||||
self.input.claimed = ids.into_iter().take(CLAIMS).map(clip).collect();
|
||||
}
|
||||
fn register_key(&mut self, name: String, label: String, key: String) -> Result<(), String> {
|
||||
if !key_ok(&key) {
|
||||
return Err(format!(
|
||||
"{key:?} is not a key as options.txt writes them (key.keyboard.r)"
|
||||
));
|
||||
}
|
||||
let (name, label) = (clip(name), clip(label));
|
||||
if let Some(k) = self.input.keys.iter_mut().find(|k| k.name == name) {
|
||||
(k.label, k.key) = (label, key);
|
||||
return Ok(());
|
||||
}
|
||||
if self.input.keys.len() == KEYS {
|
||||
return Err(format!("a mod may register {KEYS} keys"));
|
||||
}
|
||||
self.input.keys.push(ModKey { name, label, key });
|
||||
Ok(())
|
||||
}
|
||||
fn held(&mut self) -> Option<HeldItem> {
|
||||
self.snapshot.held.clone()
|
||||
}
|
||||
fn poll(&mut self) -> Vec<InputEvent> {
|
||||
self.input.events.drain(..).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// HUD shapes one mod may keep (capability `render`).
|
||||
const SHAPES: usize = 1024;
|
||||
/// The longest jolt `render.shake` makes, in seconds.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! examples and a guest
|
||||
//! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`.
|
||||
use horizon_mods::{
|
||||
Clock, Corner, Mods, Output, Package, Player, Shape, Snapshot, Status, manifest::componentize,
|
||||
Clock, Corner, HeldItem, Mods, Output, Package, Player, Shape, Snapshot, Status,
|
||||
manifest::componentize,
|
||||
};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
@@ -23,8 +24,8 @@ id = "test_ui_guest"
|
||||
name = "Test UI Guest"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
capabilities = ["chat", "ui", "render"]
|
||||
experimental = ["ui", "render"]
|
||||
capabilities = ["chat", "ui", "render", "input"]
|
||||
experimental = ["ui", "render", "input"]
|
||||
"#;
|
||||
|
||||
/// Builds the mods once and writes their `.hmod` files; returns the folder.
|
||||
@@ -97,6 +98,7 @@ fn player() -> Snapshot {
|
||||
day_time: 24000 + 6000,
|
||||
}),
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,6 +461,7 @@ fn render_shapes_and_shakes() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
mods.set_snapshot(Snapshot {
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
..Snapshot::default()
|
||||
});
|
||||
assert_eq!(mods.hud_shapes().count(), 0);
|
||||
@@ -485,6 +488,64 @@ fn render_shapes_and_shakes() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_claims_keys_and_events() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
let chat = |mods: &mut Mods| -> Vec<String> {
|
||||
mods.drain()
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Output::Chat { text, .. } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert!(!mods.claims_any() && !mods.has_keys());
|
||||
assert!(mods.command("input_claim"));
|
||||
let said = chat(&mut mods);
|
||||
assert!(
|
||||
said[0].starts_with("claimed; \"R\" is not a key"),
|
||||
"{said:?}"
|
||||
);
|
||||
assert!(mods.claims("minecraft:stick") && !mods.claims("minecraft:stone"));
|
||||
let keys: Vec<_> = mods
|
||||
.mod_keys()
|
||||
.map(|(m, k)| (m.to_owned(), k.key.clone()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[("Test UI Guest".to_owned(), "key.keyboard.r".to_owned())]
|
||||
);
|
||||
// The game feeds the events; the mod reads them in order with `poll`.
|
||||
let stick = HeldItem {
|
||||
id: "minecraft:stick".into(),
|
||||
count: 3,
|
||||
slot: 2,
|
||||
};
|
||||
mods.use_start(&stick);
|
||||
mods.key("key.keyboard.r", true);
|
||||
mods.key("key.keyboard.t", true);
|
||||
mods.key("key.keyboard.r", false);
|
||||
mods.use_stop(&stick, 12);
|
||||
assert!(mods.command("input_poll"));
|
||||
assert_eq!(
|
||||
chat(&mut mods),
|
||||
[
|
||||
"use-start minecraft:stick 0",
|
||||
"key-down wheel",
|
||||
"key-up wheel",
|
||||
"use-stop minecraft:stick 12"
|
||||
]
|
||||
);
|
||||
// `held` reads the snapshot.
|
||||
mods.set_snapshot(Snapshot {
|
||||
held: Some(stick),
|
||||
..Snapshot::default()
|
||||
});
|
||||
assert!(mods.command("input_held"));
|
||||
assert_eq!(chat(&mut mods), ["holding minecraft:stick x3 in 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_mods_load_without_an_engine() {
|
||||
let manifest = r#"
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! A mod for the runtime's `ui` tests: `/ui_screen` opens a screen with one
|
||||
//! of each widget, `/ui_settings` sets a settings page, `/ui_close` closes
|
||||
//! the screen; the `ui-events` calls answer in chat so the host sees them.
|
||||
//! `/render_hud`, `/render_clear` and `/render_shake` test `render`.
|
||||
//! `/render_hud`, `/render_clear` and `/render_shake` test `render`;
|
||||
//! `/input_claim`, `/input_poll` and `/input_held` test `input`.
|
||||
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},
|
||||
};
|
||||
@@ -87,6 +89,9 @@ impl Mod for Guest {
|
||||
"render_hud",
|
||||
"render_clear",
|
||||
"render_shake",
|
||||
"input_claim",
|
||||
"input_poll",
|
||||
"input_held",
|
||||
]
|
||||
.into_iter()
|
||||
.fold(Registration::new(), Registration::command);
|
||||
@@ -102,6 +107,29 @@ impl Mod for Guest {
|
||||
"ui_close" => ui::close_screen(),
|
||||
"render_hud" => render::set_hud(&shapes()),
|
||||
"render_clear" => render::set_hud(&[]),
|
||||
"input_claim" => {
|
||||
input::claim_items(&["minecraft:stick".into()]);
|
||||
input::register_key("wheel", "Open the wheel", "key.keyboard.r")?;
|
||||
// Not a key: refused.
|
||||
let bad = input::register_key("bad", "Bad", "R").unwrap_err();
|
||||
chat::show(&format!("claimed; {bad}"));
|
||||
}
|
||||
"input_poll" => {
|
||||
for event in input::poll() {
|
||||
chat::show(&match event {
|
||||
Event::UseStart(u) => format!("use-start {} {}", u.item.id, u.ticks),
|
||||
Event::UseStop(u) => format!("use-stop {} {}", u.item.id, u.ticks),
|
||||
Event::KeyDown(k) => format!("key-down {k}"),
|
||||
Event::KeyUp(k) => format!("key-up {k}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
"input_held" => {
|
||||
let held = input::held().map_or("nothing".into(), |h| {
|
||||
format!("{} x{} in {}", h.id, h.count, h.slot)
|
||||
});
|
||||
chat::show(&format!("holding {held}"));
|
||||
}
|
||||
// Clamped to (1, 10); the two after it shake nothing.
|
||||
"render_shake" => {
|
||||
render::shake(2.0, 99.0);
|
||||
|
||||
@@ -15,6 +15,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
|
||||
| `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds |
|
||||
| `ui` | [`ui`](#ui) | show its own screens and a settings page |
|
||||
| `render` | [`render`](#render) | draw on your screen and shake the camera |
|
||||
| `input` | [`input`](#input) | take over the use button on its own items, and add keys |
|
||||
|
||||
## World `horizon-mod`
|
||||
|
||||
@@ -25,7 +26,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
|
||||
|
||||
A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets.
|
||||
|
||||
- Imports (what the game offers): `ui`, `render`, `log`, `game`, `chat`, `hud`, `storage`, `command`
|
||||
- Imports (what the game offers): `ui`, `render`, `input`, `log`, `game`, `chat`, `hud`, `storage`, `command`
|
||||
- Exports (what the mod provides): `ui-events`, `events`
|
||||
|
||||
## World `ui-host`
|
||||
@@ -39,7 +40,7 @@ The game's side of `horizon-ui-mod` beyond `horizon-mod`.
|
||||
|
||||
The game's side of capability `render` (imports only).
|
||||
|
||||
- Imports (what the game offers): `render`
|
||||
- Imports (what the game offers): `render`, `input`
|
||||
- Exports (what the mod provides):
|
||||
|
||||
## `log`
|
||||
@@ -224,6 +225,45 @@ What the game calls on a mod that shows widgets (capability `ui`): what the play
|
||||
| `closed` | `func()` | The player left the mod's screen (Esc or Done); not for a screen the mod closed itself or one that went away with the mod. |
|
||||
| `settings-opened` | `func()` | The player opened the mod's settings page in Options > Mods: call `ui::set-settings` now to fill it with fresh widgets. |
|
||||
|
||||
## `input`
|
||||
|
||||
Access: capability `input`.
|
||||
|
||||
Capability `input` (experimental: the manifest needs `experimental = ["input"]`): the use button on items the mod claims, and the mod's own keys. Events wait for `poll`, at most 256.
|
||||
|
||||
### record `held-item`
|
||||
|
||||
The main hand's stack.
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `id` | `string` | `minecraft:spyglass`, `<mod>:<path>`. |
|
||||
| `count` | `u32` | |
|
||||
| `slot` | `u32` | The hotbar slot, 0 to 8. |
|
||||
|
||||
### record `item-use`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `item` | `held-item` | |
|
||||
| `ticks` | `u32` | Game ticks the button was held (0 on `use-start`). |
|
||||
|
||||
### variant `event`
|
||||
|
||||
| Case | Payload | |
|
||||
| --- | --- | --- |
|
||||
| `use-start` | `item-use` | The use button went down with a claimed item in the main hand. The game does nothing else with the click: no placing, no eating, no swing. |
|
||||
| `use-stop` | `item-use` | It came up again, or the item left the hand, or a screen opened. |
|
||||
| `key-down` | `string` | A key `register-key` named went down or up while playing (no screen open). The game's own mapping on that key still runs. |
|
||||
| `key-up` | `string` | |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `claim-items` | `func(ids: list<string>)` | 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. |
|
||||
| `held` | `func() -> option<held-item>` | The main hand's stack, as of this tick; none when it is empty. |
|
||||
| `poll` | `func() -> list<event>` | The events since the last call, oldest first. |
|
||||
|
||||
## `render`
|
||||
|
||||
Access: capability `render`.
|
||||
|
||||
@@ -99,6 +99,8 @@ What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
## Changelog
|
||||
|
||||
- Experimental `input` (`experimental = ["input"]`): `claim-items`, `register-key`, `held`, `poll` (use-start,
|
||||
use-stop, key-down, key-up).
|
||||
- Experimental `render` (`experimental = ["render"]`): HUD shapes (fill, quad, sprite, item, text), `gui-size`, camera
|
||||
`shake`, drawn by the game's own renderer.
|
||||
- API 0.2 (content): data-driven blocks and items, tags, `horizon:add_to`, terrain adaptation.
|
||||
|
||||
@@ -89,6 +89,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel
|
||||
| Mod API: `log`, `game`, `chat`, `hud`, `storage`, `command`, `events` | preview | 0.1.0 |
|
||||
| Mod API: `ui`, `ui-events` (a mod's screens and settings page) | experimental | manifest `experimental = ["ui"]` |
|
||||
| Mod API: `render` (HUD shapes, camera shake; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` |
|
||||
| Mod API: `input` (claimed items' use, the mod's keys) | experimental | manifest `experimental = ["input"]` |
|
||||
| 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 | |
|
||||
|
||||
+2
-1
@@ -89,6 +89,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
|
||||
| `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, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` |
|
||||
| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects. The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` |
|
||||
| `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); `held()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` |
|
||||
|
||||
| Hook (export) | When |
|
||||
|---|---|
|
||||
@@ -291,7 +292,7 @@ experimental = [] # experimental capabilities it uses, e.g. ["ui"]
|
||||
```
|
||||
|
||||
Unknown keys are refused, so a typo is an error, not a silently ignored
|
||||
permission. An experimental capability (today `ui` and `render`) may change in any release
|
||||
permission. An experimental capability (today `ui`, `render` and `input`) 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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user