From 409a8281283d7776dbb25e8c2f42863cc083971e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:11:29 +0100 Subject: [PATCH 1/6] mods: capability recipes (API level 4), the game's items and recipes for recipe viewers recipes.items() lists every item in registry order, with its name in the player's language and its tags. recipes.all() lists every recipe: crafting and furnace ones from the recipe book's own entries (vanilla's displays and display ids), then campfire, stonecutting, smithing and brewing (display only). Stacks point into the item table by index. recipes.known() gives the book ids the player's recipe book holds, from the client book in every mode, so on a server it follows the server's book. The game builds the tables once, the first time a running mod reads them. Experimental, new functions only. Smithing::Transform now keeps its recipe id. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/mod_recipes.rs | 252 ++++++++++++++++++ crates/horizon-client/src/game/mods.rs | 11 + crates/horizon-client/src/game/recipe_book.rs | 19 ++ crates/horizon-client/src/stations.rs | 3 + crates/horizon-mod-sdk/src/lib.rs | 2 +- crates/horizon-mod-sdk/wit/horizon.wit | 76 ++++++ crates/horizon-mods/src/api_level.rs | 7 +- crates/horizon-mods/src/manifest.rs | 11 +- crates/horizon-mods/src/runtime.rs | 54 ++++ crates/horizon-mods/tests/sandbox.rs | 90 ++++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 40 ++- docs/api/mods-reference.md | 72 ++++- docs/api/stability.md | 2 +- docs/mods.md | 2 +- 15 files changed, 630 insertions(+), 13 deletions(-) create mode 100644 crates/horizon-client/src/game/mod_recipes.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9bb6602fd..826ea73c1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -100,6 +100,8 @@ mod minecarts; mod mob_blocks; mod mob_gear; mod mod_input; +#[cfg(feature = "mods")] +mod mod_recipes; mod mod_render; mod mods; mod mount_menu; diff --git a/crates/horizon-client/src/game/mod_recipes.rs b/crates/horizon-client/src/game/mod_recipes.rs new file mode 100644 index 000000000..0d57e1f94 --- /dev/null +++ b/crates/horizon-client/src/game/mod_recipes.rs @@ -0,0 +1,252 @@ +//! Capability `recipes` (docs/mods.md): every item and recipe the game +//! knows, made once for the mods that read them, and the recipe book's +//! known displays. The recipes are the window's own data: the world's in +//! single player, vanilla's on a server (a client is sent no others), while +//! the known displays follow the server's book as the recipe book does. +use super::Game; +use horizon_client::{ + crafting::Ingredient, + items::ItemStack, + recipe_book::{Category, Display}, + stations::Smithing, +}; +use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; +use std::{collections::HashMap, sync::Arc}; + +/// Item id -> its index in [`Recipes::items`]. +struct Index(HashMap, u32>); +impl Index { + fn stack(&self, item: &str, count: u32, components: String) -> Option { + Some(RecipeStack { + item: *self.0.get(item)?, + count, + components, + }) + } + fn of(&self, s: &ItemStack) -> Option { + self.stack(&s.item, s.count, components(s)) + } + fn any(&self, i: &Ingredient) -> Vec { + i.1.iter() + .filter_map(|id| self.stack(id, 1, String::new())) + .collect() + } +} + +/// A stack's components beyond its item's, as vanilla's item syntax writes +/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "". +fn components(s: &ItemStack) -> String { + use horizon_world::nbt::Tag; + let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else { + return String::new(); + }; + let parts: Vec = entries + .iter() + .map(|(k, v)| { + format!( + "{}={}", + k.to_string_lossy(), + horizon_client::snbt::to_snbt(v) + ) + }) + .collect(); + format!("[{}]", parts.join(",")) +} + +fn recipe(id: String, kind: RecipeKind) -> Recipe { + Recipe { + id, + kind, + category: String::new(), + group: String::new(), + width: 0, + height: 0, + slots: Vec::new(), + results: Vec::new(), + cooking_time: 0, + experience: 0.0, + book_id: -1, + } +} + +impl Game<'_> { + /// 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<[i32]>) { + if !self.mods.mods.wants_recipes() { + return (None, Arc::from([])); + } + if self.mods.recipes.is_none() { + self.mods.recipes = Some(Arc::new(self.make_mod_recipes())); + } + let (version, known) = self.recipe_book_displays(); + if self.mods.known_recipes.0 != Some(version) { + self.mods.known_recipes = (Some(version), known.into()); + } + (self.mods.recipes.clone(), self.mods.known_recipes.1.clone()) + } + + fn make_mod_recipes(&mut self) -> Recipes { + let names = &self.pack.names; + let items = self.res.items(); + let mut tags: HashMap<&str, Vec> = HashMap::new(); + for (tag, members) in &items.item_tags { + for m in members { + tags.entry(m).or_default().push(tag.clone()); + } + } + let table: Vec = items + .registry_order + .iter() + .map(|id| RecipeItem { + id: id.to_string(), + name: names.display_item(id), + tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| { + t.sort(); + t + }), + }) + .collect(); + let index = Index( + items + .registry_order + .iter() + .enumerate() + .map(|(i, id)| (id.clone(), i as u32)) + .collect(), + ); + let mut out = Vec::new(); + let cooking: HashMap = self + .res + .recipes() + .cooking + .iter() + .map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience))) + .collect(); + for e in self.recipe_book_entries() { + let furnace = |c: Category| match c.name().split('_').next() { + Some("blast") => RecipeKind::Blasting, + Some("smoker") => RecipeKind::Smoking, + _ => RecipeKind::Smelting, + }; + let kind = match &e.display { + Display::Shaped { .. } => RecipeKind::CraftingShaped, + Display::Shapeless(_) => RecipeKind::CraftingShapeless, + Display::Furnace(_) => furnace(e.category), + }; + let mut r = recipe(e.id.clone(), kind); + r.category = e.category.name().to_owned(); + r.group = e.group.clone().unwrap_or_default(); + r.book_id = e.display_id; + r.slots = match &e.display { + Display::Shaped { + width, + height, + cells, + } => { + (r.width, r.height) = (*width as u32, *height as u32); + cells + .iter() + .map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i))) + .collect() + } + Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(), + Display::Furnace(i) => vec![index.any(i)], + }; + // Requirements shown as other stacks (an arrow's potions): the + // requirement's index counts the filled slots only. + let filled: Vec = (0..r.slots.len()) + .filter( + |&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()), + ) + .collect(); + for (req, stacks) in &e.stacks { + if let Some(&k) = filled.get(*req) { + r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect(); + } + } + r.results = e.results().iter().filter_map(|s| index.of(s)).collect(); + if let Some(&(time, xp)) = cooking.get(&e.id) { + (r.cooking_time, r.experience) = (time, xp); + } + out.push(r); + } + for c in &self.res.recipes().cooking { + if c.kind == "minecraft:campfire_cooking" { + let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire); + r.group = c.group.clone(); + r.slots = vec![index.any(&c.ingredient)]; + r.results = index.of(&c.result).into_iter().collect(); + (r.cooking_time, r.experience) = (c.time, c.experience); + out.push(r); + } + } + let stations = self.res.stations(); + for s in &stations.recipes.stonecutting { + let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting); + r.slots = vec![index.any(&s.input)]; + r.results = index.of(&s.result).into_iter().collect(); + out.push(r); + } + for s in &stations.recipes.smithing { + let (id, template, base, addition, results) = match s { + Smithing::Transform { + id, + template, + base, + addition, + result, + } => ( + id, + template, + base, + addition, + index.stack(result, 1, String::new()).into_iter().collect(), + ), + Smithing::Trim { + id, + template, + base, + addition, + .. + } => (id, template, base, addition, index.any(base)), + }; + let mut r = recipe(id.clone(), RecipeKind::Smithing); + r.slots = vec![index.any(template), index.any(base), index.any(addition)]; + r.results = results; + out.push(r); + } + for b in &stations.brewing.recipes { + let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec { + let mut item_ids: Vec<&String> = p.items.iter().collect(); + item_ids.sort(); + let mut potions: Vec<&String> = p.potions.iter().flatten().collect(); + potions.sort(); + item_ids + .into_iter() + .flat_map(|item| { + let one = |c: String| index.stack(item, 1, c); + if potions.is_empty() { + one(String::new()).into_iter().collect::>() + } else { + potions + .iter() + .filter_map(|p| { + one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]")) + }) + .collect() + } + }) + .collect() + }; + let mut r = recipe(b.id.clone(), RecipeKind::Brewing); + r.slots = vec![potion(&b.input), potion(&b.reagent)]; + r.results = index.of(&b.output).into_iter().collect(); + out.push(r); + } + Recipes { + items: table, + recipes: out, + } + } +} diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 12deb61fc..156467e7a 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -70,6 +70,12 @@ pub(super) struct ModsState { /// The HUD font's advances for `render.text-width`, made once. #[cfg(feature = "mods")] font_widths: std::sync::Arc<[f32]>, + /// Capability `recipes`'s tables, made once a mod reads them. + #[cfg(feature = "mods")] + pub(super) recipes: Option>, + /// The recipe book's known displays, and the book's version they are of. + #[cfg(feature = "mods")] + pub(super) known_recipes: (Option, std::sync::Arc<[i32]>), /// Extras that are official mods now, being installed. #[cfg(feature = "mods")] pub(super) moved: super::moved_extras::MovedState, @@ -282,6 +288,8 @@ impl Game<'_> { 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; + // Content mods may have changed the items: remade on the next read. + self.mods.recipes = None; self.list_mods(); self.sync_mod_commands(); self.show_mod_output(); @@ -409,6 +417,7 @@ impl Game<'_> { .map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1)) .collect(); } + let (recipes, known_recipes) = self.mod_recipes(); Snapshot { player, clock, @@ -420,6 +429,8 @@ impl Game<'_> { font_widths: self.mods.font_widths.clone(), players: Vec::new(), view_hit: self.mod_view_hit(), + recipes, + known_recipes, } } /// The first block along the player's view within diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 96e12d79b..045abeb6f 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -338,6 +338,25 @@ impl Game<'_> { ui.client_known = Some(known.clone()); ui.client_version += 1; } + /// Every entry of the book, in its order (capability `recipes`). + #[cfg(feature = "mods")] + pub(super) fn recipe_book_entries(&mut self) -> Vec { + self.ensure_book(); + self.recipe_ui + .book + .as_ref() + .map_or_else(Vec::new, |b| b.entries.clone()) + } + /// The display ids the player's book holds, and a number that changes + /// whenever they do (capability `recipes`). + #[cfg(feature = "mods")] + pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec) { + self.sync_client_book(); + ( + self.recipe_ui.client_version, + self.recipe_ui.client.displays(), + ) + } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { let mut book = Book::build(self.res.recipes(), self.res.items()); diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 715c2663e..bd157843a 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -445,6 +445,7 @@ pub fn grindstone_experience( #[derive(Clone, Debug)] pub enum Smithing { Transform { + id: String, template: Ingredient, base: Ingredient, addition: Ingredient, @@ -524,6 +525,7 @@ impl StationRecipes { ); match v["type"].as_str().unwrap_or("") { "minecraft:smithing_transform" => smithing.push(Smithing::Transform { + id, template: ingredient(&v["template"], items), base: ingredient(&v["base"], items), addition: ingredient(&v["addition"], items), @@ -627,6 +629,7 @@ impl StationRecipes { base: b, addition: a, result, + .. } => { if t.test(template) && b.test(base) && a.test(addition) { // SmithingTransformRecipe: transmute the base keeping its components. diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 679fdc7b8..b00d06ecf 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -39,7 +39,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, input, log, render, storage, ui}; +pub use horizon::mods::{chat, command, game, hud, input, log, recipes, 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. diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index d9bb9f5c2..7d7adaa0d 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -439,6 +439,76 @@ interface events { chat: func(text: string); } +/// Capability `recipes` (experimental): the recipes and items the game +/// knows, for recipe viewers. In single player and on Horizon's servers +/// they are the world's; on any other server they are vanilla 26.3's (a +/// client is sent no others), while `known` follows that server's book. +interface recipes { + /// An item of `items`, by its index there, with a count and the + /// components it has beyond the item's own, in vanilla's item syntax + /// (`[potion_contents={potion:"minecraft:swiftness"}]`), or "". + record stack { + item: u32, + count: u32, + components: string, + } + /// The station a recipe is made at. + enum kind { + crafting-shaped, + crafting-shapeless, + smelting, + blasting, + smoking, + campfire, + stonecutting, + smithing, + brewing, + } + record recipe { + /// `minecraft:oak_planks`. + id: string, + kind: kind, + /// The recipe book's tab (`crafting_building_blocks`, + /// `furnace_food`), or "". + category: string, + /// Recipes the book shows on one button share a group, or "". + group: string, + /// A shaped recipe's grid: `slots` holds its cells row by row. + /// 0 for the other kinds. + width: u32, + height: u32, + /// Each slot's stacks, any one of which fits; an empty list is an + /// empty cell. Cooking and stonecutting: the input. Smithing: the + /// template, the base, the addition. Brewing: the bottle, the + /// reagent. + slots: list>, + /// What it makes; several when that varies (a trim on any armour). + results: list, + /// Cooking: game ticks and experience; 0 for the other kinds. + cooking-time: u32, + experience: f32, + /// The recipe book's id for it (one per way the book shows it), as + /// `known` lists them; -1 for the kinds the book doesn't show + /// (campfire, stonecutting, smithing, brewing). + book-id: s32, + } + record item { + /// `minecraft:diamond`, `:`. + id: string, + /// In the player's language. + name: string, + /// Its item tags, without the `#`. + tags: list, + } + /// Every item, in the registry's order: `stack.item` indexes this list. + items: func() -> list; + /// Every recipe: the book's in its order, then campfire, stonecutting, + /// smithing and brewing. They don't change while a world is open. + all: func() -> list; + /// The `book-id`s of the recipes the player's recipe book holds now. + known: func() -> list; +} + /// Capability `players`, server mods only (manifest `api = "0.3"`, /// experimental): the players on the server, and messages to them. interface players { @@ -545,6 +615,7 @@ world horizon-ui-mod { import ui; import render; import input; + import recipes; export ui-events; } @@ -559,3 +630,8 @@ world render-host { import render; import input; } + +/// The game's side of capability `recipes` (imports only). +world recipes-host { + import recipes; +} diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index bf87d0cfa..ff06a94ae 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 3; +pub const LEVEL: u32 = 4; /// Every function the game offers mods, as `interface.function`, with its /// 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); 34] = [ +pub const FUNCTIONS: [(&str, u32); 37] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -48,6 +48,9 @@ pub const FUNCTIONS: [(&str, u32); 34] = [ ("players.broadcast", 1), ("game.raycast", 2), ("command.run-quiet", 3), + ("recipes.items", 4), + ("recipes.all", 4), + ("recipes.known", 4), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 5ad7823aa..05cf96447 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -97,9 +97,12 @@ pub enum Capability { Input, /// The players on the server and messages to them (server mods). Players, + /// The recipes and items the game knows, for recipe viewers + /// (interface `recipes`). + Recipes, } impl Capability { - pub const ALL: [Capability; 10] = [ + pub const ALL: [Capability; 11] = [ Capability::GameRead, Capability::Chat, Capability::Hud, @@ -110,6 +113,7 @@ impl Capability { Capability::Render, Capability::Input, Capability::Players, + Capability::Recipes, ]; /// Whether a server mod may have it: the others act on a local player. pub fn on_server(self) -> bool { @@ -128,6 +132,7 @@ impl Capability { Capability::Render => "render", Capability::Input => "input", Capability::Players => "players", + Capability::Recipes => "recipes", } } /// May change in any release: a mod uses it only with @@ -135,7 +140,7 @@ impl Capability { pub fn is_experimental(self) -> bool { matches!( self, - Capability::Ui | Capability::Render | Capability::Input + Capability::Ui | Capability::Render | Capability::Input | Capability::Recipes ) } /// What the player reads before turning the mod on: "May ". @@ -153,6 +158,7 @@ impl Capability { "see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys" } Capability::Players => "see who is on the server and message them", + Capability::Recipes => "read the game's recipes and items, and which recipes you know", } } /// The capability a component import needs, `Ok(None)` for one every @@ -188,6 +194,7 @@ impl fmt::Display for Capability { Capability::Render => "render", Capability::Input => "input", Capability::Players => "players", + Capability::Recipes => "recipes", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ce48f2317..ebce03944 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -78,6 +78,18 @@ pub use render_bindings::horizon::mods::render::{ Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; +/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items. +mod recipes_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "recipes-host", + }); +} +/// What capability `recipes` reads (WIT `interface recipes`). +pub use recipes_bindings::horizon::mods::recipes::{ + Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack, +}; +use recipes_bindings::{RecipesHost, horizon::mods::recipes}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -133,6 +145,19 @@ pub struct Snapshot { /// its distance from the eye, for `game.raycast`; the game works it out /// only while a mod calls it ([`Mods::wants_raycast`]). pub view_hit: Option<(f32, Hit)>, + /// Every item and recipe, for capability `recipes`; the game makes them + /// once, and only while a mod reads them ([`Mods::wants_recipes`]). + pub recipes: Option>, + /// The `book-id`s of the recipes the player's book holds. + pub known_recipes: Arc<[i32]>, +} + +/// Capability `recipes`'s tables: `items` in the registry's order, which +/// each [`RecipeStack::item`] indexes. +#[derive(Clone, Debug, Default)] +pub struct Recipes { + pub items: Vec, + pub recipes: Vec, } /// Which mods a game starts: the window's game the client mods, the game @@ -241,6 +266,8 @@ struct Running { hooks: Hooks, /// It imports `game.raycast`. raycasts: bool, + /// It imports capability `recipes`. + reads_recipes: bool, } /// A running mod's exports and the hooks its `init` asked for. @@ -392,6 +419,8 @@ impl Mods { .map_err(|e| e.to_string())?; RenderHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + RecipesHost::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; self.engine = Some((engine, linker)); } Ok(self.engine.as_ref().expect("made above")) @@ -509,6 +538,7 @@ impl Mods { ui, hooks, raycasts: functions.iter().any(|f| f == "game.raycast"), + reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")), })) } @@ -769,6 +799,13 @@ impl Mods { .iter() .any(|e| e.run.as_ref().is_some_and(|r| r.raycasts)) } + /// Some running mod reads capability `recipes`: the snapshot needs + /// [`Snapshot::recipes`] and [`Snapshot::known_recipes`]. + pub fn wants_recipes(&self) -> bool { + self.entries + .iter() + .any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes)) + } /// Some running mod has a `frame` hook: the game refreshes the snapshot /// every frame for it. pub fn wants_frames(&self) -> bool { @@ -1125,6 +1162,23 @@ impl game::Host for State { (*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone()) } } +impl recipes::Host for State { + fn items(&mut self) -> Vec { + self.snapshot + .recipes + .as_ref() + .map_or_else(Vec::new, |r| r.items.clone()) + } + fn all(&mut self) -> Vec { + self.snapshot + .recipes + .as_ref() + .map_or_else(Vec::new, |r| r.recipes.clone()) + } + fn known(&mut self) -> Vec { + self.snapshot.known_recipes.to_vec() + } +} impl State { /// Queues a chat line unless the call already sent [`CHAT_PER_CALL`]. fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool { diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index c6b835f10..06a8e6aa2 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -26,8 +26,8 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "command", "ui", "render", "input"] -experimental = ["ui", "render", "input"] +capabilities = ["game-read", "chat", "command", "ui", "render", "input", "recipes"] +experimental = ["ui", "render", "input", "recipes"] "#; /// Builds the mods once and writes their `.hmod` files; returns the folder. @@ -238,8 +238,8 @@ id = "too_new" name = "Too New" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input"] -experimental = ["ui", "render", "input"] +capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input", "recipes"] +experimental = ["ui", "render", "input", "recipes"] "#; std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); @@ -1016,3 +1016,85 @@ fn a_server_mod_runs_only_where_the_world_does() { "a server command isn't the window's" ); } + +/// Capability `recipes`: the guest reads tables as big as vanilla's (1,500 +/// items, 1,600 recipes of nine five-item slots) within one command's fuel. +#[test] +fn recipes_reads_the_tables() { + use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let stack = |item| RecipeStack { + item, + count: 1, + components: String::new(), + }; + let items = (0..1500) + .map(|i| RecipeItem { + id: format!("minecraft:item_{i}"), + name: format!("Item {i}"), + tags: vec!["planks".into(), "logs".into()], + }) + .collect(); + let mut recipes: Vec = (0..1600) + .map(|i| Recipe { + id: format!("minecraft:recipe_{i}"), + kind: RecipeKind::CraftingShaped, + category: "crafting_misc".into(), + group: String::new(), + width: 3, + height: 3, + slots: (0..9) + .map(|k| (0..5).map(|j| stack((i + k + j) % 1500)).collect()) + .collect(), + results: vec![RecipeStack { + item: 7, + count: 4, + components: String::new(), + }], + cooking_time: 0, + experience: 0.0, + book_id: i as i32, + }) + .collect(); + recipes[1].kind = RecipeKind::Brewing; + recipes[1].results[0].components = + "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into(); + mods.set_snapshot(Snapshot { + recipes: Some(std::sync::Arc::new(Recipes { items, recipes })), + known_recipes: vec![1, 5, 9].into(), + ..Snapshot::default() + }); + let said = |mods: &mut Mods, command: &str| { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect::>() + }; + assert_eq!( + said(&mut mods, "recipes"), + ["1500 items, 1600 recipes, 3 known, 1 brewing"] + ); + assert_eq!( + said(&mut mods, "recipes minecraft:recipe_1"), + [ + "minecraft:recipe_1 Kind::Brewing 3x3 0t slots 9, the first 1 minecraft:item_1 -> \ + 4 minecraft:item_7[minecraft:potion_contents={potion:\"minecraft:swiftness\"}] known true" + ] + ); + assert!( + mods.entries() + .iter() + .all(|e| e.status == horizon_mods::Status::Running), + "it ran out of fuel" + ); + // Without the game's tables (no mod read them yet): empty, not a trap. + mods.set_snapshot(Snapshot::default()); + assert_eq!( + said(&mut mods, "recipes"), + ["0 items, 0 recipes, 0 known, 0 brewing"] + ); +} diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 74fb64350..2fd835d3c 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -6,10 +6,12 @@ //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `/corner` and `/readings` the calls the official extras mods use; //! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs -//! lines with `command.run-quiet` (`/quiet_many N`: N of them). +//! lines with `command.run-quiet` (`/quiet_many N`: N of them). `/recipes` +//! counts what `recipes` reads; `/recipes ID` describes that recipe. use horizon_mod_sdk::{ Mod, Registration, chat, command, game, input::{self, Event}, + recipes, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; @@ -102,6 +104,7 @@ impl Mod for Guest { "raycast", "quiet", "quiet_many", + "recipes", "corner", "readings", ] @@ -241,6 +244,41 @@ impl Mod for Guest { None => "no hit".into(), }); } + "recipes" => { + let items = recipes::items(); + let all = recipes::all(); + let known = recipes::known(); + let name = |s: &recipes::Stack| { + let id = items.get(s.item as usize).map_or("?", |i| i.id.as_str()); + format!("{} {id}{}", s.count, s.components) + }; + chat::show(&match all.iter().find(|r| r.id == args) { + Some(r) => format!( + "{} {:?} {}x{} {}t slots {}, the first {} -> {} known {}", + r.id, + r.kind, + r.width, + r.height, + r.cooking_time, + r.slots.len(), + r.slots + .first() + .and_then(|s| s.first()) + .map_or("-".into(), name), + r.results.first().map_or("-".into(), name), + known.contains(&r.book_id) + ), + None => format!( + "{} items, {} recipes, {} known, {} brewing", + items.len(), + all.len(), + known.len(), + all.iter() + .filter(|r| r.kind == recipes::Kind::Brewing) + .count() + ), + }); + } // Clamped to (1, 10); the two after it shake nothing. "render_shake" => { render::shake(2.0, 99.0); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index c44f27576..1ee54e70f 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -17,6 +17,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `render` | [`render`](#render) | draw on your screen, shake and zoom the camera | | `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 | +| `recipes` | [`recipes`](#recipes) | read the game's recipes and items, and which recipes you know | ## World `horizon-mod` @@ -36,7 +37,7 @@ A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs whe 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`, `input`, `log`, `game`, `chat`, `hud`, `storage`, `command` +- Imports (what the game offers): `ui`, `render`, `input`, `recipes`, `log`, `game`, `chat`, `hud`, `storage`, `command` - Exports (what the mod provides): `ui-events`, `events` ## World `ui-host` @@ -53,6 +54,13 @@ The game's side of capability `render` (imports only). - Imports (what the game offers): `render`, `input` - Exports (what the mod provides): +## World `recipes-host` + +The game's side of capability `recipes` (imports only). + +- Imports (what the game offers): `recipes` +- Exports (what the mod provides): + ## `log` Access: always granted. @@ -461,6 +469,68 @@ What the game calls. Only the hooks `init` asks for are ever called. | `command` | `func(name: string, args: string) -> result, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. | | `chat` | `func(text: string)` | Each chat line the player receives, as plain text. | +## `recipes` + +Access: capability `recipes`. + +Capability `recipes` (experimental): the recipes and items the game knows, for recipe viewers. In single player and on Horizon's servers they are the world's; on any other server they are vanilla 26.3's (a client is sent no others), while `known` follows that server's book. + +### record `stack` + +An item of `items`, by its index there, with a count and the components it has beyond the item's own, in vanilla's item syntax (`[potion_contents={potion:"minecraft:swiftness"}]`), or "". + +| Field | Type | | +| --- | --- | --- | +| `item` | `u32` | | +| `count` | `u32` | | +| `components` | `string` | | + +### enum `kind` + +The station a recipe is made at. + +| Case | | +| --- | --- | +| `crafting-shaped` | | +| `crafting-shapeless` | | +| `smelting` | | +| `blasting` | | +| `smoking` | | +| `campfire` | | +| `stonecutting` | | +| `smithing` | | +| `brewing` | | + +### record `recipe` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | `minecraft:oak_planks`. | +| `kind` | `kind` | | +| `category` | `string` | The recipe book's tab (`crafting_building_blocks`, `furnace_food`), or "". | +| `group` | `string` | Recipes the book shows on one button share a group, or "". | +| `width` | `u32` | A shaped recipe's grid: `slots` holds its cells row by row. 0 for the other kinds. | +| `height` | `u32` | | +| `slots` | `list>` | Each slot's stacks, any one of which fits; an empty list is an empty cell. Cooking and stonecutting: the input. Smithing: the template, the base, the addition. Brewing: the bottle, the reagent. | +| `results` | `list` | What it makes; several when that varies (a trim on any armour). | +| `cooking-time` | `u32` | Cooking: game ticks and experience; 0 for the other kinds. | +| `experience` | `f32` | | +| `book-id` | `s32` | The recipe book's id for it (one per way the book shows it), as `known` lists them; -1 for the kinds the book doesn't show (campfire, stonecutting, smithing, brewing). | + +### record `item` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | `minecraft:diamond`, `:`. | +| `name` | `string` | In the player's language. | +| `tags` | `list` | Its item tags, without the `#`. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `items` | `func() -> list` | Every item, in the registry's order: `stack.item` indexes this list. | +| `all` | `func() -> list` | 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` | The `book-id`s of the recipes the player's recipe book holds now. | + ## `players` Access: capability `players`. diff --git a/docs/api/stability.md b/docs/api/stability.md index df2c1aeb3..00b5541a9 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -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`. 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 `recipes` (`items`, `all`, `known`). 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: diff --git a/docs/mods.md b/docs/mods.md index 28415d28f..73ecfb9a5 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -91,6 +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. **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..: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"]` | | Hook (export) | When | |---|---| @@ -116,7 +117,6 @@ loading. Ordered by what the first native ports need: | `keys` | keybinds | registered binds appear in Controls; press/release events | | `target` | the crosshair's block or entity, with its state and NBT summary | Jade/WTHIT-style tooltips | | `inventory-read` | the player's inventory, held item, open container | AppleSkin, recipe viewers | -| `recipes` | the recipe registry and lookups | JEI/EMI-style viewers | | `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics | | `render` (world) | world-space lines, boxes and billboards, beside the HUD shapes `render` has | Litematica-style placement, waypoints | | `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) | From 8920f08fd9724262e03220a561518b0d9a252b7b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:07:44 +0100 Subject: [PATCH 2/6] Streaming: rank queued jobs again when the centre or the loading screen changes Jobs queued while the loading screen was up carried ring-order priorities, far above the plain distances used once it closed, so they waited behind every later job. The proto chunks they generated held back the decoration of the chunks around the player: at render distance 32 in-frame, nothing was decorated until every proto chunk had been generated. Queued jobs now keep their column and bias and are ranked again from the current centre, extra areas, band and loading screen when those change, as vanilla's chunk task queue follows the current ticket levels. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/streaming.rs | 122 +++++++++++++++++++++++-- 1 file changed, 113 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 643a604bc..0c9ae0c5b 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -175,6 +175,11 @@ pub enum Done { } struct Queued { priority: i64, + /// The column the job is for and what it adds to the column's distance + /// (`Streaming::submit`): the priority is computed again from them when + /// the centre moves (`Streaming::requeue`). None for saves, which go first. + at: Option<(i32, i32)>, + bias: i64, order: u64, job: Job, } @@ -222,6 +227,9 @@ pub struct Streaming { /// radius it was last ranked for. decoration_order: DecorationOrder, order_area: Option<((i32, i32), i32)>, + /// What the queued jobs' priorities were computed from (`requeue`): the + /// centre, the loading screen, the band, and the extra areas. + queue_basis: (((i32, i32), bool, Option), Vec<((i32, i32), i32)>), finishing: FxHashSet<(i32, i32)>, decorates: bool, lighting: FxHashMap<(i32, i32), u64>, @@ -544,6 +552,7 @@ impl Streaming { saving: 0, decoration_order: DecorationOrder::default(), order_area: None, + queue_basis: Default::default(), finishing: Default::default(), decorates: generator.decorates(), lighting: Default::default(), @@ -648,15 +657,39 @@ impl Streaming { world.dirty_sections.take_column(x, z); world.chunks.remove(&(x, z)) } - fn submit(&mut self, priority: i64, job: Job) { + /// Queue a job for the column `at`, nearest first: its distance (`distance`) + /// times four plus `bias`, which orders a column's jobs. A job without a + /// column (a save) goes ahead of every other. + fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) { self.order += 1; + let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias); self.shared.queue.lock().unwrap().push(Queued { priority, + at, + bias, order: self.order, job, }); self.shared.ready.notify_one(); } + /// Rank the queued jobs again when what their priorities were computed + /// from changed: the centre, the extra areas, the band, or the loading + /// screen (ring order, `Ranges::rings`, whose values are far above the + /// distances used after it). Vanilla's chunk task queue follows the + /// current ticket levels in the same way. Without it, generation queued + /// while the loading screen was up waited behind every job queued after + /// it, and with it the decoration of the chunks around the player: at + /// render distance 32 nothing was decorated until every proto chunk had + /// been generated. + fn requeue(&mut self) { + let basis = (self.center, self.loading, self.band); + if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra { + return; + } + self.queue_basis = (basis, self.extra.clone()); + let mut queue = self.shared.queue.lock().unwrap(); + rank_again(&mut queue, |x, z| self.distance(x, z)); + } fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) { self.generation_scan.exhausted = false; self.decorating -= 1; @@ -686,7 +719,7 @@ impl Streaming { self.saving += 1; // Ahead of every other job: a column generated again meanwhile // would not find them saved. - self.submit(i64::MIN, Job::Save(protos)); + self.submit(None, 0, Job::Save(protos)); } } fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) { @@ -829,6 +862,7 @@ impl Streaming { return (uploads, Vec::new()); } ExtraCover::refresh(&mut self.cover, &self.extra); + self.requeue(); self.relight_edits(world); let deferred = std::mem::take(&mut self.deferred); let received = std::iter::from_fn(|| self.results.try_recv().ok()); @@ -984,7 +1018,7 @@ impl Streaming { .expect("present proto"); self.finishing.insert((x, z)); self.written.remove(&(x, z)); - self.submit(self.distance(x, z) * 4, Job::Finish(proto)); + self.submit(Some((x, z)), 0, Job::Finish(proto)); } } // Decorate chunks whose 3x3 proto neighbourhood is available, in @@ -1052,7 +1086,7 @@ impl Streaming { w.0 = self.decoration_order.rank_or_append(w.2, w.3); } wanted.sort_unstable(); - for (_, d, x, z) in wanted { + for (_, _, x, z) in wanted { if self.decorating >= workers * 2 { break; } @@ -1091,7 +1125,7 @@ impl Streaming { Err(_) => continue, }; self.decorating += 1; - self.submit(d * 4 + 1, Job::Decorate(x, z, region)); + self.submit(Some((x, z)), 1, Job::Decorate(x, z, region)); } } self.schedule_generation(world, workers); @@ -1111,7 +1145,8 @@ impl Streaming { self.light_snapshots .insert((x, z), self.light_edit_sequence); self.submit( - self.distance(x, z) * 4 + 1, + Some((x, z)), + 1, Job::Light(x, z, region, self.sequence, self.sky_light), ); } @@ -1183,7 +1218,8 @@ impl Streaming { self.sequence += 1; self.meshing.insert((x, sy, z), self.sequence); self.submit( - self.distance(x, z) * 4 + if first { 2 } else { 0 }, + Some((x, z)), + if first { 2 } else { 0 }, Job::Mesh( x, sy, @@ -1222,9 +1258,9 @@ impl Streaming { loading: self.loading, }; if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) { - for (d, x, z) in wanted { + for (_, x, z) in wanted { self.generating.insert((x, z)); - self.submit(d * 4, Job::Generate(x, z)); + self.submit(Some((x, z)), 0, Job::Generate(x, z)); } } } @@ -1738,10 +1774,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator { }) }) } +/// The queued jobs' priorities computed again from each one's column +/// `distance` (`Streaming::submit`). +fn rank_again(queue: &mut BinaryHeap, distance: impl Fn(i32, i32) -> i64) { + if queue.is_empty() { + return; + } + let mut jobs = std::mem::take(queue).into_vec(); + for job in &mut jobs { + if let Some((x, z)) = job.at { + job.priority = distance(x, z) * 4 + job.bias; + } + } + *queue = BinaryHeap::from(jobs); +} #[cfg(test)] mod tests { use super::*; + #[test] + fn queued_jobs_follow_the_centre_and_the_loading_screen() { + let forced = HashSet::new(); + let ranges = |center| Ranges { + center, + radius: 32, + extra: &[], + forced: &forced, + cover: None, + band: None, + }; + let generate = |x, z, priority, order| Queued { + priority, + at: Some((x, z)), + bias: 0, + order, + job: Job::Generate(x, z), + }; + let loading = ranges((0, 0)); + let queued = || { + BinaryHeap::from(vec![ + // Queued while the loading screen was up: ring order. + generate(3, 1, loading.priority(3, 1, true) * 4, 1), + // Queued after it closed: plain distances, far below any ring past the first. + generate(20, 0, loading.priority(20, 0, false) * 4, 2), + Queued { + priority: i64::MIN, + at: None, + bias: 0, + order: 3, + job: Job::Save(Vec::new()), + }, + ]) + }; + let pops = |mut queue: BinaryHeap| { + std::iter::from_fn(move || queue.pop()) + .map(|q| q.at) + .collect::>() + }; + assert_eq!( + pops(queued()), + [None, Some((20, 0)), Some((3, 1))], + "the stale order" + ); + let mut queue = queued(); + rank_again(&mut queue, |x, z| loading.priority(x, z, false)); + assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]); + // The player moved: the job near the new centre goes first. + let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]); + let moved = ranges((19, 0)); + rank_again(&mut queue, |x, z| moved.priority(x, z, false)); + assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0))); + } + #[test] fn view_distance_is_vanillas_shape() { // ChunkTrackingView.isInViewDistance at render distance 12: a column From 37559dae820de4f3fee3c83dccb7dd0840640cdf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:58:06 +0100 Subject: [PATCH 3/6] pr_ready: run CI's clippy, CI's test features, Python tests and launcher rule pr_ready --quick passed #1895 while CI's clippy failed on an unused import in horizon-mods' tests: clippy on the touched crates and their dependents gives them other features than CI's workspace-wide run (Cargo unifies features over the packages it builds). - clippy: CI's two commands as they are. The whole workspace runs with the game's code mods, and the server build (horizon-client --no-default-features) runs when horizon-client is affected. Warm on the Mac mini, a change to hud.rs took 14-16 s against 17 s before, and food.rs 22-32 s against 14 s. Each worktree's first run costs about 3 min once. - tests stay on the touched crates, with the features CI's workspace run gives them: horizon-client's code mods, and horizon-mods' runtime, pack and index. - The Python tests always run, as in CI: some read the crates, the roadmap or the workflows. - The launcher steps run when CI's launcher job would (tools/ci/rust_changes.py's rule, which also covers the root manifests and the check itself). Co-Authored-By: Claude Opus 5.5 --- tests/test_pr_ready.py | 41 +++++++++++++++++++--------- tools/pr_ready.py | 61 +++++++++++++++++++++++++----------------- 2 files changed, 66 insertions(+), 36 deletions(-) diff --git a/tests/test_pr_ready.py b/tests/test_pr_ready.py index 0eab92fb0..87373cb31 100644 --- a/tests/test_pr_ready.py +++ b/tests/test_pr_ready.py @@ -9,7 +9,8 @@ PACKAGES = {"horizon-core": "crates/horizon-core", "horizon-client": "crates/hor "horizon-theme": "crates/horizon-theme", "xtask": "xtask"} LIBRARIES = set(PACKAGES) - {"xtask"} DEPENDENCIES = {"horizon-client": {"horizon-core"}} -MODS = " --features horizon-mods/runtime,horizon-mods/pack,horizon-client/mods" +MODS = " --features horizon-client/mods,horizon-mods/pack" +CLIPPY = pr_ready.CI_CLIPPY + " && " + pr_ready.CI_CLIPPY_SERVER def args(host="local", quick=False): @@ -35,6 +36,9 @@ class PrReadyTests(unittest.TestCase): self.assertFalse(pr_ready.workspace_rust("crates/horizon-client/README.md")) self.assertFalse(pr_ready.workspace_rust("launcher/src/main.rs")) self.assertTrue(pr_ready.launcher_rust("launcher/src/main.rs")) + # CI's launcher job also runs for the root workspace's manifests and for its own check. + self.assertTrue(pr_ready.launcher_rust("Cargo.lock")) + self.assertTrue(pr_ready.launcher_rust("tools/ci/rust_changes.py")) self.assertTrue(pr_ready.launcher_rust("crates/horizon-prepare/src/lib.rs")) self.assertTrue(pr_ready.launcher_rust("crates/horizon-theme/src/lib.rs")) self.assertTrue(pr_ready.launcher_rust("crates/horizon-telemetry/src/lib.rs")) @@ -46,10 +50,9 @@ class PrReadyTests(unittest.TestCase): with mock.patch.object(pr_ready, "affected_here", return_value=[]): steps = pr_ready.plan(args(quick=True), "origin/main", {"crates/horizon-client/src/game.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES) by_name = {step.name: step for step in steps} - self.assertEqual(by_name["clippy"].command, - "cargo clippy -p horizon-client --all-targets --locked -- -D warnings") + self.assertEqual(by_name["clippy"].command, CLIPPY) self.assertEqual(by_name["tests: horizon-client"].command, - "cargo test --locked -p horizon-client --tests") + "cargo test --locked -p horizon-client --features horizon-client/mods --tests") self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p horizon-client --doc") self.assertIsNone(by_name["doc tests"].status) @@ -58,12 +61,24 @@ class PrReadyTests(unittest.TestCase): with self.subTest(path=path), mock.patch.object(pr_ready, "affected_here", return_value=[]): steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES) by_name = {step.name: step for step in steps} - self.assertEqual(by_name["clippy"].command, - "cargo clippy --workspace" + MODS + " --all-targets --locked -- -D warnings") + self.assertEqual(by_name["clippy"].command, CLIPPY) self.assertEqual(by_name["tests: workspace"].command, "cargo test --locked --workspace" + MODS + " --tests") self.assertEqual(by_name["doc tests"].command, "cargo test --locked --workspace --doc") + def test_tests_get_the_features_ci_s_workspace_run_gives_them(self): + self.assertEqual(pr_ready.mod_features(["horizon-world"]), "") + self.assertEqual(pr_ready.mod_features(["horizon-client"]), " --features horizon-client/mods") + self.assertEqual(pr_ready.mod_features(["horizon-mods"]), + " --features horizon-mods/runtime,horizon-mods/pack,horizon-mods/index") + self.assertEqual(pr_ready.mod_features(None), MODS) + + def test_python_tests_always_run(self): + with mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(quick=True), "origin/main", {"crates/horizon-core/src/lib.rs"}, + PACKAGES, LIBRARIES, DEPENDENCIES) + self.assertIsNone({step.name: step for step in steps}["Python tests"].status) + def test_non_rust_changes_skip_workspace_checks(self): for path in ("README.md", "tools/pr_ready.py", "launcher/src/main.rs"): with self.subTest(path=path), mock.patch.object(pr_ready, "affected_here", return_value=[]): @@ -77,7 +92,7 @@ class PrReadyTests(unittest.TestCase): steps = pr_ready.plan(args(), "origin/main", {"crates/horizon-core/src/lib.rs", "crates/horizon-client/examples/probe.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES) for step in steps: - if step.name in ("clippy", "tests: horizon-client, horizon-core", "doc tests"): + if step.name in ("tests: horizon-client, horizon-core", "doc tests"): self.assertIn("-p horizon-client -p horizon-core", step.command) self.assertIsNone(step.status) @@ -94,15 +109,17 @@ class PrReadyTests(unittest.TestCase): by_name = {step.name: step for step in steps} self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p horizon-core --doc") - def test_clippy_checks_transitive_consumers_but_tests_only_touched_crates(self): - packages = {name: f"crates/{name}" for name in ("core", "world", "client", "unrelated")} - dependencies = {"world": {"core"}, "client": {"world"}, "unrelated": set()} + def test_clippy_is_ci_s_and_the_server_build_when_the_game_is_affected(self): + packages = {name: f"crates/{name}" for name in ("core", "world", "horizon-client", "unrelated")} + dependencies = {"world": {"core"}, "horizon-client": {"world"}, "unrelated": set()} with mock.patch.object(pr_ready, "affected_here", return_value=[]): steps = pr_ready.plan(args(), "origin/main", {"crates/core/src/lib.rs"}, packages, set(packages), dependencies) + unrelated = pr_ready.plan(args(), "origin/main", {"crates/unrelated/src/lib.rs"}, + packages, set(packages), dependencies) + self.assertEqual({step.name: step for step in unrelated}["clippy"].command, pr_ready.CI_CLIPPY) by_name = {step.name: step for step in steps} - self.assertEqual(by_name["clippy"].command, - "cargo clippy -p client -p core -p world --all-targets --locked -- -D warnings") + self.assertEqual(by_name["clippy"].command, CLIPPY) self.assertEqual(by_name["tests: core"].command, "cargo test --locked -p core --tests") self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p core --doc") diff --git a/tools/pr_ready.py b/tools/pr_ready.py index 5b1622e2e..89a529192 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -7,12 +7,13 @@ python3 tools/pr_ready.py --quick # without running the vanilla harnesses From the files the branch changes since its merge base with --base (committed or not) it decides what to run: -rustfmt, clippy with warnings denied and the tests of the touched crates; the launcher (its own workspace) the -same way when it, horizon-prepare or horizon-theme changed; crates/horizon-theme/tokens.css against horizon-theme; -Cargo.lock changing only with a Cargo.toml; the Python tests and the public-tree check; and the vanilla -harnesses the changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run -where the vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI. -Clippy checks all targets of touched crates and their transitive workspace dependents, including examples. +rustfmt, and clippy with warnings denied exactly as CI's verify job runs it (the whole workspace with the game's code +mods, plus the server build when horizon-client is affected); the tests of the touched crates, with the features +CI's workspace-wide run gives them; the launcher (its own workspace) the same way when CI's launcher job would run +(tools/ci/rust_changes.py --launcher); crates/horizon-theme/tokens.css against horizon-theme; Cargo.lock changing +only with a Cargo.toml; the Python tests (always, as in CI) and the public-tree check; and the vanilla harnesses the +changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run where the +vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI. Tests select library, binary and integration targets explicitly, followed by doc tests, so unrelated example executables are not built and linked again. @@ -43,6 +44,7 @@ if "PARITY_SHARED" not in os.environ and not (ROOT / ".local" / "minecraft").exi # A fleet worktree without vanilla data still knows each harness's dependencies. os.environ["PARITY_SHARED"] = str(FLEET_SHARED) from tools import parity, release_train # noqa: E402 +from tools.ci import rust_changes # noqa: E402 RBUILD = Path.home() / "fleet" / "rbuild" LINE_LIMIT = 500 @@ -82,9 +84,8 @@ def workspace_rust(path): def launcher_rust(path): - """Whether a change to path is built into the launcher (its own workspace).""" - return not is_doc(path) and any(path.startswith(p) for p in release_train.LAUNCHER_PATHS) and \ - path != "launcher/links.json" and not path.startswith("launcher/docs/") + """Whether a change to path is built into the launcher (its own workspace): CI's launcher job's own rule.""" + return rust_changes.needs_launcher([path]) def touched_crates(paths, packages): @@ -268,14 +269,25 @@ def parity_summary(output): return text +# CI's verify job (.github/workflows/ci.yml): clippy over the whole workspace with the game's code mods, and over the +# server build (the game without sound or controllers); tests with code mods and mod packaging. +CI_CLIPPY = "cargo clippy --workspace --all-targets --locked --features horizon-client/mods -- -D warnings" +CI_CLIPPY_SERVER = "cargo clippy -p horizon-client --all-targets --locked --no-default-features -- -D warnings" +CI_TEST_FEATURES = "horizon-client/mods,horizon-mods/pack" + + def mod_features(crates): - """Code mods are off by default (docs/mods.md): on wherever horizon-mods is checked, as in CI.""" - if crates is not None and "horizon-mods" not in crates: - return "" - features = ["horizon-mods/runtime", "horizon-mods/pack"] - if crates is None or "horizon-client" in crates: + """The features CI's workspace-wide test run gives these crates (code mods are off by default: docs/mods.md). + Cargo unifies features over the packages it builds, so a crate tested alone needs the ones the workspace would + have turned on for it: horizon-client's code mods, and horizon-mods' runtime, packaging and index.""" + if crates is None: + return f" --features {CI_TEST_FEATURES}" + features = [] + if "horizon-mods" in crates: + features += ["horizon-mods/runtime", "horizon-mods/pack", "horizon-mods/index"] + if "horizon-client" in crates: features.append("horizon-client/mods") - return f" --features {','.join(features)}" + return f" --features {','.join(features)}" if features else "" def plan(args, base, changed, crates_of, libraries, dependencies): @@ -283,16 +295,18 @@ def plan(args, base, changed, crates_of, libraries, dependencies): rust = any(workspace_rust(path) for path in changed) launcher = any(launcher_rust(path) for path in changed) # The Python tests also hold ROADMAP.md to roadmap/roadmap.toml (tests/test_roadmap.py). - python = any(path.endswith(".py") or path.startswith(("tests/", "tools/", "roadmap/")) or path == "ROADMAP.md" - for path in changed) crates = touched_crates(changed, crates_of) if rust else [] # An unrecognised Rust path must not silently skip validation. if rust and crates == []: crates = None selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in crates) + # CI's own clippy commands: a crate checked alone gets other features than in CI's workspace-wide run, and an + # unused import behind a feature passed here and failed in CI (#1895). Warm, the workspace run costs about what + # the touched crates and their dependents did (14-32 s against 14-17 s on the Mac mini, 2026-10-26). clippy_crates = dependent_crates(crates, dependencies) - clippy_selection = "--workspace" if clippy_crates is None else " ".join( - f"-p {shlex.quote(c)}" for c in clippy_crates) + clippy = CI_CLIPPY + if clippy_crates is None or "horizon-client" in clippy_crates: + clippy += f" && {CI_CLIPPY_SERVER}" test_skip = None if crates is None or crates else "no crate touched" doc_crates = sorted(libraries if crates is None else libraries.intersection(crates)) doc_selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in doc_crates) @@ -300,11 +314,10 @@ def plan(args, base, changed, crates_of, libraries, dependencies): steps = [ Step("Cargo.lock", where="git"), Step("Public tree", "python3 tools/check_public_tree.py", where="here"), - Step("Python tests", "python3 -m unittest discover -s tests", where="here", - skip=None if python else "no Python change", summary=unittest_passed), + # Always, as in CI: some read the crates, the roadmap or the workflows. + Step("Python tests", "python3 -m unittest discover -s tests", where="here", summary=unittest_passed), Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust), - Step("clippy", f"cargo clippy {clippy_selection}{mod_features(clippy_crates)} --all-targets --locked -- -D warnings", - skip=None if rust else no_rust), + Step("clippy", clippy, skip=None if rust else no_rust), Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""), f"cargo test --locked {selection}{mod_features(crates)} --tests", skip=test_skip, summary=tests_passed), @@ -404,7 +417,7 @@ def run_windows(steps, verbose): elif step.name == "rustfmt": command = ["cargo", "fmt", "--all", "--", "--check"] elif step.name == "clippy": - command = ["cargo", "clippy", "--workspace", "--all-targets", "--locked", "--", "-D", "warnings"] + command = shlex.split(CI_CLIPPY) # the server build's clippy runs in CI (Linux) elif step.name.startswith("tests"): command = shlex.split(step.command) elif step.name == "tokens.css up to date": From 67c27701e97559473e133ffe5bcaee4836c0cdb2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:16:43 +0100 Subject: [PATCH 4/6] Server: new players join around the spawn, not all on one spot The server put every player new to the world exactly on the world spawn. On the server thread the host's own player joins that way too, so the host and each new guest stood inside each other: the guest's client targets the host's player (its eye inside that box, as vanilla's getEntityHitResult does), so it could open no crafting table, chest or furnace, and Entity.push never parts two players with the same centre. A dedicated server stacked its new players the same way. Vanilla places each new player with ServerPlayer.adjustSpawnLocation: PlayerSpawnFinder.findSpawn, a free column at a random offset within the respawn radius. Game::server_player_spawn does it for a server's new players with the window's own finder, passing over the candidates whose chunk isn't loaded yet (vanilla waits for them; a server tick can't). lan_e2e's new check `spawned` asserts that the host and the guest join on different spots, then has the guest open a crafting table, a chest, a furnace and a stonecutter where it joined. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/initial_spawn.rs | 75 +++++++++++++------ crates/horizon-client/src/game/lan.rs | 13 +++- tools/lan_e2e.py | 40 +++++++++- 3 files changed, 103 insertions(+), 25 deletions(-) diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 3f7a071bb..7ddb9cb90 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -126,28 +126,7 @@ impl Game<'_> { pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { let mut finder = match self.player_spawn { Some(finder) => finder, - None if self.level.game_mode == 2 => { - // Adventure mode: the suggestion itself. - let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); - finder.next_candidate(); - finder - } - None => { - let mut radius = self.ui.rules.int("respawn_radius").max(0); - let to_border = self - .border - .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) - .floor() as i32; - if to_border < radius { - radius = to_border; - } - if to_border <= 1 { - radius = 1; - } - PlayerSpawnFinder::new(suggestion, radius, |n| { - entity_random().next_int_bound(n).unwrap_or(0) - }) - } + None => self.spawn_finder(suggestion), }; let found = loop { let Some(candidate) = finder.next_candidate() else { @@ -176,6 +155,58 @@ impl Game<'_> { self.player_spawn = found.is_none().then_some(finder); Ok(found) } + /// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut + /// by the world border; the suggestion itself in adventure mode. + fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder { + if self.level.game_mode == 2 { + let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); + finder.next_candidate(); + return finder; + } + let mut radius = self.ui.rules.int("respawn_radius").max(0); + let to_border = self + .border + .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) + .floor() as i32; + if to_border < radius { + radius = to_border; + } + if to_border <= 1 { + radius = 1; + } + PlayerSpawnFinder::new(suggestion, radius, |n| { + entity_random().next_int_bound(n).unwrap_or(0) + }) + } + /// ServerPlayer.adjustSpawnLocation for a server's new player: where + /// PlayerSpawnFinder.findSpawn puts their feet around the world spawn + /// (`spawn`, the feet there), so that players new to a world don't all + /// stand in one spot. Vanilla waits for each candidate's chunk; a server + /// tick can't, so a candidate in a chunk not loaded yet is passed over, + /// and `spawn` stays when the search never reaches a loaded column. + pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] { + let suggestion = spawn.map(|v| v.floor() as i32); + let mut finder = self.spawn_finder(suggestion); + while let Some(candidate) = finder.next_candidate() { + let (x, z) = match candidate { + SpawnCandidate::Column(x, z) => (x, z), + SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]), + }; + if !self.streaming.is_lit(x >> 4, z >> 4) { + continue; + } + let feet = match candidate { + SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z) + .filter(|&pos| self.player_fits(pos)) + .map(bottom_center), + SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)), + }; + if let Some(feet) = feet { + return [feet.x, feet.y, feet.z]; + } + } + spawn + } /// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the /// block's bottom centre touches no block or liquid. fn player_fits(&self, pos: [i32; 3]) -> bool { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..ce65c52bc 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1128,8 +1128,17 @@ impl Game<'_> { g.game_mode = default_mode; } if !known { - g.position = spawn; - g.previous_position = spawn; + // ServerPlayer.adjustSpawnLocation: a player new to the world + // stands where PlayerSpawnFinder puts them, not all on one spot + // (it reads the loaded level, which holds the spawn when it is + // the overworld). + let feet = if self.dim == super::Dim::Overworld { + self.server_player_spawn(spawn) + } else { + spawn + }; + g.position = feet; + g.previous_position = feet; g.health = 20.0; g.food = 20; g.dimension = super::Dim::Overworld.id().to_owned(); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index ab3fcde1b..012e8f021 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -14,6 +14,8 @@ address. The script then checks, from both sides, what a guest's game used to ge closes on both when the guest closes it; the host keeps playing with its mouse look (#687); - crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table, which leaves the host's screen and mouse look alone; +- spawned: the host and a guest new to the world join on different spots (PlayerSpawnFinder), and the + guest opens a crafting table, a chest, a furnace and a stonecutter where it joined; - sign: a sign the guest places doesn't open a sign editor on the host; - damage: a guest in survival takes fall damage; - mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them; @@ -292,7 +294,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # Match normal single player; --in-frame is the comparison path. SERVER_THREAD = True -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'spawned', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', @@ -554,6 +556,39 @@ def check_crafting(host, guest, out): return {'planks': planks, 'table': counts} +def check_spawned(host, guest, out): + """Players new to a world don't share one spot: ServerPlayer.adjustSpawnLocation spreads them over the + respawn radius (PlayerSpawnFinder). Two players standing in each other target each other, so a guest + left in the host could open nothing it clicked. At its own spot, the guest opens a crafting table, a + chest, a furnace and a stonecutter.""" + joined = {'host': [round(v, 2) for v in host.joined_at], 'guest': [round(v, 2) for v in guest.joined_at]} + apart = abs(joined['host'][0] - joined['guest'][0]) + abs(joined['host'][2] - joined['guest'][2]) >= 0.6 + guest('command', command='gamemode survival') + for game in (host, guest): + x, y, z = game.joined_at + game('command', command=f'tp @s {x} {y} {z}') + guest.wait(20) + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + grab(host) + opened = {} + for block in ('crafting_table', 'chest', 'furnace', 'stonecutter'): + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}') + guest.wait(10) + guest.raw('interact', *at) + guest.wait(10) + opened[block] = guest('state').get('screen') + guest.shot(out, f'spawned-{block}') + back_to_game(guest) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + host_unaffected(host, "the guest's stations") + face_each_other(host, guest) + assert apart, f'the host and the guest joined on one spot: {joined}' + want = {'crafting_table': 'inventory', 'chest': 'container', 'furnace': 'container', 'stonecutter': 'station'} + assert opened == want, f'where it joined, the guest opened {opened}' + return {'joined': joined, 'opened': opened} + + def check_sign(host, guest, out): x, y, z = (int(v // 1) for v in pos_of(guest)) spot = (x + 2, y, z) @@ -4669,6 +4704,7 @@ def check_worn(host, guest, out): CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, + 'spawned': check_spawned, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn, 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, @@ -4727,6 +4763,8 @@ def run(ctl, out, resources, checks): guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) guest.raw('wait-for', 'loaded', '--timeout', 300) guest.wait(40) + # Where each joined, before anything moves them (check_spawned). + host.joined_at, guest.joined_at = pos_of(host), pos_of(guest) face_each_other(host, guest) host.shot(out, 'joined') guest.shot(out, 'joined') From 4afd517c2213fad4476e0b3442d16893a720f4f1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:22:46 +0100 Subject: [PATCH 5/6] tools/remote.sh: run a command on playhorizon at a worktree's commit The host fetches the commit from GitHub (nothing else is sent), keeps one checkout and target per worktree, runs the command niced in its CI slice on CPUs 4-7 with scratch homes, prepares vanilla data for harness commands as CI does, and streams the output back. One run per name at a time; no lock leaks into daemons the run starts. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 11 +++++ tools/remote.sh | 104 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100755 tools/remote.sh diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index c0cf3aec5..7419eef26 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -44,6 +44,17 @@ Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/pari Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. +### Any command on playhorizon: `tools/remote.sh` + +For Linux work that doesn't need a whole parity run (a crate's tests, a few harnesses, a server build), `tools/remote.sh ` runs the command on playhorizon at the worktree's commit and streams its output back; its exit status is the command's. Commit and push first: the host fetches the commit from GitHub, and nothing else leaves this machine (no files, no credentials, no environment). Each worktree keeps one checkout there, `~/remote-work/` with its own `target/`, so the next run only rebuilds what changed, and one run per name goes at a time. The command runs niced in the host's CI slice, pinned to CPUs 4-7 (`--cpus`; 0-3 stay free for benchmarks), with scratch game and launcher homes and the vanilla data linked as CI links it; a command naming `parity`, `lan_e2e` or `horizon-prepare` also gets `.local/horizon-client`, prepared as CI prepares it. Logs stay in `~/remote-work/.logs/`; `--list` shows the checkouts, `--gc [DAYS]` removes old ones. + +```sh +tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib # 33 s, warm +tools/remote.sh . python3 tools/parity.py food # 19 s warm (4 min the first time); here: 188 s, 229 CPU-seconds +``` + +The host is lent by a partner who keeps hypervisor access: send it no secret, token or credential, and never take a result from it as a CI result. + ### Shards and Rust scopes A harness can declare, at the top level of its script: diff --git a/tools/remote.sh b/tools/remote.sh new file mode 100755 index 000000000..1df21c560 --- /dev/null +++ b/tools/remote.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Run a command on a Linux build host (default playhorizon) at a worktree's commit, and get its output back. +# +# tools/remote.sh [--host H] [--name N] [--cpus LIST] [--jobs J] +# tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib +# tools/remote.sh . python3 tools/parity.py food light +# tools/remote.sh --list # checkouts on the host, their size and last use +# tools/remote.sh --gc [DAYS] # remove checkouts unused for DAYS (default 2) +# +# The host fetches the commit from GitHub itself: commit and push first (uncommitted changes are not sent, and +# nothing else leaves this machine: no files, no credentials, no environment). Each name (default: the worktree's +# folder) keeps one checkout there, ~/remote-work/, with its own target/: the next run checks out the new +# commit over it, so only what changed rebuilds (sccache shares the registry crates between names). One run per +# name at a time. The command runs in bash at the checkout's root, niced in the host's CI slice, with the host's +# toolchains, a virtual screen and scratch homes for the game and launcher. .local/ links to the host's vanilla +# data; a command that runs harnesses (it names parity, lan_e2e or horizon-prepare) also gets .local/horizon-client, +# prepared as CI prepares it (tools/ci/vanilla-data.sh). Output streams back and is kept in ~/remote-work/.logs/. +# The exit status is the command's. +# +# The host is lent by a partner who keeps hypervisor access: never send secrets, tokens or credentials there, +# and never treat a result from it as a CI result. +set -euo pipefail + +# CPUs 0-3 stay free for benchmarks (perf-world-entry measures on playhorizon pinned to them); --cpus all for every one. +host=playhorizon name="" jobs="" cpus=4-7 +usage() { sed -n '2,8s/^# \{0,1\}//p' "$0" >&2; exit 2; } +while [ $# -gt 0 ]; do + case $1 in + --host) host=$2; shift 2;; + --name) name=$2; shift 2;; + --jobs) jobs=$2; shift 2;; + --cpus) cpus=$2; shift 2;; + --list) exec ssh "ludovic@$host" 'cd ~/remote-work 2>/dev/null && for d in */; do d=${d%/}; + printf "%-32s %8s last used %s\n" "$d" "$(du -sh "$d" 2>/dev/null | cut -f1)" "$(stat -c %y "$d.logs" 2>/dev/null | cut -c1-16)"; done';; + --gc) days=${2:-2}; exec ssh "ludovic@$host" "cd ~/remote-work 2>/dev/null || exit 0 + find . -maxdepth 1 -name '*.logs' -mtime +$days | while read -r logs; do d=\${logs%.logs}; + flock -n \"\$d.lock\" rm -rf \"\$d\" \"\$logs\" \"\$d.lock\" && echo \"removed \${d#./}\"; done";; + -h|--help) usage;; + *) break;; + esac +done +[ $# -ge 2 ] || usage +tree=$(cd "$1" && git rev-parse --show-toplevel); shift +sha=$(git -C "$tree" rev-parse HEAD) +name=${name:-$(basename "$tree")} +[[ $name =~ ^[A-Za-z0-9._-]+$ ]] || { echo "remote.sh: name '$name' must be letters, digits, . _ -" >&2; exit 2; } +if ! git -C "$tree" diff --quiet HEAD -- 2>/dev/null; then + echo "remote.sh: uncommitted changes in $tree are not sent: the host runs ${sha:0:9}" >&2 +fi +if [ -z "$(git -C "$tree" branch -r --contains "$sha" 2>/dev/null)" ]; then + git -C "$tree" fetch -q origin 2>/dev/null || true + [ -n "$(git -C "$tree" branch -r --contains "$sha" 2>/dev/null)" ] || + { echo "remote.sh: ${sha:0:9} is not on GitHub yet: push it first (the host fetches from GitHub)" >&2; exit 2; } +fi +command=$(printf '%q ' "$@") + +# The host side reads its script and these four values on stdin (nothing is re-split by a remote shell); its +# own environment comes from the runner's files there. +{ +printf 'name=%q sha=%q jobs=%q cpus=%q command=%q\n' "$name" "$sha" "$jobs" "$cpus" "$command" +cat <<'REMOTE' +set -euo pipefail +if [ "$cpus" = all ]; then pin=(); jobs=${jobs:-$(nproc)}; else pin=(taskset -c "$cpus"); jobs=${jobs:-$(taskset -c "$cpus" nproc)}; fi +runner=~/.actions-runners/horizon +if [ -e "$runner/paused" ]; then echo "remote.sh: this host is paused ($runner/paused)" >&2; exit 75; fi +set -a; . "$runner/.env"; set +a +export PATH="$(cat "$runner/.path")" DISPLAY=":$(cat "$runner/display")" RUSTC_WRAPPER="$(command -v sccache || true)" +export CARGO_BUILD_JOBS=$jobs FLEET_LOAD_JOBS=$jobs PARITY_LOCAL_JOBS=$(( jobs > 1 ? jobs / 2 : 1 )) +unset WAYLAND_DISPLAY +mkdir -p ~/remote-work && cd ~/remote-work +exec 9> "$name.lock" +flock -n 9 || { echo "remote.sh: $name is busy with another run" >&2; exit 75; } +if [ ! -d "$name/.git" ]; then + git clone -q --filter=blob:none --no-checkout https://github.com/ludovic111/horizon "$name" 9>&- +fi +cd "$name" +# The lock's descriptor stays out of everything started here (9>&-): a daemon one of them starts (sccache's server, +# from the preparer's build or the command's) would hold the lock after the run. +git fetch -q --no-tags origin "$sha" 9>&- +git checkout -q --force --detach "$sha" +git clean -qfd -e /target -e /.local +# The host's vanilla data, linked as CI's runner links it; for harnesses also .local/horizon-client, prepared by +# this commit's own preparer (once per preparer version, kept beside the data and shared by every name). +if [[ $command =~ parity|lan_e2e|horizon-prepare ]]; then + RUNNER_WORKSPACE=$(dirname "$HORIZON_SHARED_SOURCE") RUNNER_TEMP=$(mktemp -d) bash tools/ci/vanilla-data.sh >&2 9>&- +else + mkdir -p .local + for d in minecraft tools datagen; do + if [ -e "$HORIZON_SHARED_SOURCE/$d" ]; then ln -sfn "$HORIZON_SHARED_SOURCE/$d" ".local/$d"; fi + done +fi +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +export HORIZON_HOME=$scratch/game HORIZON_LAUNCHER_HOME=$scratch/launcher XDG_DATA_HOME=$scratch/data \ + XDG_CONFIG_HOME=$scratch/config HORIZON_NO_AUDIO=1 HORIZON_LAUNCHER_NO_SELF_UPDATE=1 HORIZON_TELEMETRY_URL=off +mkdir -p "$HORIZON_HOME" "$HORIZON_LAUNCHER_HOME" "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" ../"$name.logs" +log=../"$name.logs/$(date -u +%Y%m%dT%H%M%SZ)-${sha:0:9}.log" +echo "remote.sh: $(hostname) at ${sha:0:9} in ~/remote-work/$name, CPUs $cpus, -j $jobs; log ~/remote-work/${log#../}" >&2 +status=0 +systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit="remote-$name-$$" \ + "${pin[@]}" nice -n 10 bash -c "$command" 2>&1 < /dev/null 9>&- | tee "$log" || status=${PIPESTATUS[0]} +exit "$status" +REMOTE +} | ssh -o BatchMode=yes "ludovic@$host" bash -s From 331e3a7202a9f8c667ce46e3d53cba966a55b964 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:49:24 +0100 Subject: [PATCH 6/6] dedicated_server: steps wait for the server's reply, not a 1.5 s timer The parity client's chat, villager and furnace steps went on 1.5 s after sending, so a busy server's late reply landed in the next step (or a click carried a stale state id). Each step now waits until the server answered: its chat line, both slot packets of a shift-click, and the furnace totals the click changes (up to the same 30 s patience). The respawn window keeps only the player's own entity packets: a squid's swim event or a mob coming into view falls into it as each server's ticks fall. Off the known-flaky list: it passes under 2.5 s server stalls every 5 s, where main's client fails. Co-Authored-By: Claude Opus 5.5 --- .../parity/VanillaProtocolClient.java | 64 +++++++++++++++++-- tools/parity_hosts.json | 1 - 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index e37e898a3..fbb8ed2b0 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -487,6 +487,17 @@ public final class VanillaProtocolClient { long deadCommandAt = 0; // When the client last sent where it is. long positionAt = 0; + // Chat lines and furnace slot changes received, and how many there were when the current step sent + // its command or click: a step goes on once the server answered, not after a fixed time (a busy + // server answers seconds late, and a click sent before the last one's reply carries a stale state id). + int replies = 0; + int repliesBefore = 0; + // A shift-click changes two slots, each its own packet, which a busy server can send ticks apart: a furnace + // step waits for both. A full resend of the menu counts as both. + int furnaceReplies = 0; + int furnaceBefore = 0; + // The furnace's lit and cooking totals received: the server sends them a tick after what changed them. + int furnaceData = 0; while (System.currentTimeMillis() < deadline) { Received r; try { @@ -501,7 +512,7 @@ public final class VanillaProtocolClient { if (entities != null && !entities.acceptSelf(packet) && step >= ENTITIES) entities.accept(packet); if (r.type.equals("minecraft:chunk_batch_start")) ordered = false; if (respawning && !respawned) { - String line = respawnLine(r); + String line = respawnLine(r, playerId); // PlayerList.respawn ends with initInventoryMenu: what follows is the // next ticks' (health, entity data, chunks), in each server's own order. respawned = r.type.equals("minecraft:container_set_content") && respawnAt != null; @@ -558,15 +569,18 @@ public final class VanillaProtocolClient { } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket p && furnaceWindow > 0 && p.containerId() == furnaceWindow) { furnaceState = p.stateId(); + furnaceReplies += 2; record("play-furnace", "content " + p.items() + " carried " + p.carriedItem()); } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket p && furnaceWindow > 0 && p.getContainerId() == furnaceWindow) { furnaceState = p.getStateId(); + furnaceReplies++; record("play-furnace", "slot " + p.getSlot() + " " + p.getItem()); if (p.getSlot() == 2 && !p.getItem().isEmpty() && smeltedAt == 0) smeltedAt = now; } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket p && furnaceWindow > 0 && p.getContainerId() == furnaceWindow && (p.getId() == 1 || p.getId() == 3)) { // Lit total and cooking total; the time left and the cooking timer follow the ticks. + furnaceData++; record("play-furnace", "data " + p.getId() + " " + p.getValue()); } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p && step == 5 + REPLIES.length && (int) (byte) field(p, "eventId") == 28) { @@ -583,13 +597,16 @@ public final class VanillaProtocolClient { record("play-death", "command reply " + json(p.content())); respawning = respawn(); } else if (packet instanceof ClientboundSystemChatPacket p && step > 0 && step < 5 + REPLIES.length) { + replies++; record("play-chat", "system " + p.overlay() + " " + json(p.content())); } else if (packet instanceof ClientboundPlayerChatPacket p && step > 0 && step < 5 + REPLIES.length) { + replies++; record("play-chat", "player " + p.sender() + " " + p.index() + " " + p.body().content() + " " + p.signature().isPresent() + " " + p.unsignedContent().map(VanillaProtocolClient::json) + " " + text(p.filterMask()) + " " + p.chatType().chatType().getRegisteredName() + " " + json(p.chatType().name()) + " " + p.chatType().targetName().map(VanillaProtocolClient::json)); } else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0 && step < 5 + REPLIES.length) { + replies++; record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName()); } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p && p.getType() == net.minecraft.world.entity.EntityTypes.SNOWBALL) { @@ -679,20 +696,24 @@ public final class VanillaProtocolClient { record("play-light-layers", inner.size() + " " + inner); step = 1; stepAt = now; + repliesBefore = replies; send(new ServerboundChatPacket("hello from the parity client", Instant.now(), 0L, Optional.empty(), new LastSeenMessages.Update(0, new BitSet(), (byte) 0))); - } else if (step == 1 && now - stepAt > 1500) { + } else if (step == 1 && answered(replies, repliesBefore, stepAt, now)) { step = 2; stepAt = now; + repliesBefore = replies; send(new ServerboundChatCommandPacket("list")); - } else if (step >= 2 && step < 2 + REPLIES.length && now - stepAt > 1500) { + } else if (step >= 2 && step < 2 + REPLIES.length && answered(replies, repliesBefore, stepAt, now)) { // Commands a player without operator rights may run, whose // replies (a failure, a syntax error with its context, a // failure with an argument) are compared component by component. send(new ServerboundChatCommandPacket(REPLIES[step - 2])); step++; stepAt = now; - } else if (step == 2 + REPLIES.length && now - stepAt > 1500 && (villager >= 0 || now - stepAt > PATIENCE)) { + repliesBefore = replies; + } else if (step == 2 + REPLIES.length && answered(replies, repliesBefore, stepAt, now) + && (villager >= 0 || now - stepAt > PATIENCE)) { // Right-click the villager (once the server sent it): the trading screen and its offers. record("play-trade", "villager " + (villager >= 0)); if (villager >= 0) { @@ -739,9 +760,13 @@ public final class VanillaProtocolClient { send(new net.minecraft.network.protocol.game.ServerboundUseItemOnPacket(net.minecraft.world.InteractionHand.MAIN_HAND, new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(furnace), net.minecraft.core.Direction.NORTH, furnace, false), 1)); + furnaceBefore = furnaceReplies; step++; stepAt = now; - } else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0 && now - stepAt > 1500 + } else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0 + && answered(furnaceReplies, furnaceBefore + 1, stepAt, now) + // Both totals with the window, then the cooking total the ore set, then the lit total the coal set. + && (furnaceData >= step - 6 - REPLIES.length || now - stepAt > PATIENCE) // The ingot out once the furnace made it (200 ticks), and its tick's other changes came. && (step < 10 + REPLIES.length || smeltedAt > 0 && now - smeltedAt > 1000 || now - stepAt > 10_000 + PATIENCE)) { // Shift-click the ore (hotbar 0) into the input, the coal (hotbar 1) into the @@ -752,9 +777,10 @@ public final class VanillaProtocolClient { send(new net.minecraft.network.protocol.game.ServerboundContainerClickPacket(furnaceWindow, furnaceState, (short) slot, (byte) 0, net.minecraft.world.inventory.ContainerInput.QUICK_MOVE, new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(), net.minecraft.network.HashedStack.EMPTY)); + furnaceBefore = furnaceReplies; step++; stepAt = now; - } else if (step == 11 + REPLIES.length && now - stepAt > 1500) { + } else if (step == 11 + REPLIES.length && answered(furnaceReplies, furnaceBefore + 1, stepAt, now)) { send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(furnaceWindow)); record("play-furnace", "closed"); step++; @@ -816,6 +842,11 @@ public final class VanillaProtocolClient { record("error", "timed out in play, step " + step + ", chunks " + chunks.size()); } + /** The server answered the step's command or click (at least 1.5 s after it, as before), or had all the time. */ + private static boolean answered(int count, int before, long sent, long now) { + return now - sent > 1500 && (count > before || now - sent > PATIENCE); + } + /** * A right click's snowballs are counted: once the first came and a second could have come with it * (the server spawns each in the tick it handles the click), or once the server had all the time. @@ -857,8 +888,12 @@ public final class VanillaProtocolClient { * packets (time, keep-alive, chunk data and light, whose batching follows each server's * timing) left out; null to skip it. */ - private String respawnLine(Received r) { + private String respawnLine(Received r, int playerId) { String t = r.type; + // Other entities (a squid's swim event, a mob coming into view) land in the window as each server's + // ticks fall: only the player's own are PlayerList.respawn's. + Integer entity = entityOf(r.packet); + if (entity != null && entity != playerId) return null; // Entities moving, blocks the world's ticks change (a lava fall flows again once the game // runs) and the dead player's health land in the window between the death and the respawn // as each server's ticks fall: left out. @@ -891,6 +926,21 @@ public final class VanillaProtocolClient { return t; } + /** The entity a packet is about, for the packets that name one; null for the rest. */ + private static Integer entityOf(Packet packet) { + if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p) return p.getId(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket p) return p.getEntityId(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p) return (int) field(p, "entityId"); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket p) return p.getEntity(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundAnimatePacket p) return p.getId(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundHurtAnimationPacket p) return p.id(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundDamageEventPacket p) return p.entityId(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket p) return p.getEntityId(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket p) return p.entityId(); + if (packet instanceof net.minecraft.network.protocol.game.ClientboundSoundEntityPacket p) return p.getId(); + return null; + } + /** * A chunk's blocks, biomes, heightmaps and block entities (its * ClientboundLevelChunkPacketData bytes). The light is left out: both servers relight around chunks diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 42b9a46fd..29027f87f 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -44,7 +44,6 @@ "lan_integration": "the whole lan_e2e suite: ~40 min a run on a loaded runner, and single checks flake under load; run it by name, or tools/lan_e2e.py" }, "known_flaky": { - "dedicated_server": "its Java client moves to the next step on a 1.5 s timer, not on the server's reply: under load a respawn's add_entity/update_attributes or entity_event 19 lands in the wrong step (failed, then passed at the same head, 10-26)", "remote_fireball": "samples the fireball on the wall clock, so a slow host sees it in too few samples (desktop runner, 3 times on 10-26)", "world_reopen": "counted 4 minecarts instead of 3 once on a loaded Mac mini runner, then passed at the same head (10-26)" }