Merge pull request #1963 from ludovic111/feat/mod-api-extras
🤖 Agent: Mod API calls the official HUD mods use: render corner panels, text width and frame stats; input mappings and clicks per second; a ui button widget. Main merged in (after #1914's widget refactor). Verified: horizon-mods tests, clippy with and without mods, horizon-client tests (1121 lib), Keystrokes' settings page in game.
This commit is contained in:
@@ -210,7 +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,
|
||||
..Snapshot::default()
|
||||
});
|
||||
mods.tick(t);
|
||||
for _ in 0..FRAMES_PER_TICK {
|
||||
|
||||
@@ -70,7 +70,8 @@ impl Game<'_> {
|
||||
_ => return,
|
||||
};
|
||||
self.extras.mouse[i] = pressed;
|
||||
if pressed && self.settings.extras.keystrokes {
|
||||
// Mods read the clicks too (`input.clicks-per-second`).
|
||||
if pressed && (self.settings.extras.keystrokes || self.mods.running()) {
|
||||
let now = self.extras_now();
|
||||
self.extras.cps[i].click(now);
|
||||
}
|
||||
@@ -87,13 +88,28 @@ impl Game<'_> {
|
||||
self.extras.mouse = [false; 2];
|
||||
}
|
||||
self.update_minimap();
|
||||
if self.settings.extras.fps {
|
||||
// Mods read the counter too (`render.frame-stats`).
|
||||
if self.settings.extras.fps || self.mods.running() {
|
||||
let now = self.extras_now();
|
||||
self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0);
|
||||
} else {
|
||||
self.extras.fps.clear();
|
||||
}
|
||||
}
|
||||
/// The frame counter for mods: fps, min, 1% low.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) fn frame_reading(&self) -> (u32, u32, u32) {
|
||||
let r = self.extras.fps.reading();
|
||||
(r.fps, r.min, r.low)
|
||||
}
|
||||
/// Attack and use clicks in the last second, and whether each is held.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) fn mouse_reading(&mut self) -> ((u32, u32), [bool; 2]) {
|
||||
let now = self.extras_now();
|
||||
let [l, r] = &mut self.extras.cps;
|
||||
let cps = (l.per_second(now) as u32, r.per_second(now) as u32);
|
||||
(cps, self.extras.mouse)
|
||||
}
|
||||
/// Auto-reconnect: a connection to `address` as `name` starts.
|
||||
pub(super) fn extras_connecting(&mut self, address: &str, name: &str) {
|
||||
self.extras.reconnect.connecting(address, name);
|
||||
|
||||
@@ -86,23 +86,29 @@ impl Game<'_> {
|
||||
impl Game<'_> {
|
||||
/// The running mods' HUD shapes, in order, over the HUD.
|
||||
pub(super) fn draw_mod_shapes(&self, batch: &mut HudBatch) {
|
||||
let atlas = &self.gui.atlas;
|
||||
for shape in self.mods.mods.hud_shapes() {
|
||||
self.draw_shapes(batch, std::slice::from_ref(shape), (0.0, 0.0));
|
||||
}
|
||||
}
|
||||
/// Shapes with their GUI coordinates moved by `(ox, oy)`.
|
||||
pub(super) fn draw_shapes(&self, batch: &mut HudBatch, shapes: &[Shape], (ox, oy): (f32, f32)) {
|
||||
let atlas = &self.gui.atlas;
|
||||
for shape in shapes {
|
||||
match shape {
|
||||
Shape::Fill(f) => {
|
||||
let r = f.rect;
|
||||
batch.fill(atlas, r.x, r.y, r.w, r.h, argb(f.color));
|
||||
batch.fill(atlas, ox + r.x, oy + r.y, r.w, r.h, argb(f.color));
|
||||
}
|
||||
Shape::Quad(q) => {
|
||||
let (a, b, c, d) = q.corners;
|
||||
let corners = [[a.x, a.y], [b.x, b.y], [c.x, c.y], [d.x, d.y]];
|
||||
let corners = [a, b, c, d].map(|p| [ox + p.x, oy + p.y]);
|
||||
batch.fill_quad(atlas, corners, argb(q.color));
|
||||
}
|
||||
Shape::Sprite(s) => {
|
||||
let r = s.rect;
|
||||
let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite);
|
||||
let name = format!("gui/sprites/{name}");
|
||||
batch.sprite_scaled(atlas, &name, r.x, r.y, r.w, r.h, argb(s.color));
|
||||
batch.sprite_scaled(atlas, &name, ox + r.x, oy + r.y, r.w, r.h, argb(s.color));
|
||||
}
|
||||
Shape::Item(i) => {
|
||||
if self.res.items().get(&i.item).is_none() {
|
||||
@@ -110,21 +116,23 @@ impl Game<'_> {
|
||||
}
|
||||
let start = batch.vertices.len();
|
||||
let stack = ItemStack::new(i.item.as_str(), 1);
|
||||
self.draw_item_model(batch, &stack, i.at.x, i.at.y);
|
||||
batch.scale_since(start, i.at.x, i.at.y, i.scale, i.scale);
|
||||
let (x, y) = (ox + i.at.x, oy + i.at.y);
|
||||
self.draw_item_model(batch, &stack, x, y);
|
||||
batch.scale_since(start, x, y, i.scale, i.scale);
|
||||
}
|
||||
Shape::Text(t) => {
|
||||
let text = Text::literal(t.text.clone());
|
||||
let x = if t.centered {
|
||||
t.at.x - (HudBatch::text_width(atlas, &t.text) / 2.0).floor()
|
||||
let centre = if t.centered {
|
||||
(HudBatch::text_width(atlas, &t.text) / 2.0).floor()
|
||||
} else {
|
||||
t.at.x
|
||||
0.0
|
||||
};
|
||||
let x = ox + t.at.x - centre;
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&text,
|
||||
x,
|
||||
t.at.y,
|
||||
oy + t.at.y,
|
||||
argb(t.color | 0xFF00_0000),
|
||||
t.shadow,
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@ use {
|
||||
extras::Corner,
|
||||
extras_hud,
|
||||
items::ItemStack,
|
||||
keybinds,
|
||||
mod_list::Installed,
|
||||
options_ui::Page,
|
||||
text::{self, Text},
|
||||
@@ -59,8 +60,32 @@ pub(super) struct ModsState {
|
||||
/// A `ui` mod's screen or settings page while it is up.
|
||||
#[cfg(feature = "mods")]
|
||||
screen: Option<ModScreen>,
|
||||
/// The HUD font's advances for `render.text-width`, made once.
|
||||
#[cfg(feature = "mods")]
|
||||
font_widths: std::sync::Arc<[f32]>,
|
||||
}
|
||||
|
||||
/// The mappings `input.mapping` answers for, with the default key their
|
||||
/// binding is translated to (none: a mouse button, attack or use).
|
||||
#[cfg(feature = "mods")]
|
||||
const MAPPINGS: [(&str, Option<winit::keyboard::KeyCode>); 9] = {
|
||||
use winit::keyboard::KeyCode as K;
|
||||
[
|
||||
("key.forward", Some(K::KeyW)),
|
||||
("key.left", Some(K::KeyA)),
|
||||
("key.back", Some(K::KeyS)),
|
||||
("key.right", Some(K::KeyD)),
|
||||
("key.jump", Some(K::Space)),
|
||||
("key.sneak", Some(K::ShiftLeft)),
|
||||
("key.sprint", Some(K::ControlLeft)),
|
||||
("key.attack", None),
|
||||
("key.use", None),
|
||||
]
|
||||
};
|
||||
/// Characters `render.text-width` knows exactly: U+0000 to U+024F.
|
||||
#[cfg(feature = "mods")]
|
||||
const FONT_CHARS: u32 = 0x250;
|
||||
|
||||
/// A `ui` mod's own screen, or its settings page from Options > Mods: the
|
||||
/// widgets the mod pushed, laid out and drawn with the menus' own widgets.
|
||||
#[cfg(feature = "mods")]
|
||||
@@ -99,10 +124,10 @@ impl ModsState {
|
||||
}
|
||||
false
|
||||
}
|
||||
/// Whether a mod draws a HUD panel.
|
||||
/// Whether a mod draws a HUD panel or a corner panel.
|
||||
pub(super) fn has_panels(&self) -> bool {
|
||||
#[cfg(feature = "mods")]
|
||||
if self.mods.panels().next().is_some() {
|
||||
if self.mods.panels().next().is_some() || self.mods.corner_panels().next().is_some() {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
@@ -328,8 +353,8 @@ impl Game<'_> {
|
||||
self.start_mods();
|
||||
}
|
||||
}
|
||||
/// What mods read this tick.
|
||||
fn mod_snapshot(&self) -> Snapshot {
|
||||
/// What mods read this tick (or frame, for mods with a `frame` hook).
|
||||
fn mod_snapshot(&mut self) -> Snapshot {
|
||||
let player = self.player.as_ref().map(|p| Player {
|
||||
x: p.position.x,
|
||||
y: p.position.y,
|
||||
@@ -344,11 +369,35 @@ impl Game<'_> {
|
||||
game_time: self.world.game_time.max(0) as u64,
|
||||
day_time: self.world.day_time.max(0) as u64,
|
||||
});
|
||||
let (cps, mouse) = self.mouse_reading();
|
||||
// The movement and click mappings, as the keystroke overlay reads them:
|
||||
// keys by the default key their binding is translated to.
|
||||
let mappings = MAPPINGS
|
||||
.iter()
|
||||
.map(|&(name, key)| {
|
||||
let label = keybinds::display_name(self.settings.keys.get(name)).plain();
|
||||
let down = match key {
|
||||
Some(k) => self.keys.contains(&k),
|
||||
None => mouse[usize::from(name == "key.use")],
|
||||
};
|
||||
(name, label, down)
|
||||
})
|
||||
.collect();
|
||||
if self.mods.font_widths.is_empty() {
|
||||
let atlas = &self.gui.atlas;
|
||||
self.mods.font_widths = (0..FONT_CHARS)
|
||||
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
|
||||
.collect();
|
||||
}
|
||||
Snapshot {
|
||||
player,
|
||||
clock,
|
||||
gui_size: self.gui_size(),
|
||||
held: self.mod_held(),
|
||||
frame: self.frame_reading(),
|
||||
mappings,
|
||||
cps,
|
||||
font_widths: self.mods.font_widths.clone(),
|
||||
}
|
||||
}
|
||||
/// A game tick.
|
||||
@@ -385,6 +434,10 @@ impl Game<'_> {
|
||||
if !self.mods.mods.is_running() {
|
||||
return;
|
||||
}
|
||||
if self.mods.mods.wants_frames() {
|
||||
let snapshot = self.mod_snapshot();
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
}
|
||||
self.mods.mods.frame(elapsed.as_secs_f32());
|
||||
self.show_mod_output();
|
||||
}
|
||||
@@ -486,6 +539,20 @@ impl Game<'_> {
|
||||
.collect();
|
||||
extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines);
|
||||
}
|
||||
// Capability `render`'s corner panels, placed the same way.
|
||||
for panel in self.mods.mods.corner_panels() {
|
||||
let corner = match panel.corner {
|
||||
horizon_mods::RenderCorner::TopLeft => Corner::TopLeft,
|
||||
horizon_mods::RenderCorner::TopRight => Corner::TopRight,
|
||||
horizon_mods::RenderCorner::BottomLeft => Corner::BottomLeft,
|
||||
horizon_mods::RenderCorner::BottomRight => Corner::BottomRight,
|
||||
};
|
||||
if self.debug && corner == Corner::TopLeft {
|
||||
continue;
|
||||
}
|
||||
let at = corners.place(corner, panel.width, panel.height);
|
||||
self.draw_shapes(batch, &panel.shapes, at);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `ui` screen's title and widgets as the mod last pushed them; None
|
||||
@@ -516,7 +583,7 @@ impl Game<'_> {
|
||||
for w in widgets {
|
||||
let wh = match w {
|
||||
UiWidget::Text(_) => 12.0,
|
||||
UiWidget::Item(_) => 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.
|
||||
@@ -611,6 +678,21 @@ impl Game<'_> {
|
||||
let mut list_i = 0usize;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
match w {
|
||||
UiWidget::Button(b) => {
|
||||
let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0);
|
||||
let label = Text::literal(b.label.clone());
|
||||
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
|
||||
@@ -733,6 +815,16 @@ impl Game<'_> {
|
||||
// The `ui_select` call needs `&mut`: find the pick first.
|
||||
let mut hit = None;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
// A button is `select(id, 0)`.
|
||||
if let UiWidget::Button(b) = w
|
||||
&& ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0)
|
||||
{
|
||||
self.audio.play_button_click();
|
||||
let owner = self.mods.screen.as_ref().map_or(0, |ms| ms.owner);
|
||||
self.mods.mods.ui_select(owner, b.id, 0);
|
||||
self.show_mod_output();
|
||||
return;
|
||||
}
|
||||
let UiWidget::List(l) = w else { continue };
|
||||
let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default();
|
||||
list_i += 1;
|
||||
|
||||
@@ -128,9 +128,20 @@ interface ui {
|
||||
selected: option<u32>,
|
||||
}
|
||||
/// A thing on a mod's screen or settings page.
|
||||
/// A button as the options pages have them (200 × 20): a click is
|
||||
/// `ui-events::select(id, 0)`. Mods cycle its label for a choice
|
||||
/// ("Corner: Top Left").
|
||||
record button-widget {
|
||||
/// The mod's own name for the widget.
|
||||
id: u32,
|
||||
/// Up to 256 characters.
|
||||
label: string,
|
||||
}
|
||||
variant widget {
|
||||
/// Text the player reads.
|
||||
text(text-widget),
|
||||
/// A button.
|
||||
button(button-widget),
|
||||
/// An item's icon and name.
|
||||
item(item-widget),
|
||||
/// Rows the player picks from.
|
||||
@@ -211,6 +222,20 @@ interface input {
|
||||
held: func() -> option<held-item>;
|
||||
/// The events since the last call, oldest first.
|
||||
poll: func() -> list<event>;
|
||||
/// A mapping as the player has bound it.
|
||||
record mapping-state {
|
||||
/// The bound key's name as Controls shows it: `W`, `Space`, `LMB`.
|
||||
label: string,
|
||||
/// Held down now (as of this frame for a mod with a `frame` hook,
|
||||
/// else this tick).
|
||||
down: bool,
|
||||
}
|
||||
/// A movement or click mapping as the player has bound it: `key.forward`,
|
||||
/// `key.left`, `key.back`, `key.right`, `key.jump`, `key.sneak`,
|
||||
/// `key.sprint`, `key.attack` or `key.use`. None for another name.
|
||||
mapping: func(name: string) -> option<mapping-state>;
|
||||
/// Clicks of the attack and use buttons in the last second.
|
||||
clicks-per-second: func() -> tuple<u32, u32>;
|
||||
}
|
||||
|
||||
/// Capability `render` (experimental: the manifest needs
|
||||
@@ -218,6 +243,13 @@ interface input {
|
||||
/// own renderer, kept until the mod replaces them (no call per frame). A mod
|
||||
/// never supplies shader code.
|
||||
interface render {
|
||||
/// A corner of the screen, as `hud`'s panels use them.
|
||||
enum corner {
|
||||
top-left,
|
||||
top-right,
|
||||
bottom-left,
|
||||
bottom-right,
|
||||
}
|
||||
/// A rectangle in GUI pixels: the top left corner and the size.
|
||||
record rect {
|
||||
x: f32,
|
||||
@@ -287,6 +319,26 @@ interface render {
|
||||
/// turns, the player doesn't, and the player's Distortion Effects option
|
||||
/// scales it (0 turns it off).
|
||||
shake: func(strength: f32, seconds: f32);
|
||||
/// Replaces the mod's corner panel: shapes in GUI pixels from the top
|
||||
/// left of a `width` × `height` box that the game places in `corner`,
|
||||
/// stacked with the game's overlays and the other mods' panels (under
|
||||
/// the status effects at the top right), as `hud`'s panels are.
|
||||
set-corner: func(corner: corner, width: f32, height: f32, shapes: list<shape>);
|
||||
/// Removes the mod's corner panel.
|
||||
clear-corner: func();
|
||||
/// The width of one line of text in GUI pixels, in the HUD's font: exact
|
||||
/// for Latin letters (U+0000 to U+024F), 6 per other character.
|
||||
text-width: func(text: string) -> f32;
|
||||
record frame-rate {
|
||||
/// Frames drawn in the last second.
|
||||
fps: u32,
|
||||
/// The slowest frame's rate, and the 1% low (the 99th percentile
|
||||
/// frame time's rate), over the last 5 seconds.
|
||||
min: u32,
|
||||
low: u32,
|
||||
}
|
||||
/// The game's frame counter, recomputed twice a second.
|
||||
frame-stats: func() -> frame-rate;
|
||||
}
|
||||
|
||||
/// What the game calls. Only the hooks `init` asks for are ever called.
|
||||
|
||||
@@ -138,7 +138,9 @@ 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",
|
||||
Capability::Input => {
|
||||
"see the keys you hold and your clicks, take over the use button on its own items, and add keys"
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
|
||||
@@ -37,7 +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::{
|
||||
ItemWidget, 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.
|
||||
@@ -52,8 +52,8 @@ use render_bindings::horizon::mods::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,
|
||||
TextShape,
|
||||
Corner as RenderCorner, FillShape, FrameRate, ItemShape, Point as RenderPoint, QuadShape,
|
||||
Rect as RenderRect, Shape, SpriteShape, TextShape,
|
||||
};
|
||||
use render_bindings::{RenderHost, horizon::mods::render};
|
||||
|
||||
@@ -90,6 +90,16 @@ pub struct Snapshot {
|
||||
pub gui_size: (f32, f32),
|
||||
/// The main hand's stack (capability `input`'s `held`).
|
||||
pub held: Option<HeldItem>,
|
||||
/// The game's frame counter: fps, min, 1% low (`render.frame-stats`).
|
||||
pub frame: (u32, u32, u32),
|
||||
/// The movement and click mappings `input.mapping` answers for:
|
||||
/// (mapping, the bound key's label, held).
|
||||
pub mappings: Vec<(&'static str, String, bool)>,
|
||||
/// Attack and use clicks in the last second.
|
||||
pub cps: (u32, u32),
|
||||
/// The HUD font's advance per character from U+0000
|
||||
/// (`render.text-width`); empty: 6 each.
|
||||
pub font_widths: Arc<[f32]>,
|
||||
}
|
||||
|
||||
/// What mods asked the game to show since the last [`Mods::drain`].
|
||||
@@ -180,6 +190,8 @@ struct State {
|
||||
ui: UiState,
|
||||
/// Capability `render`'s HUD shapes, drawn until replaced.
|
||||
shapes: Vec<Shape>,
|
||||
/// Capability `render`'s corner panel.
|
||||
corner: Option<CornerPanel>,
|
||||
input: InputState,
|
||||
/// Capability `storage`'s folder; made on first `set`.
|
||||
data_dir: PathBuf,
|
||||
@@ -321,6 +333,7 @@ impl Mods {
|
||||
panel: None,
|
||||
ui: UiState::default(),
|
||||
shapes: Vec::new(),
|
||||
corner: None,
|
||||
input: InputState::default(),
|
||||
data_dir,
|
||||
storage_budget: STORAGE_WRITE_BUDGET,
|
||||
@@ -513,6 +526,19 @@ impl Mods {
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref())
|
||||
}
|
||||
/// The running mods' corner panels (capability `render`), in load order.
|
||||
pub fn corner_panels(&self) -> impl Iterator<Item = &CornerPanel> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.store.data().corner.as_ref())
|
||||
}
|
||||
/// Some running mod has a `frame` hook: the game refreshes the snapshot
|
||||
/// every frame for it.
|
||||
pub fn wants_frames(&self) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.hooks.frame))
|
||||
}
|
||||
/// Some running mod claimed items (capability `input`).
|
||||
pub fn claims_any(&self) -> bool {
|
||||
self.inputs().any(|i| !i.claimed.is_empty())
|
||||
@@ -731,6 +757,10 @@ fn clip_widgets(widgets: Vec<UiWidget>) -> Vec<UiWidget> {
|
||||
t.text = clip(t.text);
|
||||
UiWidget::Text(t)
|
||||
}
|
||||
UiWidget::Button(mut b) => {
|
||||
b.label = clip(b.label);
|
||||
UiWidget::Button(b)
|
||||
}
|
||||
UiWidget::Item(mut i) => {
|
||||
i.item = clip(i.item);
|
||||
i.name = clip(i.name);
|
||||
@@ -852,6 +882,16 @@ impl input::Host for State {
|
||||
fn poll(&mut self) -> Vec<InputEvent> {
|
||||
self.input.events.drain(..).collect()
|
||||
}
|
||||
fn mapping(&mut self, name: String) -> Option<input::MappingState> {
|
||||
let (_, label, down) = self.snapshot.mappings.iter().find(|m| m.0 == name)?;
|
||||
Some(input::MappingState {
|
||||
label: label.clone(),
|
||||
down: *down,
|
||||
})
|
||||
}
|
||||
fn clicks_per_second(&mut self) -> (u32, u32) {
|
||||
self.snapshot.cps
|
||||
}
|
||||
}
|
||||
|
||||
/// HUD shapes one mod may keep (capability `render`).
|
||||
@@ -859,33 +899,76 @@ const SHAPES: usize = 1024;
|
||||
/// The longest jolt `render.shake` makes, in seconds.
|
||||
const SHAKE_SECONDS: f32 = 10.0;
|
||||
|
||||
/// A mod's corner panel: shapes in a `width` × `height` box the game
|
||||
/// places in `corner`, stacked with the other overlays.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CornerPanel {
|
||||
pub corner: RenderCorner,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub shapes: Vec<Shape>,
|
||||
}
|
||||
|
||||
fn clip_shapes(shapes: Vec<Shape>) -> Vec<Shape> {
|
||||
shapes
|
||||
.into_iter()
|
||||
.take(SHAPES)
|
||||
.map(|shape| match shape {
|
||||
Shape::Sprite(mut s) => {
|
||||
s.sprite = clip(s.sprite);
|
||||
Shape::Sprite(s)
|
||||
}
|
||||
Shape::Item(mut i) => {
|
||||
i.item = clip(i.item);
|
||||
i.scale = if i.scale.is_finite() {
|
||||
i.scale.clamp(0.0, 16.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Shape::Item(i)
|
||||
}
|
||||
Shape::Text(mut t) => {
|
||||
t.text = clip(t.text);
|
||||
t.color &= 0xFF_FFFF;
|
||||
Shape::Text(t)
|
||||
}
|
||||
other => other,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl render::Host for State {
|
||||
fn set_hud(&mut self, shapes: Vec<Shape>) {
|
||||
self.shapes = shapes
|
||||
.into_iter()
|
||||
.take(SHAPES)
|
||||
.map(|shape| match shape {
|
||||
Shape::Sprite(mut s) => {
|
||||
s.sprite = clip(s.sprite);
|
||||
Shape::Sprite(s)
|
||||
}
|
||||
Shape::Item(mut i) => {
|
||||
i.item = clip(i.item);
|
||||
i.scale = if i.scale.is_finite() {
|
||||
i.scale.clamp(0.0, 16.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Shape::Item(i)
|
||||
}
|
||||
Shape::Text(mut t) => {
|
||||
t.text = clip(t.text);
|
||||
t.color &= 0xFF_FFFF;
|
||||
Shape::Text(t)
|
||||
}
|
||||
other => other,
|
||||
})
|
||||
.collect();
|
||||
self.shapes = clip_shapes(shapes);
|
||||
}
|
||||
fn set_corner(&mut self, corner: RenderCorner, width: f32, height: f32, shapes: Vec<Shape>) {
|
||||
let size = |v: f32| {
|
||||
if v.is_finite() {
|
||||
v.clamp(0.0, 1024.0)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
self.corner = Some(CornerPanel {
|
||||
corner,
|
||||
width: size(width),
|
||||
height: size(height),
|
||||
shapes: clip_shapes(shapes),
|
||||
});
|
||||
}
|
||||
fn clear_corner(&mut self) {
|
||||
self.corner = None;
|
||||
}
|
||||
fn text_width(&mut self, text: String) -> f32 {
|
||||
let widths = &self.snapshot.font_widths;
|
||||
text.chars()
|
||||
.map(|c| widths.get(c as usize).copied().unwrap_or(6.0))
|
||||
.sum::<f32>()
|
||||
.ceil()
|
||||
}
|
||||
fn frame_stats(&mut self) -> FrameRate {
|
||||
let (fps, min, low) = self.snapshot.frame;
|
||||
FrameRate { fps, min, low }
|
||||
}
|
||||
fn gui_size(&mut self) -> (f32, f32) {
|
||||
self.snapshot.gui_size
|
||||
|
||||
@@ -98,7 +98,7 @@ fn player() -> Snapshot {
|
||||
day_time: 24000 + 6000,
|
||||
}),
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
..Snapshot::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(), 1);
|
||||
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 }));
|
||||
@@ -461,7 +461,6 @@ 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);
|
||||
@@ -546,6 +545,47 @@ fn input_claims_keys_and_events() {
|
||||
assert_eq!(chat(&mut mods), ["holding minecraft:stick x3 in 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_panels_text_width_and_readings() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
// A font of 5-pixel glyphs, 3-pixel spaces.
|
||||
let mut widths = vec![5.0f32; 0x250];
|
||||
widths[' ' as usize] = 3.0;
|
||||
mods.set_snapshot(Snapshot {
|
||||
frame: (60, 41, 52),
|
||||
mappings: vec![("key.forward", "W".into(), true)],
|
||||
cps: (7, 2),
|
||||
font_widths: widths.into(),
|
||||
..Snapshot::default()
|
||||
});
|
||||
assert!(mods.command("corner"));
|
||||
let panels: Vec<_> = mods.corner_panels().cloned().collect();
|
||||
assert_eq!(panels.len(), 1);
|
||||
// "60 fps": five glyphs and a space, plus the box's 4.
|
||||
assert_eq!(
|
||||
(panels[0].width, panels[0].height),
|
||||
(5.0 * 5.0 + 3.0 + 4.0, 12.0)
|
||||
);
|
||||
assert_eq!(panels[0].shapes.len(), 2);
|
||||
assert!(matches!(
|
||||
panels[0].corner,
|
||||
horizon_mods::RenderCorner::TopRight
|
||||
));
|
||||
assert!(matches!(
|
||||
&mods.settings_widgets(0)[0],
|
||||
horizon_mods::UiWidget::Button(b) if b.id == 3 && b.label == "Corner: Top Right"
|
||||
));
|
||||
mods.drain();
|
||||
assert!(mods.command("readings"));
|
||||
assert_eq!(
|
||||
mods.drain(),
|
||||
[Output::Chat {
|
||||
name: "Test UI Guest".into(),
|
||||
text: "60 41 52; forward W true; cps 7 2; other true".into(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_mods_load_without_an_engine() {
|
||||
let manifest = r#"
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! 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`;
|
||||
//! `/input_claim`, `/input_poll` and `/input_held` test `input`.
|
||||
//! `/input_claim`, `/input_poll` and `/input_held` test `input`;
|
||||
//! `/corner` and `/readings` the calls the official extras mods use.
|
||||
use horizon_mod_sdk::{
|
||||
Mod, Registration, chat,
|
||||
input::{self, Event},
|
||||
@@ -92,6 +93,8 @@ impl Mod for Guest {
|
||||
"input_claim",
|
||||
"input_poll",
|
||||
"input_held",
|
||||
"corner",
|
||||
"readings",
|
||||
]
|
||||
.into_iter()
|
||||
.fold(Registration::new(), Registration::command);
|
||||
@@ -107,6 +110,49 @@ impl Mod for Guest {
|
||||
"ui_close" => ui::close_screen(),
|
||||
"render_hud" => render::set_hud(&shapes()),
|
||||
"render_clear" => render::set_hud(&[]),
|
||||
// An FPS-counter-like box: as wide as its text plus 4.
|
||||
"corner" => {
|
||||
let text = "60 fps";
|
||||
let w = render::text_width(text) + 4.0;
|
||||
render::set_corner(
|
||||
render::Corner::TopRight,
|
||||
w,
|
||||
12.0,
|
||||
&[
|
||||
Shape::Fill(FillShape {
|
||||
rect: Rect {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
w,
|
||||
h: 12.0,
|
||||
},
|
||||
color: 0x78000000,
|
||||
}),
|
||||
Shape::Text(TextShape {
|
||||
text: text.into(),
|
||||
at: Point { x: 2.0, y: 2.0 },
|
||||
color: 0xFFFFFF,
|
||||
centered: false,
|
||||
shadow: true,
|
||||
}),
|
||||
],
|
||||
);
|
||||
ui::set_settings(&[Widget::Button(ui::ButtonWidget {
|
||||
id: 3,
|
||||
label: "Corner: Top Right".into(),
|
||||
})]);
|
||||
}
|
||||
"readings" => {
|
||||
let f = render::frame_stats();
|
||||
let fwd = input::mapping("key.forward")
|
||||
.map_or("none".into(), |m| format!("{} {}", m.label, m.down));
|
||||
let (l, r) = input::clicks_per_second();
|
||||
let none = input::mapping("key.inventory").is_none();
|
||||
chat::show(&format!(
|
||||
"{} {} {}; forward {fwd}; cps {l} {r}; other {none}",
|
||||
f.fps, f.min, f.low
|
||||
));
|
||||
}
|
||||
"input_claim" => {
|
||||
input::claim_items(&["minecraft:stick".into()]);
|
||||
input::register_key("wheel", "Open the wheel", "key.keyboard.r")?;
|
||||
@@ -147,11 +193,17 @@ impl Mod for Guest {
|
||||
chat::show("closed");
|
||||
}
|
||||
fn ui_settings_opened(&mut self) {
|
||||
ui::set_settings(&[Widget::Text(TextWidget {
|
||||
id: 1,
|
||||
text: "fresh".into(),
|
||||
color: 0x33CC33,
|
||||
})]);
|
||||
ui::set_settings(&[
|
||||
Widget::Text(TextWidget {
|
||||
id: 1,
|
||||
text: "fresh".into(),
|
||||
color: 0x33CC33,
|
||||
}),
|
||||
Widget::Button(ui::ButtonWidget {
|
||||
id: 3,
|
||||
label: "Corner: Top Right".into(),
|
||||
}),
|
||||
]);
|
||||
chat::show("settings opened");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +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 |
|
||||
| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items, and add keys |
|
||||
|
||||
## World `horizon-mod`
|
||||
|
||||
@@ -188,13 +188,21 @@ Rows the player picks one of, as an options page lists choices: a pick is `ui-ev
|
||||
| `rows` | `list<string>` | The rows' texts, at most 512, each up to 256 characters. |
|
||||
| `selected` | `option<u32>` | The row to mark as the current choice, if any. |
|
||||
|
||||
### variant `widget`
|
||||
### record `button-widget`
|
||||
|
||||
A thing on a mod's screen or settings page.
|
||||
A thing on a mod's screen or settings page. A button as the options pages have them (200 × 20): a click is `ui-events::select(id, 0)`. Mods cycle its label for a choice ("Corner: Top Left").
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `id` | `u32` | The mod's own name for the widget. |
|
||||
| `label` | `string` | Up to 256 characters. |
|
||||
|
||||
### variant `widget`
|
||||
|
||||
| Case | Payload | |
|
||||
| --- | --- | --- |
|
||||
| `text` | `text-widget` | Text the player reads. |
|
||||
| `button` | `button-widget` | A button. |
|
||||
| `item` | `item-widget` | An item's icon and name. |
|
||||
| `list` | `list-widget` | Rows the player picks from. |
|
||||
|
||||
@@ -257,12 +265,23 @@ The main hand's stack.
|
||||
| `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` | |
|
||||
|
||||
### record `mapping-state`
|
||||
|
||||
A mapping as the player has bound it.
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `label` | `string` | The bound key's name as Controls shows it: `W`, `Space`, `LMB`. |
|
||||
| `down` | `bool` | Held down now (as of this frame for a mod with a `frame` hook, else this tick). |
|
||||
|
||||
| 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. |
|
||||
| `mapping` | `func(name: string) -> option<mapping-state>` | A movement or click mapping as the player has bound it: `key.forward`, `key.left`, `key.back`, `key.right`, `key.jump`, `key.sneak`, `key.sprint`, `key.attack` or `key.use`. None for another name. |
|
||||
| `clicks-per-second` | `func() -> tuple<u32, u32>` | Clicks of the attack and use buttons in the last second. |
|
||||
|
||||
## `render`
|
||||
|
||||
@@ -270,6 +289,17 @@ Access: capability `render`.
|
||||
|
||||
Capability `render` (experimental: the manifest needs `experimental = ["render"]`): shapes the game draws for the mod with its own renderer, kept until the mod replaces them (no call per frame). A mod never supplies shader code.
|
||||
|
||||
### enum `corner`
|
||||
|
||||
A corner of the screen, as `hud`'s panels use them.
|
||||
|
||||
| Case | |
|
||||
| --- | --- |
|
||||
| `top-left` | |
|
||||
| `top-right` | |
|
||||
| `bottom-left` | |
|
||||
| `bottom-right` | |
|
||||
|
||||
### record `rect`
|
||||
|
||||
A rectangle in GUI pixels: the top left corner and the size.
|
||||
@@ -342,11 +372,23 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun
|
||||
| `item` | `item-shape` | |
|
||||
| `text` | `text-shape` | |
|
||||
|
||||
### record `frame-rate`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `fps` | `u32` | Frames drawn in the last second. |
|
||||
| `min` | `u32` | The slowest frame's rate, and the 1% low (the 99th percentile frame time's rate), over the last 5 seconds. |
|
||||
| `low` | `u32` | |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `set-hud` | `func(shapes: list<shape>)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. |
|
||||
| `gui-size` | `func() -> tuple<f32, f32>` | The screen's size in GUI pixels (width, height), as of this tick. |
|
||||
| `shake` | `func(strength: f32, seconds: f32)` | Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that fades out over `seconds` (at most 10). Jolts add up to 1. The view turns, the player doesn't, and the player's Distortion Effects option scales it (0 turns it off). |
|
||||
| `set-corner` | `func(corner: corner, width: f32, height: f32, shapes: list<shape>)` | Replaces the mod's corner panel: shapes in GUI pixels from the top left of a `width` × `height` box that the game places in `corner`, stacked with the game's overlays and the other mods' panels (under the status effects at the top right), as `hud`'s panels are. |
|
||||
| `clear-corner` | `func()` | Removes the mod's corner panel. |
|
||||
| `text-width` | `func(text: string) -> f32` | The width of one line of text in GUI pixels, in the HUD's font: exact for Latin letters (U+0000 to U+024F), 6 per other character. |
|
||||
| `frame-stats` | `func() -> frame-rate` | The game's frame counter, recomputed twice a second. |
|
||||
|
||||
## `events`
|
||||
|
||||
|
||||
@@ -99,6 +99,8 @@ What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
## Changelog
|
||||
|
||||
- Experimental: `ui` button widget; `render.set-corner`, `text-width`, `frame-stats`; `input.mapping`,
|
||||
`clicks-per-second` (what the official FPS, keystrokes and zoom mods need).
|
||||
- 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
|
||||
|
||||
+3
-3
@@ -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, 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"]` |
|
||||
| `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. 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()`; `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 |
|
||||
|---|---|
|
||||
|
||||
Reference in New Issue
Block a user