Merge pull request #2318 from ludovic111/feat/mod-recipe-actions

🤖 Agent: #2306 has merged and this PR's base is main. recipes.place and recipes.give at API level 6, give cut to one stack. Sandbox (31), api_reference and clippy -D warnings pass; the actions e2e passed 58/58 in five modes. Queued at bd1436f16.
This commit is contained in:
Ludovic Marie
2026-10-26 22:31:39 +01:00
committed by GitHub
13 changed files with 256 additions and 10 deletions
+4
View File
@@ -273,6 +273,10 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
}
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
Output::PlaceRecipe { book_id, all } => {
format!("placed recipe {book_id}{}", if all { " (all)" } else { "" })
}
Output::Give { item, count, .. } => format!("gave {count} {item}"),
Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s")
}
@@ -70,6 +70,28 @@ fn recipe(id: String, kind: RecipeKind) -> Recipe {
}
impl Game<'_> {
/// `recipes.give`: a creative player takes the stack as from the
/// creative inventory; a server hears it as `SetCreativeModeSlot`
/// through the inventory's sync, and refuses it unless creative.
pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) {
let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else {
return;
};
if !self.creative {
return;
}
let (damage, extra) = horizon_client::item_data::command_components(components)
.map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
});
let _ = self.give(ItemStack {
item: item.into(),
// One stack at most, as the creative inventory hands out.
count: count.min(max),
damage,
extra,
});
}
/// Capability `recipes`'s tables and known displays for this tick's
/// snapshot; nothing while no running mod reads them.
pub(super) fn mod_recipes(&mut self) -> (Option<Arc<Recipes>>, Arc<[i32]>) {
+14
View File
@@ -474,6 +474,8 @@ impl Game<'_> {
view_hit: self.mod_view_hit(),
recipes,
known_recipes,
placing: self.mod_recipe_screen(),
creative: self.creative,
}
}
/// The first block along the player's view within
@@ -711,6 +713,18 @@ impl Game<'_> {
self.mods.shake.add(strength, seconds);
continue;
}
Output::PlaceRecipe { book_id, all } => {
self.mod_place_recipe(book_id, all);
continue;
}
Output::Give {
item,
count,
components,
} => {
self.mod_give(&item, count, &components);
continue;
}
Output::CloseScreen { owner } => {
if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) {
self.close_mod_screen(false);
@@ -845,6 +845,34 @@ impl Game<'_> {
self.recipe_ui.ghost.clear();
self.place_recipe(book_type, entry_index, use_max);
}
/// Whether the open screen takes `recipes.place`: a crafting grid's
/// book (the inventory's or a crafting table's).
#[cfg(feature = "mods")]
pub(super) fn mod_recipe_screen(&self) -> bool {
self.screen == Screen::Inventory
&& self.active_book() == Some(BookType::Crafting)
&& !self.spectator()
}
/// `recipes.place`: the book's click on the recipe with this display
/// id, refused as `handlePlaceRecipe` refuses it (no crafting screen,
/// not in the player's book; an impossible one in `place_recipe`).
#[cfg(feature = "mods")]
pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) {
if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) {
return;
}
self.ensure_book();
let Some(index) = self
.recipe_ui
.book
.as_ref()
.and_then(|b| b.entries.iter().position(|e| e.display_id == display_id))
else {
return;
};
self.recipe_ui.ghost.clear();
self.place_recipe(BookType::Crafting, index, all);
}
/// `ServerboundPlaceRecipePacket`: the server places the recipe
/// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost
/// recipe when the items are missing.
+12
View File
@@ -507,6 +507,18 @@ interface recipes {
all: func() -> list<recipe>;
/// The `book-id`s of the recipes the player's recipe book holds now.
known: func() -> list<s32>;
/// Places a recipe in the open screen's grid as a click in the recipe
/// book does (`ServerboundPlaceRecipePacket`): the inventory's grid or
/// a crafting table. `all` places as many as the items allow, as with
/// Shift. Refused while no such screen is open, for a recipe the
/// player's book doesn't hold and for one that can't be placed; one
/// missing items shows as a ghost in the grid, as in the book.
place: func(book-id: s32, all: bool) -> result<_, string>;
/// Creative mode only: gives the player the stack, as taking it from
/// the creative inventory does (`ServerboundSetCreativeModeSlot`): the
/// selected slot first, then the hotbar, then the inventory. The count
/// is cut to one stack of the item (64, 16 or 1).
give: func(stack: stack) -> result<_, string>;
}
/// Capability `ui` (experimental): a recipe viewer's panel beside the
+3 -1
View File
@@ -13,7 +13,7 @@ pub const LEVEL: u32 = 6;
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
/// test fails until it is listed here).
pub const FUNCTIONS: [(&str, u32); 43] = [
pub const FUNCTIONS: [(&str, u32); 45] = [
("log.write", 0),
("game.get-player", 0),
("game.get-clock", 0),
@@ -57,6 +57,8 @@ pub const FUNCTIONS: [(&str, u32); 43] = [
("browser.set-items", 6),
("browser.poll", 6),
("browser.set-recipes", 6),
("recipes.place", 6),
("recipes.give", 6),
];
/// What the game's program carries so the launcher can read its level
+3 -1
View File
@@ -167,7 +167,9 @@ impl Capability {
}
Capability::Players => "see who is on the server and message them",
Capability::World => "read and change the world's blocks",
Capability::Recipes => "read the game's recipes and items, and which recipes you know",
Capability::Recipes => {
"read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items"
}
}
}
/// The capability a component import needs, `Ok(None)` for one every
+63
View File
@@ -161,6 +161,10 @@ pub struct Snapshot {
pub recipes: Option<Arc<Recipes>>,
/// The `book-id`s of the recipes the player's book holds.
pub known_recipes: Arc<[i32]>,
/// The open screen takes recipes (`recipes.place`).
pub placing: bool,
/// The player is in creative mode (`recipes.give`).
pub creative: bool,
}
/// Capability `recipes`'s tables: `items` in the registry's order, which
@@ -232,6 +236,15 @@ pub enum Output {
CloseScreen { owner: usize },
/// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10).
Shake { strength: f32, seconds: f32 },
/// `recipes.place`: the recipe book's click on this display id, all of
/// it when `all`.
PlaceRecipe { book_id: i32, all: bool },
/// `recipes.give`: a stack for a creative player.
Give {
item: String,
count: u32,
components: String,
},
}
/// The game's world as capability `world` reads it during a call: the
@@ -367,6 +380,8 @@ pub struct RecipePage {
static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// Items a panel may hold, and events kept for `browser.poll`.
const BROWSER_ITEMS: usize = 8192;
/// `recipes.place` and `give` calls a hook call may make.
const RECIPE_ACTIONS: usize = 36;
/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles.
const BROWSER_RECIPES: usize = 256;
const RECIPE_SLOTS: usize = 9;
@@ -1384,6 +1399,54 @@ impl recipes::Host for State {
fn known(&mut self) -> Vec<i32> {
self.snapshot.known_recipes.to_vec()
}
fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> {
self.recipe_action()?;
if !self.snapshot.placing {
return Err("no screen that takes recipes is open".into());
}
if !self.snapshot.known_recipes.contains(&book_id) {
return Err(format!(
"recipe {book_id} is not in the player's recipe book"
));
}
self.out.push(Output::PlaceRecipe { book_id, all });
Ok(())
}
fn give(&mut self, stack: RecipeStack) -> Result<(), String> {
self.recipe_action()?;
if !self.snapshot.creative {
return Err("only in creative mode".into());
}
let item = self
.snapshot
.recipes
.as_ref()
.and_then(|r| r.items.get(stack.item as usize))
.ok_or_else(|| format!("no item {}", stack.item))?
.id
.clone();
self.out.push(Output::Give {
item,
count: stack.count.clamp(1, 99),
components: clip_to(stack.components, 4096),
});
Ok(())
}
}
impl State {
/// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call.
fn recipe_action(&self) -> Result<(), String> {
let done = self
.out
.iter()
.filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. }))
.count();
if done < RECIPE_ACTIONS {
Ok(())
} else {
Err(format!("at most {RECIPE_ACTIONS} places and gives a call"))
}
}
}
impl State {
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
+42 -1
View File
@@ -1084,8 +1084,9 @@ fn recipes_reads_the_tables() {
recipes[1].kind = RecipeKind::Brewing;
recipes[1].results[0].components =
"[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into();
let mods_recipes = Some(std::sync::Arc::new(Recipes { items, recipes }));
mods.set_snapshot(Snapshot {
recipes: Some(std::sync::Arc::new(Recipes { items, recipes })),
recipes: mods_recipes.clone(),
known_recipes: vec![1, 5, 9].into(),
..Snapshot::default()
});
@@ -1116,6 +1117,46 @@ fn recipes_reads_the_tables() {
.all(|e| e.status == horizon_mods::Status::Running),
"it ran out of fuel"
);
// Actions: refused without a crafting screen, for an unknown recipe,
// and outside creative mode.
assert_eq!(
said(&mut mods, "recipe_place minecraft:recipe_5"),
["place minecraft:recipe_5: no screen that takes recipes is open"]
);
let mut snap = Snapshot {
recipes: mods_recipes.clone(),
known_recipes: vec![1, 5, 9].into(),
placing: true,
..Snapshot::default()
};
mods.set_snapshot(snap.clone());
assert_eq!(
said(&mut mods, "recipe_place minecraft:recipe_6"),
["place minecraft:recipe_6: recipe 6 is not in the player's recipe book"]
);
assert!(mods.command("recipe_place minecraft:recipe_5 all"));
assert_eq!(
mods.drain()[0],
Output::PlaceRecipe {
book_id: 5,
all: true
}
);
assert_eq!(
said(&mut mods, "recipe_give minecraft:item_7 3"),
["give minecraft:item_7: only in creative mode"]
);
snap.creative = true;
mods.set_snapshot(snap);
assert!(mods.command("recipe_give minecraft:item_7 3"));
assert_eq!(
mods.drain()[0],
Output::Give {
item: "minecraft:item_7".into(),
count: 3,
components: String::new()
}
);
// Without the game's tables (no mod read them yet): empty, not a trap.
mods.set_snapshot(Snapshot::default());
assert_eq!(
+60 -4
View File
@@ -12,7 +12,9 @@
//! items, `/browser` alone empties it) and registers the keys `recipe` (R)
//! and `uses` (U); `/browser_poll` says what the player did on it;
//! `/browser_recipes ID` shows the recipes making ID (`/browser_recipes`
//! alone: the items again).
//! alone: the items again). `/recipe_place ID [all]` places that recipe
//! with `recipes.place`; `/recipe_give ITEM [COUNT]` gives with
//! `recipes.give`.
use horizon_mod_sdk::{
Mod, Registration, browser, chat, command, game,
input::{self, Event},
@@ -69,7 +71,11 @@ fn shapes() -> Vec<Shape> {
]
}
struct Guest;
struct Guest {
/// `/recipe_place ID [all] later`: placed on the first tick a crafting
/// screen is open.
pending: Option<(i32, bool, String)>,
}
fn widgets() -> Vec<Widget> {
vec![
@@ -113,12 +119,15 @@ impl Mod for Guest {
"browser",
"browser_poll",
"browser_recipes",
"recipe_place",
"recipe_give",
"corner",
"readings",
]
.into_iter()
.fold(Registration::new(), Registration::command);
Ok((Guest, hooks))
.fold(Registration::new(), Registration::command)
.on_tick();
Ok((Guest { pending: None }, hooks))
}
fn command(&mut self, name: &str, args: &str) -> Result<Option<String>, String> {
match name {
@@ -385,6 +394,44 @@ impl Mod for Guest {
browser::set_recipes(&format!("Recipes for {args}"), &tabs, 0, &views);
chat::show(&format!("recipes shown: {}", views.len()));
}
"recipe_place" => {
let mut words = args.split_whitespace();
let id = words.next().unwrap_or_default();
let rest: Vec<&str> = words.collect();
let all = rest.contains(&"all");
let book = recipes::all()
.iter()
.find(|r| r.id == id)
.map(|r| r.book_id);
if let Some(b) = book.filter(|_| rest.contains(&"later")) {
self.pending = Some((b, all, id.to_owned()));
chat::show(&format!("place {id}: waiting"));
return Ok(None);
}
chat::show(&match book.map(|b| recipes::place(b, all)) {
Some(Ok(())) => format!("place {id}: ok"),
Some(Err(e)) => format!("place {id}: {e}"),
None => format!("place {id}: no such recipe"),
});
}
"recipe_give" => {
let mut words = args.split_whitespace();
let id = words.next().unwrap_or_default();
let count = words.next().and_then(|c| c.parse().ok()).unwrap_or(1);
let item = recipes::items().iter().position(|i| i.id == id);
let result = item.map(|i| {
recipes::give(&recipes::Stack {
item: i as u32,
count,
components: String::new(),
})
});
chat::show(&match result {
Some(Ok(())) => format!("give {id}: ok"),
Some(Err(e)) => format!("give {id}: {e}"),
None => format!("give {id}: no such item"),
});
}
"browser_poll" => {
let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components);
// A hook shows at most 8 chat lines: the count, then the first 7.
@@ -421,6 +468,15 @@ impl Mod for Guest {
}
Ok(None)
}
fn tick(&mut self, _tick: u64) {
if let Some((book, all, id)) = self.pending.take() {
match recipes::place(book, all) {
Err(e) if e.starts_with("no screen") => self.pending = Some((book, all, id)),
Ok(()) => chat::show(&format!("place {id}: ok")),
Err(e) => chat::show(&format!("place {id}: {e}")),
}
}
}
fn ui_select(&mut self, id: u32, row: u32) {
chat::show(&format!("selected {id}:{row}"));
}
+3 -1
View File
@@ -18,7 +18,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys |
| `players` | [`players`](#players) | see who is on the server and message them |
| `world` | [`world`](#world) | read and change the world's blocks |
| `recipes` | [`recipes`](#recipes) | read the game's recipes and items, and which recipes you know |
| `recipes` | [`recipes`](#recipes) | read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items |
## World `horizon-mod`
@@ -531,6 +531,8 @@ The station a recipe is made at.
| `items` | `func() -> list<item>` | Every item, in the registry's order: `stack.item` indexes this list. |
| `all` | `func() -> list<recipe>` | Every recipe: the book's in its order, then campfire, stonecutting, smithing and brewing. They don't change while a world is open. |
| `known` | `func() -> list<s32>` | The `book-id`s of the recipes the player's recipe book holds now. |
| `place` | `func(book-id: s32, all: bool) -> result<_, string>` | Places a recipe in the open screen's grid as a click in the recipe book does (`ServerboundPlaceRecipePacket`): the inventory's grid or a crafting table. `all` places as many as the items allow, as with Shift. Refused while no such screen is open, for a recipe the player's book doesn't hold and for one that can't be placed; one missing items shows as a ghost in the grid, as in the book. |
| `give` | `func(stack: stack) -> result<_, string>` | Creative mode only: gives the player the stack, as taking it from the creative inventory does (`ServerboundSetCreativeModeSlot`): the selected slot first, then the hotbar, then the inventory. The count is cut to one stack of the item (64, 16 or 1). |
## `browser`
+1 -1
View File
@@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says
A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every
function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`):
level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`, level 5 `recipes` (`items`, `all`, `known`), level 6 `browser` (`set-items`, `poll`, `set-recipes`). A mod needs the level of
level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`, level 5 `recipes` (`items`, `all`, `known`), level 6 `browser` (`set-items`, `poll`, `set-recipes`) and `recipes.place` and `recipes.give`. A mod needs the level of
the newest function it imports (a component imports only the functions it calls). The level is read from the file,
never declared:
+1 -1
View File
@@ -91,7 +91,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
| `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; `browser.set-items`, `browser.poll`: a recipe viewer's panel of items right of the inventory and container screens (not the creative one), which the game pages and draws with its own slots and search box, and the mod hears its clicks, its searches and the mod's own keys (`input.register-key`) pressed over any item on the screen; `browser.set-recipes`: recipes in the panel's place (crafting grids, cooking, stonecutting, smithing and brewing layouts, their slots cycling through their stacks, a note and an action button each), paged by the game, with clicks on their slots, action buttons, page turns and a back button. **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); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). 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`. 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.<mod>.<name>: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"]` |
| `recipes` | `recipes` | `items()`: every item in the registry's order, with its name in the player's language and its tags; `all()`: every recipe (crafting, smelting, blasting, smoking, campfire, stonecutting, smithing, brewing), its slots as the stacks that fit each, its results, cooking time and experience, and the recipe book's id for it; `known()`: the book ids the player's recipe book holds. The recipes are the world's in single player and on Horizon's servers, vanilla 26.3's on any other server (a client is sent no others), while `known` follows that server's book. The game makes the tables once, when a mod first reads them. **Experimental:** `experimental = ["recipes"]` |
| `recipes` | `recipes` | `items()`: every item in the registry's order, with its name in the player's language and its tags; `all()`: every recipe (crafting, smelting, blasting, smoking, campfire, stonecutting, smithing, brewing), its slots as the stacks that fit each, its results, cooking time and experience, and the recipe book's id for it; `known()`: the book ids the player's recipe book holds; `place(book-id, all)`: the recipe book's click on a recipe, in the open inventory's or crafting table's grid (refused for a recipe the player's book doesn't hold, as vanilla's server refuses it); `give(stack)`: in creative mode, the stack into the player's inventory, as from the creative inventory. The recipes are the world's in single player and on Horizon's servers, vanilla 26.3's on any other server (a client is sent no others), while `known` follows that server's book. The game makes the tables once, when a mod first reads them. **Experimental:** `experimental = ["recipes"]` |
| Hook (export) | When |
|---|---|