From 35a89eaebe28921c12c9b5a05072d3b3f31ab00a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:48:38 +0100 Subject: [PATCH 001/132] Mod API 0.3: capability world for server mods (blocks, biomes) Server mods get interface world: get-block(dimension, x, y, z) reads a loaded chunk's block state as "minecraft:oak_log[axis=y]", get-biome its biome ("minecraft:plains"), and set-blocks(dimension, changes) sets up to 4096 blocks per call, checked at once, made as /setblock makes them (place_state: neighbours, light, block entities, every client told through the block log) after the call, before that dimension's next tick. Reads cost no copy: for a mod call the game lends Mods the levels' chunk maps (moved out with mem::take and put back after), only while a running mod has world. Writes for a level that isn't ticking (another dimension, in-frame) wait for it, up to 65,536. Test scripts get blocks (setup) and expect.blocks; cargo horizon-mod check reports a trial run's block writes. Example beacons: /beacon builds a glowstone pillar beside the player, /ground reads the block underfoot and the biome. parse_state is now a free function so the mod path shares it. Docs: docs/mods.md (the capability, script keys), docs/api/mods.md and the regenerated reference. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 7 + Cargo.toml | 2 +- crates/cargo-horizon-mod/src/check.rs | 5 + crates/horizon-client/src/game/levels.rs | 15 ++ crates/horizon-client/src/game/mods.rs | 15 +- .../horizon-client/src/game/render_control.rs | 61 ++++--- crates/horizon-client/src/game/server_mods.rs | 154 +++++++++++++++++- .../examples/beacons/Cargo.toml | 16 ++ .../examples/beacons/horizon-mod.toml | 8 + .../examples/beacons/src/lib.rs | 87 ++++++++++ .../examples/beacons/tests/beacons.toml | 22 +++ crates/horizon-mod-sdk/src/lib.rs | 1 + crates/horizon-mod-sdk/wit/horizon.wit | 28 ++++ crates/horizon-mods/src/manifest.rs | 14 +- crates/horizon-mods/src/runtime.rs | 98 ++++++++++- crates/horizon-mods/src/testing.rs | 92 ++++++++++- crates/horizon-mods/tests/sandbox.rs | 29 +++- docs/api/mods-reference.md | 24 ++- docs/api/mods.md | 12 +- docs/mods.md | 18 +- 20 files changed, 658 insertions(+), 50 deletions(-) create mode 100644 crates/horizon-mod-sdk/examples/beacons/Cargo.toml create mode 100644 crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml create mode 100644 crates/horizon-mod-sdk/examples/beacons/src/lib.rs create mode 100644 crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml diff --git a/Cargo.lock b/Cargo.lock index 0b8adf3ea..8c74b3b46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -205,6 +205,13 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "beacons" +version = "0.1.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "bit-set" version = "0.10.0" diff --git a/Cargo.toml b/Cargo.toml index 44ed89122..ffe744e65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/welcome", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/welcome", "crates/horizon-mod-sdk/examples/beacons", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 86ce9654d..4d271e2c1 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -242,6 +242,11 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), + Output::SetBlocks { + dimension, blocks, .. + } => { + format!("set {} block(s) in {dimension}", blocks.len()) + } }); } match failed(&mods) { diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index f685200f2..09d5c0bff 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -106,6 +106,19 @@ pub(super) struct Levels { parked: HashMap, } +impl Levels { + /// The chunks of each level not in place (capability `world` lends + /// them to server mods for a call). + #[cfg_attr(not(feature = "mods"), allow(dead_code))] + pub(super) fn parked_chunks( + &mut self, + ) -> impl Iterator { + self.parked + .iter_mut() + .map(|(d, p)| (*d, &mut p.world.chunks)) + } +} + impl Game<'_> { /// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`). fn open_level(&self, dim: Dim) -> Result { @@ -295,6 +308,8 @@ impl Game<'_> { }; self.update_dedicated_streaming(); self.update_world(); + // What server mods set in this level since its last tick. + self.apply_mod_block_writes(); result = if paused { self.tick_lan(true); Ok(()) diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index b1ce4207c..111b797ad 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -49,6 +49,14 @@ pub(super) struct ModsState { /// What players did this tick, for server mods at its end. #[cfg(feature = "mods")] pub(super) events: Vec, + /// A running server mod has capability `world`: its calls get the + /// levels' chunks to read. + #[cfg(feature = "mods")] + pub(super) world: bool, + /// Blocks server mods set, by dimension, made before that level's next + /// tick. + #[cfg(feature = "mods")] + pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. @@ -213,6 +221,7 @@ impl Game<'_> { /// The Mods page's rows, from what loaded. fn list_mods(&mut self) { self.mods.server = self.mods.mods.runs_server(); + self.mods.world = self.mods.mods.wants_world(); let dev = &self.mods.dev; self.settings.mods.installed = self .mods @@ -399,8 +408,10 @@ impl Game<'_> { } Text::literal(line).with_color(text::RED) } - server - @ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => { + server @ (Output::Tell { .. } + | Output::Broadcast { .. } + | Output::Reply { .. } + | Output::SetBlocks { .. }) => { self.route_server_output(host.as_deref_mut(), server); continue; } diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index 0a2f9b715..7c5ff4b2d 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[ impl Game<'_> { /// Parse `name[k=v,...]` into a registry state (defaults for missing properties). fn parse_state(&self, text: &str) -> Result { - let (name, props) = match text.split_once('[') { - Some((n, rest)) => (n, rest.trim_end_matches(']')), - None => (text, ""), - }; - let name = if name.contains(':') { - name.to_owned() - } else { - format!("minecraft:{name}") - }; - let registry = &self.pack.assets.registry; - let default = registry - .default_state(&name) - .ok_or_else(|| format!("unknown block {name}"))?; - let mut state = registry - .state(default) - .ok_or("missing default state")? - .clone(); - for pair in props.split(',').filter(|p| !p.is_empty()) { - let (k, v) = pair - .split_once('=') - .ok_or_else(|| format!("bad property {pair}"))?; - if !state.properties.contains_key(k) { - return Err(format!("{name} has no property {k}").into()); - } - state.properties.insert(k.to_owned(), v.to_owned()); - } - Ok(registry.resolve(&state)?) + parse_state(self.pack.assets.registry, text) } pub(super) fn render_command(&mut self, words: &[&str]) -> Result> { let int = |i: usize| -> Result { @@ -137,3 +111,36 @@ impl Game<'_> { } } } + +/// Parse `name[k=v,...]` into a registry state (defaults for missing properties). +pub(super) fn parse_state( + registry: &horizon_world::registry::BlockRegistry, + text: &str, +) -> Result { + let (name, props) = match text.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let default = registry + .default_state(&name) + .ok_or_else(|| format!("unknown block {name}"))?; + let mut state = registry + .state(default) + .ok_or("missing default state")? + .clone(); + for pair in props.split(',').filter(|p| !p.is_empty()) { + let (k, v) = pair + .split_once('=') + .ok_or_else(|| format!("bad property {pair}"))?; + if !state.properties.contains_key(k) { + return Err(format!("{name} has no property {k}").into()); + } + state.properties.insert(k.to_owned(), v.to_owned()); + } + Ok(registry.resolve(&state)?) +} diff --git a/crates/horizon-client/src/game/server_mods.rs b/crates/horizon-client/src/game/server_mods.rs index db88639eb..f5ee5cdc2 100644 --- a/crates/horizon-client/src/game/server_mods.rs +++ b/crates/horizon-client/src/game/server_mods.rs @@ -47,19 +47,72 @@ impl Game<'_> { ) -> bool { false } + pub(super) fn apply_mod_block_writes(&mut self) {} } #[cfg(feature = "mods")] mod run { use super::{Game, LanHost, ModEvent, Who}; + use horizon_client::chunk_map::ChunkMap; use horizon_client::{ command::args::GameMode as Mode, lan::data::component_nbt, text::{self, Text}, }; - use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer}; + use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView}; use horizon_protocol::packets::play::{self, Clientbound as C}; - use horizon_world::registry::BlockStateId; + use horizon_world::registry::{BlockRegistry, BlockStateId}; + + /// Blocks queued for levels that don't tick (another dimension, in-frame) + /// are kept up to this many; the oldest go first. + const MAX_QUEUED_WRITES: usize = 1 << 16; + + /// Capability `world`'s view during a call: the levels' chunks, moved out + /// of the game for the call and back after it (no copy). + struct LentWorld { + registry: &'static BlockRegistry, + biomes: std::sync::Arc, + dims: Vec<(&'static str, ChunkMap)>, + } + impl WorldView for LentWorld { + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?; + let chunk = chunks.get(&(x >> 4, z >> 4))?; + Some(state_string(self.registry, chunk.block(x & 15, y, z & 15))) + } + fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?; + let chunk = chunks.get(&(x >> 4, z >> 4))?; + Some(self.biomes.get(chunk.biome(x, y, z)).name.clone()) + } + fn has_dimension(&self, dimension: &str) -> bool { + matches!( + dimension, + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) + } + fn check_state(&self, state: &str) -> Result<(), String> { + crate::game::render_control::parse_state(self.registry, state) + .map(drop) + .map_err(|e| format!("{state}: {e}")) + } + } + + /// `minecraft:oak_log[axis=y]`. + fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String { + let Some(s) = registry.state(state) else { + return "minecraft:air".into(); + }; + if s.properties.is_empty() { + return s.name.clone(); + } + let props: Vec = s + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}[{}]", s.name, props.join(",")) + } /// `UUID.toString()`. fn uuid_string(u: u128) -> String { @@ -144,6 +197,7 @@ mod run { let players = self.server_players(None); let snapshot = self.mod_snapshot_with(players.clone()); self.mods.mods.set_snapshot(snapshot); + self.lend_world(); let before = std::mem::take(&mut self.mods.players); for p in before .iter() @@ -197,8 +251,80 @@ mod run { } } self.mods.mods.server_tick(self.ticks); + self.return_world(); self.mods.players = players; self.show_mod_output(); + self.apply_mod_block_writes(); + } + + /// Lends the levels' chunks to capability `world` for the calls up to + /// [`Game::return_world`], when a running server mod has it. + fn lend_world(&mut self) { + if !self.mods.world { + return; + } + let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))]; + for (dim, chunks) in self.levels.parked_chunks() { + dims.push((dim.id(), std::mem::take(chunks))); + } + let registry = self.pack.assets.registry; + let biomes = self.res.biomes().clone(); + self.mods.mods.lend_world(Box::new(LentWorld { + registry, + biomes, + dims, + })); + } + + /// Puts back the chunks [`Game::lend_world`] lent. + fn return_world(&mut self) { + let Some(view) = self.mods.mods.take_world() else { + return; + }; + let view: Box = view; + let Ok(lent) = view.downcast::() else { + return; + }; + let mut dims = lent.dims; + if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) { + self.world.chunks = dims.swap_remove(i).1; + } + for (dim, chunks) in self.levels.parked_chunks() { + if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) { + *chunks = dims.swap_remove(i).1; + } + } + } + + /// Makes the blocks server mods set in the level in place, in order, + /// as `/setblock` does. Those of other dimensions wait for their level. + pub(in crate::game) fn apply_mod_block_writes(&mut self) { + if self.mods.block_writes.is_empty() { + return; + } + let dim = self.dim.id(); + let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes) + .into_iter() + .partition(|(d, _)| d == dim); + self.mods.block_writes = later; + let registry = self.pack.assets.registry; + for (_, b) in now { + let state = match crate::game::render_control::parse_state(registry, &b.state) { + Ok(state) => state, + Err(e) => { + log::warn!("Horizon: a server mod set {}: {e}", b.state); + continue; + } + }; + if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) { + log::debug!( + "Horizon: a server mod's block at {} {} {}: {e:?}", + b.x, + b.y, + b.z + ); + } + } } /// A player broke (or placed) `state` at `pos`: the player acting now. @@ -240,8 +366,11 @@ mod run { }; let snapshot = self.mod_snapshot_with(players); self.mods.mods.set_snapshot(snapshot); + self.lend_world(); let owned = self.mods.mods.server_command(&me, line); + self.return_world(); self.show_mod_output(); + self.apply_mod_block_writes(); owned } @@ -266,10 +395,14 @@ mod run { }; let snapshot = self.mod_snapshot_with(players); self.mods.mods.set_snapshot(snapshot); - if !self.mods.mods.server_command(&me, line) { + self.lend_world(); + let owned = self.mods.mods.server_command(&me, line); + self.return_world(); + if !owned { return false; } self.route_mod_output(Some(host)); + self.apply_mod_block_writes(); true } @@ -349,6 +482,21 @@ mod run { self.tell_server_player(host.as_deref_mut(), &p.id, line); } } + Output::SetBlocks { + name, + dimension, + blocks, + } => { + let queued = &mut self.mods.block_writes; + queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b))); + if queued.len() > MAX_QUEUED_WRITES { + let over = queued.len() - MAX_QUEUED_WRITES; + queued.drain(..over); + log::warn!( + "Horizon: mod {name} set more blocks than wait for their level: {over} dropped" + ); + } + } _ => {} } } diff --git a/crates/horizon-mod-sdk/examples/beacons/Cargo.toml b/crates/horizon-mod-sdk/examples/beacons/Cargo.toml new file mode 100644 index 000000000..c001614e8 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "beacons" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../.." } + +[lints] +workspace = true diff --git a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml new file mode 100644 index 000000000..0c2004b5f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml @@ -0,0 +1,8 @@ +id = "beacons" +name = "Beacons" +version = "0.1.0" +description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome." +authors = ["Horizon"] +api = "0.3" +side = "server" +capabilities = ["players", "world"] diff --git a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs new file mode 100644 index 000000000..509431775 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs @@ -0,0 +1,87 @@ +//! Example Horizon server mod (`docs/mods.md`, "Server mods") with +//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east +//! of the player, `/ground` reads the block under their feet and the biome. +use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world}; + +/// How tall `/beacon` builds. +const HEIGHT: i32 = 4; + +struct Beacons; + +/// The block the player stands in: their feet, floored. +fn feet(player: &Player) -> (i32, i32, i32) { + ( + player.x.floor() as i32, + player.y.floor() as i32, + player.z.floor() as i32, + ) +} + +/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up. +fn pillar(player: &Player) -> Vec { + let (x, y, z) = feet(player); + (0..HEIGHT) + .map(|dy| BlockChange { + x: x + 2, + y: y + dy, + z, + state: "minecraft:glowstone".into(), + }) + .collect() +} + +impl ServerMod for Beacons { + fn init() -> Result<(Self, Registration), String> { + Ok(( + Beacons, + Registration::new().command("beacon").command("ground"), + )) + } + + fn command( + &mut self, + player: &Player, + name: &str, + _args: &str, + ) -> Result, String> { + let (x, y, z) = feet(player); + if name == "beacon" { + world::set_blocks(&player.dimension, &pillar(player))?; + players::broadcast(&format!( + "{} lit a beacon at {} {y} {z}", + player.name, + x + 2 + )); + return Ok(None); + } + let below = world::get_block(&player.dimension, x, y - 1, z) + .ok_or("The ground under you isn't loaded")?; + let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default(); + Ok(Some(format!("You are standing on {below} in {biome}"))) + } +} + +horizon_mod_sdk::export_server_mod!(Beacons); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pillar_stands_two_blocks_east() { + let p = Player { + id: String::new(), + name: "Alex".into(), + x: -0.5, + y: 64.0, + z: 3.2, + dimension: "minecraft:overworld".into(), + game_mode: horizon_mod_sdk::server::GameMode::Survival, + health: 20.0, + }; + let blocks = pillar(&p); + assert_eq!(blocks.len(), HEIGHT as usize); + assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3)); + assert_eq!(blocks[3].y, 67); + } +} diff --git a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml new file mode 100644 index 000000000..e75caeb75 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml @@ -0,0 +1,22 @@ +# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east. + +[[step]] +join = "Alex" +blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }] +command = "ground" +expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains" + +[[step]] +command = "beacon" +expect.broadcast = ["Alex lit a beacon at 2 64 0"] +expect.blocks = [ + { x = 2, y = 64, z = 0, state = "minecraft:glowstone" }, + { x = 2, y = 67, z = 0, state = "minecraft:glowstone" }, + { x = 2, y = 68, z = 0, state = "minecraft:air" }, +] + +# Anywhere the script set nothing is air. +[[step]] +player = { x = 10.5, z = 10.5 } +command = "ground" +expect.feedback = "You are standing on minecraft:air in minecraft:plains" diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 1cffcc183..98f6a5ef4 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -166,6 +166,7 @@ pub mod server { pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; pub use horizon::mods::players::{self, GameMode, Player}; + pub use horizon::mods::world::{self, BlockChange}; /// The server'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 3a9027bba..f0dd1c596 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -144,6 +144,33 @@ interface players { broadcast: func(text: string); } +/// Capability `world`, server mods only (manifest `api = "0.3"`, +/// experimental): the blocks of the server's loaded chunks, and changes to +/// them through the server's own block updates. +interface %world { + record block-change { + x: s32, + y: s32, + z: s32, + /// `minecraft:oak_log[axis=y]`; properties left out take the block's + /// defaults, `minecraft:stone` alone is the default state. + state: string, + } + /// The block state at a position in a dimension (`minecraft:overworld`, + /// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the + /// server has no chunk loaded there. + get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option; + /// The biome at a position (`minecraft:plains`, ...), as the server + /// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. + get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option; + /// Sets blocks as `/setblock` does: the old block entity removed, + /// neighbours and shapes updated, light, and every player told. Every + /// state is checked now (an error queues nothing); the changes are made + /// in order after this call returns, before that dimension's next tick; + /// one in a chunk not loaded then is skipped. At most 4096 per call. + set-blocks: func(dimension: string, blocks: list) -> result<_, string>; +} + /// What the server calls in a server mod (manifest `api = "0.3"`, /// experimental). Only the hooks `init` asks for are ever called. The player /// in each event is as the server saw them when it happened. @@ -205,5 +232,6 @@ world horizon-server-mod { import log; import storage; import players; + import %world; export server-events; } diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 1caf2038f..ca7443186 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -80,19 +80,26 @@ pub enum Capability { Registries, /// The players on the server and messages to them (server mods). Players, + /// Blocks in the server's loaded chunks, and changes to them (server + /// mods; client mods later, where the game runs the world). + World, } impl Capability { - pub const ALL: [Capability; 6] = [ + pub const ALL: [Capability; 7] = [ Capability::GameRead, Capability::Chat, Capability::Hud, Capability::Storage, Capability::Registries, Capability::Players, + Capability::World, ]; /// Whether a server mod may have it: the others act on a local player. pub fn on_server(self) -> bool { - matches!(self, Capability::Storage | Capability::Players) + matches!( + self, + Capability::Storage | Capability::Players | Capability::World + ) } /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { @@ -103,6 +110,7 @@ impl Capability { Capability::Storage => "storage", Capability::Registries => "registries", Capability::Players => "players", + Capability::World => "world", } } /// What the player reads before turning the mod on: "May ". @@ -114,6 +122,7 @@ impl Capability { Capability::Storage => "save its own settings to disk", Capability::Registries => "add blocks and items to your worlds", Capability::Players => "see who is on the server and message them", + Capability::World => "read and change the world's blocks", } } /// The capability a component import needs, `Ok(None)` for one every @@ -145,6 +154,7 @@ impl fmt::Display for Capability { Capability::Storage => "storage", Capability::Registries => "registries", Capability::Players => "players", + Capability::World => "world", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index e80dbdc9f..fa0998614 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -1,12 +1,13 @@ //! Loading and calling mods with wasmtime's component model. use crate::manifest::{Manifest, Package, Side}; use server_bindings::{ - HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration, - horizon::mods::players, + HorizonServerMod, + exports::horizon::mods::server_events::Registration as ServerRegistration, + horizon::mods::{players, world as mod_world}, }; use std::{ path::{Path, PathBuf}, - sync::Arc, + sync::{Arc, Mutex}, time::{Duration, Instant, SystemTime}, }; use wasmtime::{ @@ -25,6 +26,7 @@ mod server_bindings { wasmtime::component::bindgen!({ path: "../horizon-mod-sdk/wit", world: "horizon-server-mod", + additional_derives: [PartialEq], with: { "horizon:mods/log": super::bindings::horizon::mods::log, "horizon:mods/storage": super::bindings::horizon::mods::storage, @@ -43,6 +45,7 @@ use bindings::{ pub use server_bindings::{ exports::horizon::mods::server_events::BlockPos, horizon::mods::players::{GameMode, Player as ServerPlayer}, + horizon::mods::world::BlockChange, }; type ClientEvents = bindings::exports::horizon::mods::events::Guest; type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest; @@ -55,6 +58,8 @@ const FUEL_INIT: u64 = 2_000_000_000; const FUEL_TICK: u64 = 50_000_000; const FUEL_FRAME: u64 = 10_000_000; const FUEL_EVENT: u64 = 100_000_000; +/// Blocks a mod may set per `world.set-blocks` call. +pub const BLOCKS_PER_CALL: usize = 4096; /// Chat lines a mod may show per call, HUD lines and their length. const CHAT_PER_CALL: usize = 8; const HUD_LINES: usize = 16; @@ -121,8 +126,32 @@ pub enum Output { text: String, error: bool, }, + /// `world.set-blocks`: changes to make in `dimension`, in order, each + /// state checked by the [`WorldView`] lent for the call. + SetBlocks { + name: String, + dimension: String, + blocks: Vec, + }, } +/// The game's world as capability `world` reads it during a call: the +/// game lends one with [`Mods::lend_world`] and takes it back after. +pub trait WorldView: std::any::Any + Send { + /// The block state at a position, `minecraft:oak_log[axis=y]`; `None` + /// where no chunk of that dimension is loaded. + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option; + /// The biome at a position, `minecraft:plains`; `None` as for blocks. + fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option; + /// Whether `dimension` is one the server has. + fn has_dimension(&self, dimension: &str) -> bool; + /// `Err` (why) for a state string that names no block state. + fn check_state(&self, state: &str) -> Result<(), String>; +} + +/// The view lent for the current calls, shared by every mod's store. +type WorldSlot = Arc>>>; + /// A mod's text panel, drawn every frame until it changes. #[derive(Clone, Debug)] pub struct Panel { @@ -199,6 +228,7 @@ struct State { /// needs its own budget. storage_budget: u64, limits: StoreLimits, + world: WorldSlot, } /// The installed mods and the engine running them. `Mods::default()` is @@ -209,9 +239,33 @@ pub struct Mods { entries: Vec, snapshot: Arc, out: Vec, + world: WorldSlot, } impl Mods { + /// Whether a running mod may use capability `world`: only then is a + /// view worth lending. + pub fn wants_world(&self) -> bool { + self.entries.iter().any(|e| { + e.status == Status::Running + && e.manifest + .as_ref() + .is_some_and(|m| m.capabilities.contains(&crate::Capability::World)) + }) + } + /// Lends the game's world to capability `world` for the calls until + /// [`Mods::take_world`]; with none lent, `get-block` finds nothing and + /// `set-blocks` checks only its count. + pub fn lend_world(&mut self, view: Box) { + if let Ok(mut slot) = self.world.lock() { + *slot = Some(view); + } + } + /// The view [`Mods::lend_world`] lent, back to the game. + pub fn take_world(&mut self) -> Option> { + self.world.lock().ok()?.take() + } + /// Reads every mod at `paths` and starts those `enabled` says are on, /// client and server mods alike. A command that `reserved` (vanilla's /// commands) or an earlier mod already uses is refused. @@ -281,6 +335,8 @@ impl Mods { .map_err(|e| e.to_string())?; players::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + mod_world::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")) @@ -318,6 +374,7 @@ impl Mods { .flat_map(|r| r.hooks.commands().iter().cloned()) .collect(); let snapshot = self.snapshot.clone(); + let world = self.world.clone(); let (engine, linker) = self.engine()?; let component = Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?; @@ -344,6 +401,7 @@ impl Mods { .memory_size(MEMORY) .instances(16) .build(), + world, }; let mut store = Store::new(engine, state); store.limiter(|s| &mut s.limits); @@ -731,6 +789,40 @@ impl chat::Host for State { }); } } +impl mod_world::Host for State { + fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option { + let view = self.world.lock().ok()?; + view.as_ref()?.block(&dimension, x, y, z) + } + fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option { + let view = self.world.lock().ok()?; + view.as_ref()?.biome(&dimension, x, y, z) + } + fn set_blocks(&mut self, dimension: String, blocks: Vec) -> Result<(), String> { + if blocks.len() > BLOCKS_PER_CALL { + return Err(format!( + "{} blocks: at most {BLOCKS_PER_CALL} per call", + blocks.len() + )); + } + if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) { + if !view.has_dimension(&dimension) { + return Err(format!("no dimension {dimension}")); + } + for b in &blocks { + view.check_state(&b.state)?; + } + } + if !blocks.is_empty() { + self.out.push(Output::SetBlocks { + name: self.name.clone(), + dimension, + blocks, + }); + } + Ok(()) + } +} impl players::Host for State { fn online(&mut self) -> Vec { self.snapshot.players.clone() diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index 31ff27227..239642357 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -29,6 +29,54 @@ pub struct TestGame { /// Every name that joined, for their id. names: Vec, tick: u64, + /// Capability `world`'s Overworld: the blocks a script set or the mod + /// changed; every other block, and the other dimensions, are air. Every + /// biome is the dimension's plainest: plains, nether wastes, the end. + pub world: std::collections::BTreeMap<(i32, i32, i32), String>, +} + +/// The world a script's mod reads: [`TestGame::world`], copied for a step. +struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>); + +impl crate::WorldView for ScriptWorld { + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let here = (dimension == "minecraft:overworld") + .then(|| self.0.get(&(x, y, z)).cloned()) + .flatten(); + Some(here.unwrap_or_else(|| "minecraft:air".into())) + } + fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option { + let biome = match dimension { + "minecraft:overworld" => "minecraft:plains", + "minecraft:the_nether" => "minecraft:nether_wastes", + "minecraft:the_end" => "minecraft:the_end", + _ => return None, + }; + Some(biome.into()) + } + fn has_dimension(&self, dimension: &str) -> bool { + matches!( + dimension, + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) + } + fn check_state(&self, state: &str) -> Result<(), String> { + // No registry here: the shape only (the game checks the names). + let name = state.split('[').next().unwrap_or_default(); + let plain = |t: &str| { + !t.is_empty() + && t.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b)) + }; + let ok = match name.split_once(':') { + Some((ns, path)) => plain(ns) && plain(path), + None => plain(name), + }; + let closed = !state.contains('[') || state.ends_with(']'); + (ok && closed) + .then_some(()) + .ok_or_else(|| format!("{state} is not a block state")) + } } /// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing @@ -71,6 +119,7 @@ impl TestGame { players: Vec::new(), names: Vec::new(), tick: 0, + world: Default::default(), }; copy_mod(hmod, ©)?; game.start()?; @@ -309,9 +358,10 @@ pub struct ClockSet { } /// One step. Its parts happen in this order: `reload`, `title-screen`, -/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`, -/// `place`, `leave`; then `expect` is checked against what the mod showed -/// during the step. For a server mod, `player`, `chat`, `command`, `break` +/// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, +/// `break`, `place`, `leave`; then the blocks the mod set are made, and +/// `expect` is checked against what the mod showed and changed during the +/// step. For a server mod, `player`, `chat`, `command`, `break` /// and `place` are the doing of the player named by `as`, or of the first /// player on. #[derive(Debug, Default, Deserialize)] @@ -338,6 +388,10 @@ pub struct Step { #[serde(rename = "break")] broken: Option, place: Option, + /// Blocks of the Overworld before the rest of the step (capability + /// `world`); every other block is air. + #[serde(default)] + blocks: Vec, #[serde(default)] expect: Expect, } @@ -360,6 +414,9 @@ pub struct Expect { /// The panel's lines (`[]`: no panel) and its corner. panel: Option>, corner: Option, + /// Blocks of the Overworld after the step, the mod's changes made + /// (capability `world`). + blocks: Option>, /// The mod is turned off during this step, for a reason holding this text. /// Without it, a mod that stops fails the test. stopped: Option, @@ -464,6 +521,11 @@ impl Step { game.player = None; game.clock = None; } + for b in &self.blocks { + game.world.insert((b.x, b.y, b.z), b.state.clone()); + } + game.mods + .lend_world(Box::new(ScriptWorld(game.world.clone()))); if let Some(name) = &self.join { game.join(name); } @@ -528,7 +590,19 @@ impl Step { { return Err(format!("{name} is not on the server")); } + game.mods.take_world(); let out = game.drain(); + for o in &out { + if let Output::SetBlocks { + dimension, blocks, .. + } = o + && dimension == "minecraft:overworld" + { + for b in blocks { + game.world.insert((b.x, b.y, b.z), b.state.clone()); + } + } + } let stopped = out.iter().find_map(|o| match o { Output::Stopped { reason, .. } => Some(reason.as_str()), _ => None, @@ -612,6 +686,18 @@ impl Step { .unwrap_or_default(); same("panel", want, &got)?; } + if let Some(want) = &e.blocks { + for b in want { + let got = game.world.get(&(b.x, b.y, b.z)); + let got = got.map_or("minecraft:air", String::as_str); + if got != b.state { + return Err(format!( + "block at {} {} {}: expected {}, got {got}", + b.x, b.y, b.z, b.state + )); + } + } + } if let Some(want) = &e.corner { let got = game.panel().map(|p| corner_name(p.corner).to_string()); same("corner", &Some(want.clone()), &got)?; diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index ca2b8896e..3647cca30 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -36,6 +36,8 @@ fn mods_dir() -> &'static Path { "-p", "welcome", "-p", + "beacons", + "-p", "horizon-mods-test-guest", "--target-dir", ]) @@ -56,6 +58,7 @@ fn mods_dir() -> &'static Path { let mods = [ ("coords_hud", example("coords-hud")), ("welcome", example("welcome")), + ("beacons", example("beacons")), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), ]; for (name, manifest) in mods { @@ -412,7 +415,12 @@ capabilities = ["registries"] fn the_examples_test_scripts_pass() { let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples"); let mut ran = 0; - for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] { + let examples_and_files = [ + ("coords-hud", "coords_hud"), + ("welcome", "welcome"), + ("beacons", "beacons"), + ]; + for (example, hmod) in examples_and_files { for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() { let path = entry.unwrap().path(); let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); @@ -423,7 +431,24 @@ fn the_examples_test_scripts_pass() { ran += 1; } } - assert_eq!(ran, 4); + assert_eq!(ran, 5); +} + +/// Capability `world` without a world lent (the registry's trial run): +/// `get-block` finds nothing, `set-blocks` checks its count and queues. +#[test] +fn a_server_mod_without_a_world_reads_nothing() { + let mut game = TestGame::load(&mods_dir().join("beacons.hmod")).unwrap(); + game.join("Alex"); + let alex = game.players[0].clone(); + assert!(game.player_command(&alex, "ground")); + let out = game.drain(); + assert!( + out.iter() + .any(|o| matches!(o, Output::Reply { text, error: true, .. } + if text == "The ground under you isn't loaded")), + "{out:?}" + ); } #[test] diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index f179e99cc..3aaf29d0c 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -13,6 +13,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `storage` | [`storage`](#storage) | save its own settings to disk | | `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds | | `players` | [`players`](#players) | see who is on the server and message them | +| `world` | [`world`](#world) | read and change the world's blocks | ## World `horizon-mod` @@ -25,7 +26,7 @@ A client mod: runs in the player's game. A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs where the world is simulated, on the dedicated server, a LAN host and single player's own server. -- Imports (what the game offers): `log`, `storage`, `players` +- Imports (what the game offers): `log`, `storage`, `players`, `world` - Exports (what the mod provides): `server-events` ## `log` @@ -184,6 +185,27 @@ Capability `players`, server mods only (manifest `api = "0.3"`, experimental): t | `tell` | `func(player: string, text: string) -> bool` | A system message to one player, after the mod's name; false when no player with that id is online. Up to 8 messages per call. | | `broadcast` | `func(text: string)` | A system message to every player and the server's log, after the mod's name. Counts toward the same 8 per call. | +## `world` + +Access: capability `world`. + +Capability `world`, server mods only (manifest `api = "0.3"`, experimental): the blocks of the server's loaded chunks, and changes to them through the server's own block updates. + +### record `block-change` + +| Field | Type | | +| --- | --- | --- | +| `x` | `s32` | | +| `y` | `s32` | | +| `z` | `s32` | | +| `state` | `string` | `minecraft:oak_log[axis=y]`; properties left out take the block's defaults, `minecraft:stone` alone is the default state. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `get-block` | `func(dimension: string, x: s32, y: s32, z: s32) -> option` | The block state at a position in a dimension (`minecraft:overworld`, ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the server has no chunk loaded there. | +| `get-biome` | `func(dimension: string, x: s32, y: s32, z: s32) -> option` | The biome at a position (`minecraft:plains`, ...), as the server stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. | +| `set-blocks` | `func(dimension: string, blocks: list) -> result<_, string>` | Sets blocks as `/setblock` does: the old block entity removed, neighbours and shapes updated, light, and every player told. Every state is checked now (an error queues nothing); the changes are made in order after this call returns, before that dimension's next tick; one in a chunk not loaded then is skipped. At most 4096 per call. | + ## `server-events` Access: exported by the mod: the game calls it. diff --git a/docs/api/mods.md b/docs/api/mods.md index 5fb9d9c1e..76075e989 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -84,11 +84,11 @@ release. What real mods need next, in the order modpacks and servers need it: - **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run - on the server thread, a LAN host and the dedicated server today, with joins, chat, commands and players' block - breaking and placing; next entity events, game rules, server commands with typed arguments sent to clients' - command trees. -- **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block - log, so clients and the parity harnesses see vanilla's updates. + on the server thread, a LAN host and the dedicated server today, with joins, chat, commands, players' block + breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` does); next entity events, game rules, + server commands with typed arguments sent to clients' command trees. +- **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities, + and `world` for client mods (raycasts, single player and LAN hosts). - **Items and inventories**: the player's inventory, held item and open container; item stacks with components. - **Entities**: query and change entities near a position; spawn from a mod's own entity types (data first). - **Block entities and menus**: ticking machines with slots and their screens. @@ -102,6 +102,8 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and + `expect.blocks`. - Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server. - API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events` hooks; SDK `server::ServerMod`; example `welcome`. diff --git a/docs/mods.md b/docs/mods.md index f0df45994..19b05f9ec 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -278,6 +278,7 @@ A step's parts happen in this order: | --- | --- | | `reload = true` | stops the mod and starts it again, as a rebuild does in the game: its memory starts over, its `storage` stays | | `title-screen = true` | no player and no clock until a step sets them | +| `blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:stone" }]` | server mods with `world`: those blocks of the Overworld, before the rest of the step (every other block is air, every biome the dimension's plainest: plains, nether wastes, the end) | | `player = { x = 3.0, ... }`, `clock = { day-time = 0 }` | changes those fields (`x y z yaw pitch health food dimension`, `game-time day-time`) | | `ticks = n`, `frames = n` | that many ticks (the game's tick counter and the clock move on), then frames 1/60 s apart | | `chat = " hi"` | a chat line the player receives | @@ -303,6 +304,7 @@ checked: | `feedback = "..."`, `error = "..."` | the command's answer, shown plain or in red | | `panel = ["..."]`, `corner = "top-left"` | its HUD panel's lines (`[]`: no panel) and corner | | `told = ["Alex: Welcome!"]`, `broadcast = ["..."]` | server mods: every `players.tell` (as `name: text`) and `players.broadcast`, in order | +| `blocks = [{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" }]` | server mods with `world`: those blocks of the Overworld after the step, the mod's `set-blocks` made (the script checks a state's shape; the game checks its name) | | `stopped = "panic"` | the mod was turned off, for a reason holding this text; without it, a mod that traps, panics or overruns fails the test | Unknown keys are errors, so a typo never passes silently. The same runner is @@ -465,6 +467,7 @@ its component targets the WIT world `horizon-server-mod` instead of | `log` | always | as for client mods | | `storage` | `storage` | as for client mods, in the server's `horizon-mods/` | | `players` | `players` | `online()`: id, name, position, dimension, game mode, health of each player on; `tell(id, text)`, `broadcast(text)`: system messages after the mod's name, 8 per call | +| `world` | `world` | `get-block(dimension, x, y, z)`: the state in a loaded chunk, `minecraft:oak_log[axis=y]`; `get-biome(dimension, x, y, z)`: `minecraft:plains`, ...; `set-blocks(dimension, changes)`: up to 4096 per call, checked at once, made as `/setblock` makes them (neighbours, light, block entities, every player told) after the call, before that dimension's next tick | | Hook (export `server-events`) | When | |---|---| @@ -478,7 +481,20 @@ its component targets the WIT world `horizon-server-mod` instead of Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for client mods; `players` is for server mods. In Rust: `impl horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is -[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs). +[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with +`world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs). + +**Capability `world`.** Reads are of the server's loaded chunks as they are +during the call: the game lends a server mod's call the levels' chunk maps +(moved, not copied, and only while a running mod has `world`), so a read +costs a map lookup and no copy of the world. A dimension with no chunk loaded +at a position reads as none. Writes go through the same code as `/setblock`, +so block updates, light, block entities and every client (LAN guests, +dedicated server players) see them as vanilla's; the parity harnesses test +that code. Changes for a dimension whose level isn't ticking wait for it +(in-frame single player ticks only the player's), up to 65,536 blocks; a +change in a chunk that isn't loaded when it is made is skipped, as `/setblock` +refuses one. **Where they run.** The game that simulates the world starts the server mods that are on, and only that one: From c5bb51bb053a7f41acf7361f831091a7b54ce493 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:19:50 +0100 Subject: [PATCH 002/132] Mod API 0.3: typed server commands, in players' command trees A server mod's registration now lists each command's arguments: a name, a kind (word, text, integer with bounds, number, boolean, player, block-pos) and whether it is optional. The server adds them to the command tree every player receives, after vanilla's commands, so a player's chat box completes and colours them as vanilla's. When a player sends one, the server parses the line as vanilla's parsers do (horizon-mods' commands.rs: ~ coordinates from the player, @s/@p, integer bounds) and calls the mod's command hook with the values by name, or answers with vanilla's error without calling the mod. The hub keeps the server mods' commands as a root in the commands report's format and resends players' trees when they change (CommandTree:: packet_with); the game sets it when its mods start, stop or reload, or a hub opens. In-frame, the window's own chat box lists them by name. SDK: Registration::command_with(name, [Argument::...]), Argument builders, Args (text(), integer(), player(), block_pos() ...); command(name) is free text, an optional text argument. Examples: welcome's /mined [player], beacons' /beacon [height] and /ground [pos], with scripts for values and errors. Docs: docs/mods.md (typed commands, kinds table), docs/api/mods.md and the regenerated reference. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 2 +- crates/horizon-client/src/game/mods.rs | 5 +- crates/horizon-client/src/game/server_mods.rs | 74 ++++- crates/horizon-client/src/lan/commands.rs | 63 +++- crates/horizon-client/src/lan/hub.rs | 29 +- .../examples/beacons/horizon-mod.toml | 2 +- .../examples/beacons/src/lib.rs | 46 ++- .../examples/beacons/tests/beacons.toml | 19 +- .../examples/welcome/src/lib.rs | 25 +- .../examples/welcome/tests/commands.toml | 17 +- crates/horizon-mod-sdk/src/lib.rs | 135 +++++++- crates/horizon-mod-sdk/wit/horizon.wit | 68 +++- crates/horizon-mods/src/commands.rs | 301 ++++++++++++++++++ crates/horizon-mods/src/lib.rs | 2 + crates/horizon-mods/src/runtime.rs | 117 +++++-- crates/horizon-mods/src/testing.rs | 2 +- crates/horizon-mods/tests/sandbox.rs | 12 +- docs/api/mods-reference.md | 65 +++- docs/api/mods.md | 11 +- docs/mods.md | 36 ++- 20 files changed, 923 insertions(+), 108 deletions(-) create mode 100644 crates/horizon-mods/src/commands.rs diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 4d271e2c1..7e3091805 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -183,7 +183,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { return Err(format!("it didn't start: {reason}")); } let client: Vec = mods.commands().map(str::to_owned).collect(); - let server: Vec = mods.server_commands().map(str::to_owned).collect(); + let server: Vec = mods.server_commands().map(|c| c.name.clone()).collect(); report.commands = [client.clone(), server.clone()].concat(); // A server mod plays with one player on, who joins, chats and leaves. let steve = ServerPlayer { diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 111b797ad..0c3d32a40 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -262,7 +262,10 @@ impl Game<'_> { } /// The chat's tree after the running mods changed. fn sync_mod_commands(&mut self) { - let mut names = self.mods.mods.commands().peekable(); + // In-frame, the window runs server mods too: their names, free text + // here (the server parses their arguments). + let server = self.mods.mods.server_commands().map(|c| c.name.as_str()); + let mut names = self.mods.mods.commands().chain(server).peekable(); self.mods.tree = names .peek() .is_some() diff --git a/crates/horizon-client/src/game/server_mods.rs b/crates/horizon-client/src/game/server_mods.rs index f5ee5cdc2..a5a4b0f3f 100644 --- a/crates/horizon-client/src/game/server_mods.rs +++ b/crates/horizon-client/src/game/server_mods.rs @@ -59,9 +59,12 @@ mod run { lan::data::component_nbt, text::{self, Text}, }; - use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView}; + use horizon_mods::{ + ArgumentKind, BlockPos, GameMode, Output, ServerCommand, ServerPlayer, WorldView, + }; use horizon_protocol::packets::play::{self, Clientbound as C}; use horizon_world::registry::{BlockRegistry, BlockStateId}; + use serde_json::{Value, json}; /// Blocks queued for levels that don't tick (another dimension, in-frame) /// are kept up to this many; the oldest go first. @@ -98,6 +101,60 @@ mod run { } } + /// Server mods' commands as a root of the commands report + /// (`lan::commands`): a literal per command, then its arguments in a + /// chain, each node runnable where only optional arguments follow. + fn command_tree<'a>(commands: impl Iterator) -> Value { + let mut root = serde_json::Map::new(); + for c in commands { + let mut next: Option<(String, Value)> = None; + for (i, a) in c.arguments.iter().enumerate().rev() { + let executable = c.arguments.get(i + 1).is_none_or(|b| b.optional); + let (parser, properties) = match a.kind { + ArgumentKind::Word => ("brigadier:string", json!({"type": "word"})), + ArgumentKind::Text => ("brigadier:string", json!({"type": "greedy"})), + ArgumentKind::Integer((min, max)) => { + let mut p = serde_json::Map::new(); + if let Some(min) = min { + p.insert("min".into(), min.into()); + } + if let Some(max) = max { + p.insert("max".into(), max.into()); + } + ("brigadier:integer", Value::Object(p)) + } + ArgumentKind::Number => ("brigadier:double", Value::Null), + ArgumentKind::Boolean => ("brigadier:bool", Value::Null), + ArgumentKind::Player => ( + "minecraft:entity", + json!({"amount": "single", "type": "players"}), + ), + ArgumentKind::BlockPos => ("minecraft:block_pos", Value::Null), + }; + let mut node = json!({ + "type": "argument", + "parser": parser, + "properties": properties, + "executable": executable, + }); + if let Some((name, child)) = next.take() { + node["children"] = json!({ name: child }); + } + next = Some((a.name.clone(), node)); + } + let executable = c.arguments.first().is_none_or(|a| a.optional); + let mut literal = json!({"type": "literal", "executable": executable}); + if let Some((name, child)) = next { + literal["children"] = json!({ name: child }); + } + root.insert(c.name.clone(), literal); + } + if root.is_empty() { + return Value::Null; + } + json!({"type": "root", "children": root}) + } + /// `minecraft:oak_log[axis=y]`. fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String { let Some(s) = registry.state(state) else { @@ -191,6 +248,7 @@ mod run { // A server has no frames to check its dev mods in. self.reload_dev_mods(); } + self.send_server_mod_commands(); if !self.mods.server { return; } @@ -257,6 +315,20 @@ mod run { self.apply_mod_block_writes(); } + /// Players' command trees list the running server mods' commands + /// after vanilla's, whenever they change (or a hub opens). + fn send_server_mod_commands(&mut self) { + let key = self.mods.mods.generation(); + let Some(host) = self.lan.as_mut() else { + return; + }; + if host.hub.mod_commands_key() == Some(key) { + return; + } + let tree = command_tree(self.mods.mods.server_commands()); + host.hub.set_mod_commands(key, tree); + } + /// Lends the levels' chunks to capability `world` for the calls up to /// [`Game::return_world`], when a running server mod has it. fn lend_world(&mut self) { diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs index 71b7fa68d..c3e462348 100644 --- a/crates/horizon-client/src/lan/commands.rs +++ b/crates/horizon-client/src/lan/commands.rs @@ -86,6 +86,18 @@ impl CommandTree { /// The ClientboundCommandsPacket for a player with `level` permissions. pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands { + self.packet_with(level, dedicated, builtin, &Value::Null) + } + + /// [`CommandTree::packet`] with more commands after vanilla's: `extra` + /// is a root in the report's format (server mods' commands). + pub fn packet_with( + &self, + level: u8, + dedicated: bool, + builtin: &Builtin, + extra: &Value, + ) -> Commands { let mut nodes = vec![Node { name: String::new(), kind: 0, @@ -99,16 +111,18 @@ impl CommandTree { let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect(); let mut paths: HashMap, usize> = HashMap::new(); paths.insert(Vec::new(), 0); - fill( - &self.root, - 0, - &mut Vec::new(), - level, - dedicated, - &suggestions, - &mut nodes, - &mut paths, - ); + for root in [&self.root, extra] { + fill( + root, + 0, + &mut Vec::new(), + level, + dedicated, + &suggestions, + &mut nodes, + &mut paths, + ); + } // enumerateNodes: breadth first from the root, each node's children // (in registration order) then its redirect target. let mut ids = vec![None; nodes.len()]; @@ -365,4 +379,33 @@ mod tests { ); assert!(op.nodes[3].restricted); } + + #[test] + fn server_mods_commands_follow_vanillas() { + let report: Value = serde_json::from_str( + r#"{"type":"root","children":{"me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}}}"#, + ) + .unwrap(); + let mods: Value = serde_json::from_str( + r#"{"type":"root","children":{"beacon":{"type":"literal","executable":true,"children":{ + "height":{"type":"argument","parser":"brigadier:integer","properties":{"min":1,"max":64},"executable":true}}}}}"#, + ) + .unwrap(); + let tree = CommandTree { root: report }; + let packet = tree.packet_with(0, true, &Builtin::default(), &mods); + let names: Vec<_> = packet.nodes.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["", "me", "beacon", "action", "height"]); + let beacon = &packet.nodes[2]; + assert!(beacon.executable && !beacon.restricted); + assert_eq!(beacon.children, [4]); + let height = packet.nodes[4].parser.as_ref().unwrap(); + assert_eq!(height.1, vec![3, 0, 0, 0, 1, 0, 0, 0, 64]); + // No mods: vanilla's tree as it is. + assert_eq!( + tree.packet_with(0, true, &Builtin::default(), &Value::Null) + .nodes + .len(), + 3 + ); + } } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 761d31af4..2938e530b 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -174,6 +174,9 @@ pub struct Hub { entities: std::collections::HashMap, /// What one tick of entity tracking sends each guest, kept between ticks. entity_out: Vec>>, + /// Server mods' commands, a root in the commands report's format, sent + /// after vanilla's; the key the game last set them for. + mod_commands: (serde_json::Value, Option), } fn string(s: &str) -> Tag { @@ -320,6 +323,7 @@ impl Hub { entity_types: Default::default(), entities: Default::default(), entity_out: Vec::new(), + mod_commands: (serde_json::Value::Null, None), } } @@ -815,13 +819,36 @@ impl Hub { } } + /// The key [`Hub::set_mod_commands`] last had: the game compares it + /// with its server mods' each tick. + pub fn mod_commands_key(&self) -> Option { + self.mod_commands.1 + } + /// Server mods' commands changed: every player gets their tree again. + pub fn set_mod_commands(&mut self, key: u64, commands: serde_json::Value) { + let resend = self.mod_commands.0 != commands; + self.mod_commands = (commands, Some(key)); + if resend { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.send_commands(i); + } + } + } + } + /// Commands.sendCommands: the command tree for this player. fn send_commands(&self, i: usize) { let g = &self.guests[i]; let packet = match &self.sync.commands { Some(tree) => { let dedicated = self.config.dedicated && !self.config.integrated; - tree.packet(g.permission, dedicated, &self.sync.builtin) + tree.packet_with( + g.permission, + dedicated, + &self.sync.builtin, + &self.mod_commands.0, + ) } None => play::Commands { nodes: vec![play::CommandNode { diff --git a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml index 0c2004b5f..5b58273c6 100644 --- a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml +++ b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml @@ -1,7 +1,7 @@ id = "beacons" name = "Beacons" version = "0.1.0" -description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome." +description = "/beacon [height] lights a pillar of glowstone beside you; /ground [pos] says what you are standing on (or what is at pos), and in which biome." authors = ["Horizon"] api = "0.3" side = "server" diff --git a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs index 509431775..4a4de5cc1 100644 --- a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs +++ b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs @@ -1,9 +1,12 @@ //! Example Horizon server mod (`docs/mods.md`, "Server mods") with -//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east -//! of the player, `/ground` reads the block under their feet and the biome. -use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world}; +//! capability `world` and typed commands: `/beacon [height]` lights a +//! pillar of glowstone two blocks east of the player, `/ground [pos]` reads +//! the block under their feet (or at `pos`) and its biome. +use horizon_mod_sdk::server::{ + Args, Argument, BlockChange, Player, Registration, ServerMod, players, world, +}; -/// How tall `/beacon` builds. +/// How tall `/beacon` builds when no height is given. const HEIGHT: i32 = 4; struct Beacons; @@ -17,10 +20,10 @@ fn feet(player: &Player) -> (i32, i32, i32) { ) } -/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up. -fn pillar(player: &Player) -> Vec { +/// The pillar beside `player`: `height` blocks of glowstone, from their feet up. +fn pillar(player: &Player, height: i32) -> Vec { let (x, y, z) = feet(player); - (0..HEIGHT) + (0..height) .map(|dy| BlockChange { x: x + 2, y: y + dy, @@ -34,7 +37,12 @@ impl ServerMod for Beacons { fn init() -> Result<(Self, Registration), String> { Ok(( Beacons, - Registration::new().command("beacon").command("ground"), + Registration::new() + .command_with( + "beacon", + [Argument::integer("height", Some(1), Some(64)).optional()], + ) + .command_with("ground", [Argument::block_pos("pos").optional()]), )) } @@ -42,11 +50,12 @@ impl ServerMod for Beacons { &mut self, player: &Player, name: &str, - _args: &str, + args: &Args, ) -> Result, String> { let (x, y, z) = feet(player); if name == "beacon" { - world::set_blocks(&player.dimension, &pillar(player))?; + let height = args.integer("height").unwrap_or(HEIGHT); + world::set_blocks(&player.dimension, &pillar(player, height))?; players::broadcast(&format!( "{} lit a beacon at {} {y} {z}", player.name, @@ -54,10 +63,17 @@ impl ServerMod for Beacons { )); return Ok(None); } - let below = world::get_block(&player.dimension, x, y - 1, z) - .ok_or("The ground under you isn't loaded")?; - let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default(); - Ok(Some(format!("You are standing on {below} in {biome}"))) + let (bx, by, bz) = match args.block_pos("pos") { + Some(p) => (p.x, p.y, p.z), + None => (x, y - 1, z), + }; + let block = + world::get_block(&player.dimension, bx, by, bz).ok_or("That block isn't loaded")?; + let biome = world::get_biome(&player.dimension, bx, by, bz).unwrap_or_default(); + if args.block_pos("pos").is_some() { + return Ok(Some(format!("{bx} {by} {bz} is {block} in {biome}"))); + } + Ok(Some(format!("You are standing on {block} in {biome}"))) } } @@ -79,7 +95,7 @@ mod tests { game_mode: horizon_mod_sdk::server::GameMode::Survival, health: 20.0, }; - let blocks = pillar(&p); + let blocks = pillar(&p, HEIGHT); assert_eq!(blocks.len(), HEIGHT as usize); assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3)); assert_eq!(blocks[3].y, 67); diff --git a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml index e75caeb75..bab4839f3 100644 --- a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml +++ b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml @@ -1,4 +1,4 @@ -# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east. +# /ground [pos] reads the block under the player (or at pos) and the biome; /beacon [height] sets glowstone two to the east. [[step]] join = "Alex" @@ -20,3 +20,20 @@ expect.blocks = [ player = { x = 10.5, z = 10.5 } command = "ground" expect.feedback = "You are standing on minecraft:air in minecraft:plains" + +# Typed arguments: a height, a position relative to the player. +[[step]] +player = { x = 5.5, y = 64.0, z = 5.5 } +command = "beacon 2" +expect.blocks = [ + { x = 7, y = 65, z = 5, state = "minecraft:glowstone" }, + { x = 7, y = 66, z = 5, state = "minecraft:air" }, +] + +[[step]] +command = "beacon 65" +expect.error = "Integer must not be more than 64, found 65" + +[[step]] +command = "ground ~2 ~1 ~" +expect.feedback = "7 65 5 is minecraft:glowstone in minecraft:plains" diff --git a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs index c45712c88..e5a5ef13e 100644 --- a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs +++ b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs @@ -1,9 +1,10 @@ //! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each //! player who joins, announces a newcomer to everyone (the players it has //! seen are kept in `storage`), `/online` lists who is on and where, and -//! `/mined` counts the blocks the player broke since the server started. +//! `/mined [player]` counts the blocks a player broke since the server +//! started (typed arguments: the chat box completes the player's name). use horizon_mod_sdk::{ - server::{BlockPos, Player, Registration, ServerMod, players}, + server::{Args, Argument, BlockPos, Player, Registration, ServerMod, players}, storage, }; use std::collections::HashMap; @@ -25,8 +26,8 @@ impl ServerMod for Welcome { }) .unwrap_or_default(); let hooks = Registration::new() - .command("online") - .command("mined") + .command_with("online", []) + .command_with("mined", [Argument::player("player").optional()]) .on_joins() .on_blocks(); Ok(( @@ -55,7 +56,7 @@ impl ServerMod for Welcome { &mut self, player: &Player, name: &str, - _args: &str, + args: &Args, ) -> Result, String> { Ok(Some(match name { "online" => players::online() @@ -69,10 +70,16 @@ impl ServerMod for Welcome { }) .collect::>() .join(", "), - _ => { - let n = self.mined.get(&player.id).copied().unwrap_or(0); - format!("You broke {n} block(s)") - } + _ => match args.player("player") { + Some(other) if other.id != player.id => { + let n = self.mined.get(&other.id).copied().unwrap_or(0); + format!("{} broke {n} block(s)", other.name) + } + _ => { + let n = self.mined.get(&player.id).copied().unwrap_or(0); + format!("You broke {n} block(s)") + } + }, })) } diff --git a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml index 5f0018346..a55bd421d 100644 --- a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml +++ b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml @@ -1,4 +1,4 @@ -# /online lists the players and their dimension; /mined counts the acting player's blocks. +# /online lists the players and their dimension; /mined [player] counts a player's blocks. [[step]] join = "Alex" @@ -29,3 +29,18 @@ expect.feedback = "You broke 2 block(s)" as = "Steve" command = "mined" expect.feedback = "You broke 0 block(s)" + +[[step]] +as = "Steve" +command = "mined alex" +expect.feedback = "Alex broke 2 block(s)" + +# The server parses the arguments before the mod: vanilla's errors. +[[step]] +as = "Steve" +command = "mined Herobrine" +expect.error = "No player was found" + +[[step]] +command = "online now" +expect.error = "Incorrect argument for command" diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 98f6a5ef4..875113e94 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -164,7 +164,10 @@ pub mod server { }, }); - pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; + pub use exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, Guest as __Guest, Registration, + ServerCommand, + }; pub use horizon::mods::players::{self, GameMode, Player}; pub use horizon::mods::world::{self, BlockChange}; @@ -181,13 +184,14 @@ pub mod server { fn player_left(&mut self, _player: &Player) {} /// A chat message a player sent, when [`Registration::chat`] is set. fn chat(&mut self, _player: &Player, _text: &str) {} - /// `/name args` typed by `player`. `Ok(Some(text))` is their - /// feedback, `Err(text)` their error in red. + /// `/name args` typed by `player`, parsed as the command's + /// arguments say ([`Registration::command_with`]). `Ok(Some(text))` + /// is their feedback, `Err(text)` their error in red. fn command( &mut self, _player: &Player, _name: &str, - _args: &str, + _args: &Args, ) -> Result, String> { Err("This command does nothing".into()) } @@ -207,9 +211,23 @@ pub mod server { blocks: false, } } - /// Adds `/name`. - pub fn command(mut self, name: &str) -> Self { - self.commands.push(name.into()); + /// Adds `/name`, taking free text ([`Args::text`]): one optional + /// `text` argument named `args`. + pub fn command(self, name: &str) -> Self { + self.command_with(name, [Argument::text("args").optional()]) + } + /// Adds `/name` with typed arguments (none: nothing after the name): + /// players' chat boxes complete and check them, and the server + /// parses them into [`Args`]. + pub fn command_with( + mut self, + name: &str, + arguments: impl IntoIterator, + ) -> Self { + self.commands.push(ServerCommand { + name: name.into(), + arguments: arguments.into_iter().collect(), + }); self } pub fn on_tick(mut self) -> Self { @@ -234,6 +252,105 @@ pub mod server { Self::new() } } + + impl Argument { + fn of(name: &str, kind: ArgumentKind) -> Self { + Self { + name: name.into(), + kind, + optional: false, + } + } + /// One word: letters, digits and `_ - . +`. + pub fn word(name: &str) -> Self { + Self::of(name, ArgumentKind::Word) + } + /// The rest of the line: only last. + pub fn text(name: &str) -> Self { + Self::of(name, ArgumentKind::Text) + } + /// A whole number, at least `min` and at most `max` when given. + pub fn integer(name: &str, min: Option, max: Option) -> Self { + Self::of(name, ArgumentKind::Integer((min, max))) + } + pub fn number(name: &str) -> Self { + Self::of(name, ArgumentKind::Number) + } + pub fn boolean(name: &str) -> Self { + Self::of(name, ArgumentKind::Boolean) + } + /// One online player: a name, `@s` or `@p`. + pub fn player(name: &str) -> Self { + Self::of(name, ArgumentKind::Player) + } + /// `x y z`, each one also `~` or `~n`. + pub fn block_pos(name: &str) -> Self { + Self::of(name, ArgumentKind::BlockPos) + } + /// May be left out; optional arguments come after the required ones. + pub fn optional(mut self) -> Self { + self.optional = true; + self + } + } + + /// A command's arguments: the line as typed, and the values the server + /// parsed from it, by argument name. + #[derive(Clone, Debug, Default)] + pub struct Args { + text: String, + values: Vec<(String, ArgumentValue)>, + } + impl Args { + pub fn new(text: String, values: Vec<(String, ArgumentValue)>) -> Self { + Self { text, values } + } + /// The line after the command's name, as typed. + pub fn text(&self) -> &str { + &self.text + } + /// The value of argument `name`; `None` when it was left out. + pub fn get(&self, name: &str) -> Option<&ArgumentValue> { + self.values.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + pub fn integer(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Integer(n) => Some(*n), + _ => None, + } + } + pub fn number(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Number(n) => Some(*n), + _ => None, + } + } + /// A `word` or `text` argument. + pub fn string(&self, name: &str) -> Option<&str> { + match self.get(name)? { + ArgumentValue::Word(s) | ArgumentValue::Text(s) => Some(s), + _ => None, + } + } + pub fn boolean(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Boolean(b) => Some(*b), + _ => None, + } + } + pub fn player(&self, name: &str) -> Option<&Player> { + match self.get(name)? { + ArgumentValue::Player(p) => Some(p), + _ => None, + } + } + pub fn block_pos(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::BlockPos(p) => Some(*p), + _ => None, + } + } + } } /// Exports a [`ServerMod`](server::ServerMod) as the component's @@ -243,7 +360,7 @@ macro_rules! export_server_mod { ($t:ty) => { const _: () = { use ::std::cell::RefCell; - use $crate::server::{BlockPos, Player, Registration, ServerMod}; + use $crate::server::{Args, ArgumentValue, BlockPos, Player, Registration, ServerMod}; ::std::thread_local! { static STATE: RefCell> = const { RefCell::new(None) }; } @@ -277,8 +394,10 @@ macro_rules! export_server_mod { player: Player, name: String, args: String, + values: Vec<(String, ArgumentValue)>, ) -> Result, String> { let mut out = Err("The mod is not running".to_string()); + let args = Args::new(args, values); with(|m| out = m.command(&player, &name, &args)); out } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index f0dd1c596..e8cea0d02 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -177,10 +177,61 @@ interface %world { interface server-events { use players.{player}; + record block-pos { + x: s32, + y: s32, + z: s32, + } + /// What an argument of a command takes. The server sends each command + /// and its arguments to players' games, whose chat box completes and + /// colours them as vanilla's; the server parses them before the mod's + /// `command` hook gets their values. + variant argument-kind { + /// One word: letters, digits and `_ - . +`. + word, + /// The rest of the line, spaces included: only last. + text, + /// A whole number, within the bounds given. + integer(tuple, option>), + /// A number with or without decimals. + number, + /// `true` or `false`. + boolean, + /// One online player: a name, or `@s` or `@p` (whoever typed it, + /// as vanilla picks for a player). + player, + /// A block position: three whole numbers, each one also `~` or + /// `~n`, relative to whoever typed it. + block-pos, + } + record argument { + /// Shown in the chat box's hint (``) and the key of its value. + name: string, + kind: argument-kind, + /// Optional arguments come after every required one. + optional: bool, + } + record server-command { + /// Without the slash. A name vanilla already uses is refused + /// (vanilla's command runs). + name: string, + /// In order; none: the command takes nothing after its name. Free + /// text is one optional `text` argument. + arguments: list, + } + /// An argument's value, parsed as its kind says. + variant argument-value { + word(string), + text(string), + integer(s32), + number(f64), + boolean(bool), + player(player), + block-pos(block-pos), + } record registration { - /// Commands players may type, without the slash. A name vanilla - /// already uses is refused (vanilla's command runs). - commands: list, + /// Commands players may type. + commands: list, /// Call `tick` every server tick (20 per second). tick: bool, /// Call `player-joined` and `player-left`. @@ -190,11 +241,6 @@ interface server-events { /// Call `block-broken` and `block-placed`. blocks: bool, } - record block-pos { - x: s32, - y: s32, - z: s32, - } /// Once, after loading. An error keeps the mod off and is logged. init: func() -> result; /// Each server tick, with the server's tick counter. @@ -206,8 +252,10 @@ interface server-events { /// A chat message a player sent, as plain text. chat: func(player: player, text: string); /// `/name args` typed by `player`: ok(some(text)) is their feedback, - /// err(text) their error in red. - command: func(player: player, name: string, args: string) -> result, string>; + /// err(text) their error in red. `values` holds each argument given, by + /// name, in order (an optional one left out isn't there); a line that + /// doesn't parse never reaches the mod: the player gets vanilla's error. + command: func(player: player, name: string, args: string, values: list>) -> result, string>; /// A player broke the block at `pos` in their dimension: `state` is what /// was there, as `minecraft:oak_log[axis=y]`. block-broken: func(player: player, pos: block-pos, state: string); diff --git a/crates/horizon-mods/src/commands.rs b/crates/horizon-mods/src/commands.rs new file mode 100644 index 000000000..4421b47ba --- /dev/null +++ b/crates/horizon-mods/src/commands.rs @@ -0,0 +1,301 @@ +//! Server mods' typed commands: an argument line parsed as the command's +//! arguments say, the way vanilla's Brigadier parsers read them, with +//! vanilla's error messages. The game sends the same arguments to players' +//! command trees, so their chat box checks them before the server does. +use crate::runtime::{Argument, ArgumentKind, ArgumentValue, BlockPos, ServerPlayer}; + +/// The values of `args`, typed by `player`, for `arguments` (in order; +/// optional ones left out aren't there), or the error the player reads. +pub fn parse( + arguments: &[Argument], + args: &str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result, String> { + let mut values = Vec::new(); + let mut rest = args; + for (i, argument) in arguments.iter().enumerate() { + if i > 0 && !rest.is_empty() { + rest = rest.strip_prefix(' ').ok_or( + "Expected whitespace to end one argument, but found trailing data".to_string(), + )?; + } + if rest.is_empty() { + if argument.optional { + break; + } + return Err("Unknown or incomplete command, see below for error".into()); + } + let (value, after) = one(&argument.kind, rest, player, online)?; + values.push((argument.name.clone(), value)); + rest = after; + } + if !rest.is_empty() { + return Err("Incorrect argument for command".into()); + } + Ok(values) +} + +/// StringReader.isAllowedInUnquotedString. +fn unquoted(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+') +} + +/// The unquoted string at the start of `s`, and what follows it. +fn word(s: &str) -> (&str, &str) { + let end = s.find(|c: char| !unquoted(c)).unwrap_or(s.len()); + s.split_at(end) +} + +/// One argument from the start of `s`, and what follows it. +fn one<'a>( + kind: &ArgumentKind, + s: &'a str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result<(ArgumentValue, &'a str), String> { + Ok(match kind { + ArgumentKind::Word => { + let (w, rest) = word(s); + if w.is_empty() { + return Err("Expected string".into()); + } + (ArgumentValue::Word(w.into()), rest) + } + ArgumentKind::Text => (ArgumentValue::Text(s.into()), ""), + ArgumentKind::Integer((min, max)) => { + let (n, rest) = integer(s)?; + if let Some(min) = min.filter(|m| n < *m) { + return Err(format!("Integer must not be less than {min}, found {n}")); + } + if let Some(max) = max.filter(|m| n > *m) { + return Err(format!("Integer must not be more than {max}, found {n}")); + } + (ArgumentValue::Integer(n), rest) + } + ArgumentKind::Number => { + let (n, rest) = double(s)?; + (ArgumentValue::Number(n), rest) + } + ArgumentKind::Boolean => { + let (w, rest) = word(s); + let b = match w { + "true" => true, + "false" => false, + "" => return Err("Expected bool".into()), + _ => { + return Err(format!( + "Invalid boolean, expected 'true' or 'false' but found '{w}'" + )); + } + }; + (ArgumentValue::Boolean(b), rest) + } + ArgumentKind::Player => { + if let Some(selector) = s.strip_prefix('@') { + let (kind, rest) = word(selector); + return match kind { + // A player's @p is themselves (the nearest to where they are). + "s" | "p" => Ok((ArgumentValue::Player(player.clone()), rest)), + "a" | "e" | "r" | "n" => { + Err("Only one player is allowed, but the provided selector allows more than one".into()) + } + _ => Err(format!("Unknown selector type '@{kind}'")), + }; + } + let (name, rest) = word(s); + if name.is_empty() { + return Err("Invalid name or UUID".into()); + } + let found = online + .iter() + .find(|p| p.name.eq_ignore_ascii_case(name)) + .ok_or("No player was found")?; + (ArgumentValue::Player(found.clone()), rest) + } + ArgumentKind::BlockPos => { + let (x, rest) = coordinate(s, player.x)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (y, rest) = coordinate(rest, player.y)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (z, rest) = coordinate(rest, player.z)?; + (ArgumentValue::BlockPos(BlockPos { x, y, z }), rest) + } + }) +} + +/// StringReader.readInt. +fn integer(s: &str) -> Result<(i32, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected integer".into()); + } + let n = n.parse().map_err(|_| format!("Invalid integer '{n}'"))?; + Ok((n, rest)) +} + +/// StringReader.readDouble. +fn double(s: &str) -> Result<(f64, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected double".into()); + } + let n = n.parse().map_err(|_| format!("Invalid double '{n}'"))?; + Ok((n, rest)) +} + +/// WorldCoordinate.parseInt, then BlockPos.containing: `~` and `~n` from +/// `base`, a whole number as it is. +fn coordinate(s: &str, base: f64) -> Result<(i32, &str), String> { + if s.starts_with('^') { + return Err( + "Cannot mix world & local coordinates (everything must either use ^ or not)".into(), + ); + } + if let Some(offset) = s.strip_prefix('~') { + if offset.is_empty() || offset.starts_with(' ') { + return Ok((base.floor() as i32, offset)); + } + let (n, rest) = double(offset)?; + return Ok(((base + n).floor() as i32, rest)); + } + integer(s) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::GameMode; + + fn player(name: &str) -> ServerPlayer { + ServerPlayer { + id: format!("id-{name}"), + name: name.into(), + x: 10.7, + y: 64.0, + z: -3.2, + dimension: "minecraft:overworld".into(), + game_mode: GameMode::Survival, + health: 20.0, + } + } + fn arg(name: &str, kind: ArgumentKind, optional: bool) -> Argument { + Argument { + name: name.into(), + kind, + optional, + } + } + + #[test] + fn values_in_order_and_optional_ones_left_out() { + let alex = player("Alex"); + let online = [alex.clone(), player("Steve")]; + let args = [ + arg("who", ArgumentKind::Player, false), + arg("height", ArgumentKind::Integer((Some(1), Some(64))), true), + arg("note", ArgumentKind::Text, true), + ]; + let v = parse(&args, "steve 5 hello there", &alex, &online).unwrap(); + assert_eq!(v[0].0, "who"); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Steve")); + assert_eq!(v[1], ("height".into(), ArgumentValue::Integer(5))); + assert_eq!( + v[2], + ("note".into(), ArgumentValue::Text("hello there".into())) + ); + let v = parse(&args, "@s", &alex, &online).unwrap(); + assert_eq!(v.len(), 1); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Alex")); + } + + #[test] + fn vanilla_errors() { + let alex = player("Alex"); + let online = [alex.clone()]; + let height = [arg( + "height", + ArgumentKind::Integer((Some(1), Some(64))), + false, + )]; + let err = |a: &[Argument], s| parse(a, s, &alex, &online).unwrap_err(); + assert_eq!( + err(&height, "0"), + "Integer must not be less than 1, found 0" + ); + assert_eq!( + err(&height, "65"), + "Integer must not be more than 64, found 65" + ); + assert_eq!(err(&height, "x"), "Expected integer"); + assert_eq!(err(&height, "1.5"), "Invalid integer '1.5'"); + assert_eq!( + err(&height, ""), + "Unknown or incomplete command, see below for error" + ); + assert_eq!(err(&height, "3 4"), "Incorrect argument for command"); + let who = [arg("who", ArgumentKind::Player, false)]; + assert_eq!(err(&who, "Herobrine"), "No player was found"); + assert_eq!(err(&who, "@q"), "Unknown selector type '@q'"); + let flag = [arg("on", ArgumentKind::Boolean, false)]; + assert_eq!( + err(&flag, "yes"), + "Invalid boolean, expected 'true' or 'false' but found 'yes'" + ); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + assert_eq!(err(&pos, "1 2"), "Incomplete (expected 3 coordinates)"); + } + + #[test] + fn block_positions_relative_to_the_player() { + let alex = player("Alex"); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + let v = parse(&pos, "~ ~1 ~-0.5", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: 10, + y: 65, + z: -4 + }) + ); + let v = parse(&pos, "-5 70 ~", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: -5, + y: 70, + z: -4 + }) + ); + } + + #[test] + fn free_text_is_an_optional_text_argument() { + let alex = player("Alex"); + let free = [arg("args", ArgumentKind::Text, true)]; + assert_eq!(parse(&free, "", &alex, &[]), Ok(Vec::new())); + assert_eq!( + parse(&free, "anything at all", &alex, &[]), + Ok(vec![( + "args".into(), + ArgumentValue::Text("anything at all".into()) + )]) + ); + assert_eq!( + parse(&[], "more", &alex, &[]), + Err("Incorrect argument for command".into()) + ); + assert_eq!(parse(&[], "", &alex, &[]), Ok(Vec::new())); + } +} diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index 3c5fe74f6..d352f8c90 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -5,6 +5,8 @@ //! //! Nothing here runs unless a mod is installed and turned on: an empty //! [`Mods`] makes no engine and every hook returns at once. +#[cfg(feature = "runtime")] +pub mod commands; pub mod content; #[cfg(feature = "index")] pub mod index; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index fa0998614..f4ab5c4dd 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -43,7 +43,9 @@ use bindings::{ horizon::mods::{chat, game, hud, log as mod_log, storage}, }; pub use server_bindings::{ - exports::horizon::mods::server_events::BlockPos, + exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, ServerCommand, + }, horizon::mods::players::{GameMode, Player as ServerPlayer}, horizon::mods::world::BlockChange, }; @@ -206,10 +208,10 @@ impl Hooks { Hooks::Client(..) => None, } } - fn commands(&self) -> &[String] { + fn commands(&self) -> Vec<&str> { match self { - Hooks::Client(_, r) => &r.commands, - Hooks::Server(_, r) => &r.commands, + Hooks::Client(_, r) => r.commands.iter().map(String::as_str).collect(), + Hooks::Server(_, r) => r.commands.iter().map(|c| c.name.as_str()).collect(), } } } @@ -240,9 +242,16 @@ pub struct Mods { snapshot: Arc, out: Vec, world: WorldSlot, + /// Moves on whenever a mod starts or stops: the game resends the server + /// mods' commands to players when it changes. + generation: u64, } impl Mods { + /// Changes whenever the running mods (so their commands) change. + pub fn generation(&self) -> u64 { + self.generation + } /// Whether a running mod may use capability `world`: only then is a /// view worth lending. pub fn wants_world(&self) -> bool { @@ -371,7 +380,8 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(|r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().cloned()) + .flat_map(|r| r.hooks.commands()) + .map(str::to_owned) .collect(); let snapshot = self.snapshot.clone(); let world = self.world.clone(); @@ -423,17 +433,30 @@ impl Mods { .map_err(|e| reason(&e))??; Hooks::Client(exports, r) }; - let commands = match &mut hooks { - Hooks::Client(_, r) => &mut r.commands, - Hooks::Server(_, r) => &mut r.commands, - }; - commands.retain(|c| { - let free = !reserved(c) && !taken.contains(c); + let free = |c: &str| { + let free = !reserved(c) && !taken.iter().any(|t| t == c); if !free { log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id); } free - }); + }; + match &mut hooks { + Hooks::Client(_, r) => r.commands.retain(|c| free(c)), + Hooks::Server(_, r) => { + r.commands.retain(|c| free(&c.name)); + for c in &mut r.commands { + if let Err(e) = check_arguments(&c.arguments) { + log::warn!( + "Horizon: mod {}'s /{}: {e}; it takes free text", + m.id, + c.name + ); + c.arguments.clear(); + } + } + } + } + self.generation += 1; self.out.append(&mut store.data_mut().out); Ok(Some(Running { store, hooks })) } @@ -537,6 +560,7 @@ impl Mods { }); entry.status = Status::Failed(reason); entry.run = None; + self.generation += 1; None } } @@ -561,7 +585,7 @@ impl Mods { fn command_owner(&self, server: bool, name: &str) -> Option { self.entries.iter().position(|e| { e.run.as_ref().is_some_and(|r| { - r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name) + r.hooks.server().is_some() == server && r.hooks.commands().contains(&name) }) }) } @@ -592,7 +616,7 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(move |r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().map(String::as_str)) + .flat_map(|r| r.hooks.commands()) } /// A server tick. @@ -635,9 +659,13 @@ impl Mods { |m, s| m.call_block_placed(s, player, pos, state), ); } - /// The commands running server mods own, for the server's command tree. - pub fn server_commands(&self) -> impl Iterator { - self.owned_commands(true) + /// The commands running server mods own and their arguments, for the + /// server's command tree. + pub fn server_commands(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()?.hooks.server()) + .flat_map(|r| r.commands.iter()) } /// Runs `line` (without its slash), typed by `player`, if a server mod /// owns its command; its feedback is an [`Output::Reply`]. False when @@ -647,17 +675,31 @@ impl Mods { let Some(i) = self.command_owner(true, name) else { return false; }; - let result = self.call(i, FUEL_EVENT, |h, s| match h { - Hooks::Server(m, _) => m - .horizon_mods_server_events() - .call_command(s, player, name, args), - Hooks::Client(..) => Ok(Ok(None)), - }); let reply = |text, error| Output::Reply { player: player.id.clone(), text, error, }; + let arguments = self.entries[i] + .run + .as_ref() + .and_then(|r| r.hooks.server()) + .and_then(|r| r.commands.iter().find(|c| c.name == name)) + .map(|c| c.arguments.as_slice()) + .unwrap_or_default(); + let values = match crate::commands::parse(arguments, args, player, &self.snapshot.players) { + Ok(values) => values, + Err(e) => { + self.out.push(reply(e, true)); + return true; + } + }; + let result = self.call(i, FUEL_EVENT, |h, s| match h { + Hooks::Server(m, _) => m + .horizon_mods_server_events() + .call_command(s, player, name, args, &values), + Hooks::Client(..) => Ok(Ok(None)), + }); match result { Some(Ok(Some(text))) => self.out.push(reply(text, false)), Some(Err(text)) => self.out.push(reply(text, true)), @@ -688,6 +730,7 @@ impl Mods { continue; } any = true; + self.generation += 1; self.entries[i].modified = now; self.entries[i].run = None; let path = self.entries[i].path.clone(); @@ -713,6 +756,34 @@ impl Mods { } } +/// A command's arguments are well formed: names given and distinct, +/// optional ones last, free text only last. +fn check_arguments(arguments: &[Argument]) -> Result<(), String> { + for (i, a) in arguments.iter().enumerate() { + if a.name.is_empty() + || !a + .name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Err(format!("argument name '{}' isn't [A-Za-z0-9_]+", a.name)); + } + if arguments[..i].iter().any(|b| b.name == a.name) { + return Err(format!("two arguments are named {}", a.name)); + } + if i > 0 && arguments[i - 1].optional && !a.optional { + return Err(format!("{} is required after an optional argument", a.name)); + } + if a.kind == ArgumentKind::Text && i + 1 < arguments.len() { + return Err(format!( + "{} takes the rest of the line, so it must be last", + a.name + )); + } + } + Ok(()) +} + fn modified(path: &Path) -> Option { let meta = std::fs::metadata(path).ok()?; if meta.is_dir() { diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index 239642357..5a18d4cb8 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -250,7 +250,7 @@ impl TestGame { } /// The commands the mod registered. pub fn commands(&self) -> Vec { - let server = self.mods.server_commands(); + let server = self.mods.server_commands().map(|c| c.name.as_str()); self.mods .commands() .chain(server) diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 3647cca30..c9cd60bdc 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -446,7 +446,7 @@ fn a_server_mod_without_a_world_reads_nothing() { assert!( out.iter() .any(|o| matches!(o, Output::Reply { text, error: true, .. } - if text == "The ground under you isn't loaded")), + if text == "That block isn't loaded")), "{out:?}" ); } @@ -545,10 +545,12 @@ fn a_server_mod_runs_only_where_the_world_does() { let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give"); assert!(mods.runs_server()); - assert_eq!( - mods.server_commands().collect::>(), - ["online", "mined"] - ); + let commands: Vec<_> = mods.server_commands().map(|c| c.name.as_str()).collect(); + assert_eq!(commands, ["online", "mined"]); + // `/mined [player]`: its argument travels with it, for the command tree. + let mined = mods.server_commands().nth(1).unwrap(); + assert_eq!(mined.arguments[0].kind, horizon_mods::ArgumentKind::Player); + assert!(mined.arguments[0].optional); assert_eq!(mods.commands().count(), 0, "not the window's chat commands"); let alex = alex(); mods.set_snapshot(Snapshot { diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 3aaf29d0c..7f0beeee6 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -216,16 +216,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On `type player = player` -### record `registration` - -| Field | Type | | -| --- | --- | --- | -| `commands` | `list` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). | -| `tick` | `bool` | Call `tick` every server tick (20 per second). | -| `joins` | `bool` | Call `player-joined` and `player-left`. | -| `chat` | `bool` | Call `chat` for each chat message a player sends. | -| `blocks` | `bool` | Call `block-broken` and `block-placed`. | - ### record `block-pos` | Field | Type | | @@ -234,6 +224,59 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `y` | `s32` | | | `z` | `s32` | | +### variant `argument-kind` + +What an argument of a command takes. The server sends each command and its arguments to players' games, whose chat box completes and colours them as vanilla's; the server parses them before the mod's `command` hook gets their values. + +| Case | Payload | | +| --- | --- | --- | +| `word` | | One word: letters, digits and `_ - . +`. | +| `text` | | The rest of the line, spaces included: only last. | +| `integer` | `tuple, option>` | A whole number, within the bounds given. | +| `number` | | A number with or without decimals. | +| `boolean` | | `true` or `false`. | +| `player` | | One online player: a name, or `@s` or `@p` (whoever typed it, as vanilla picks for a player). | +| `block-pos` | | A block position: three whole numbers, each one also `~` or `~n`, relative to whoever typed it. | + +### record `argument` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Shown in the chat box's hint (``) and the key of its value. | +| `kind` | `argument-kind` | | +| `optional` | `bool` | Optional arguments come after every required one. | + +### record `server-command` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Without the slash. A name vanilla already uses is refused (vanilla's command runs). | +| `arguments` | `list` | In order; none: the command takes nothing after its name. Free text is one optional `text` argument. | + +### variant `argument-value` + +An argument's value, parsed as its kind says. + +| Case | Payload | | +| --- | --- | --- | +| `word` | `string` | | +| `text` | `string` | | +| `integer` | `s32` | | +| `number` | `f64` | | +| `boolean` | `bool` | | +| `player` | `player` | | +| `block-pos` | `block-pos` | | + +### record `registration` + +| Field | Type | | +| --- | --- | --- | +| `commands` | `list` | Commands players may type. | +| `tick` | `bool` | Call `tick` every server tick (20 per second). | +| `joins` | `bool` | Call `player-joined` and `player-left`. | +| `chat` | `bool` | Call `chat` for each chat message a player sends. | +| `blocks` | `bool` | Call `block-broken` and `block-placed`. | + | Function | Signature | What it does | | --- | --- | --- | | `init` | `func() -> result` | Once, after loading. An error keeps the mod off and is logged. | @@ -241,6 +284,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. | | `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. | | `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. | -| `command` | `func(player: player, name: string, args: string) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. | +| `command` | `func(player: player, name: string, args: string, values: list>) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. `values` holds each argument given, by name, in order (an optional one left out isn't there); a line that doesn't parse never reaches the mod: the player gets vanilla's error. | | `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. | | `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. | diff --git a/docs/api/mods.md b/docs/api/mods.md index 76075e989..6e7a87205 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -18,7 +18,7 @@ the player before the mod is turned on, and checked against the component's real | Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` | | Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` | | Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) | -| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` | +| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (6 builders), `server::Argument`, `server::Args`, `export_server_mod!` | | `cargo horizon-mod` | `new`, `build`, `run`, `test`, `check` | | Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) | @@ -84,9 +84,9 @@ release. What real mods need next, in the order modpacks and servers need it: - **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run - on the server thread, a LAN host and the dedicated server today, with joins, chat, commands, players' block - breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` does); next entity events, game rules, - server commands with typed arguments sent to clients' command trees. + on the server thread, a LAN host and the dedicated server today, with joins, chat, typed commands in players' + command trees, players' block breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` + does); next entity events, game rules, entity, item and block-state arguments. - **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities, and `world` for client mods (raycasts, single player and LAN hosts). - **Items and inventories**: the player's inventory, held item and open container; item stacks with components. @@ -102,6 +102,9 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- API 0.3: typed server commands: `registration.commands` lists each command's arguments (`argument-kind`: word, + text, integer, number, boolean, player, block-pos), sent in players' command trees and parsed by the server; + `command` gets their values. SDK `Registration::command_with`, `Argument`, `Args`. - API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and `expect.blocks`. - Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server. diff --git a/docs/mods.md b/docs/mods.md index 19b05f9ec..5d0378a34 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -475,7 +475,7 @@ its component targets the WIT world `horizon-server-mod` instead of | `tick(tick)` | each server tick | | `player-joined(player)`, `player-left(player)` | `registration.joins` | | `chat(player, text)` | `registration.chat`: each chat message a player sends | -| `command(player, name, args)` | `/name args` typed by a player, for a command it registered; `ok(some)` is that player's feedback, `err` their red error | +| `command(player, name, args, values)` | `/name args` typed by a player, for a command it registered, with its arguments' values (below); `ok(some)` is that player's feedback, `err` their red error | | `block-broken(player, pos, state)`, `block-placed(player, pos, state)` | `registration.blocks`, with the state as `minecraft:oak_log[axis=y]` | Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for @@ -484,6 +484,31 @@ horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is [`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with `world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs). +**Typed commands.** Each command in `registration.commands` lists its +arguments, in order: a name and a kind, required or optional (optional ones +last). The server adds them to the command tree every player receives, after +vanilla's commands, so a player's chat box completes and colours them as it +does vanilla's (player names, coordinates, bounds); when a player sends one, +the server parses the line the way vanilla's parsers do and gives the mod the +values, by argument name, or answers with vanilla's error (`Integer must not +be more than 64, found 65`, `No player was found`) without calling the mod. + +| Kind | Takes | Value | Chat box parser | +|---|---|---|---| +| `word` | one word: letters, digits, `_ - . +` | `word(string)` | `brigadier:string` (word) | +| `text` | the rest of the line, only last | `text(string)` | `brigadier:string` (greedy) | +| `integer(min, max)` | a whole number within the bounds given | `integer(s32)` | `brigadier:integer` | +| `number` | a number | `number(f64)` | `brigadier:double` | +| `boolean` | `true` or `false` | `boolean(bool)` | `brigadier:bool` | +| `player` | an online player's name, `@s` or `@p` (whoever typed it) | `player(player)` | `minecraft:entity` (one player) | +| `block-pos` | `x y z`, each a whole number, `~` or `~n` (from whoever typed it) | `block-pos(block-pos)` | `minecraft:block_pos` | + +A command with no arguments takes nothing after its name. In Rust, +`Registration::command_with("beacon", [Argument::integer("height", Some(1), +Some(64)).optional()])`, read with `args.integer("height")`; `command(name)` +alone takes free text, an optional `text` argument named `args` +(`args.text()` is the line as typed either way). + **Capability `world`.** Reads are of the server's loaded chunks as they are during the call: the game lends a server mod's call the levels' chunk maps (moved, not copied, and only while a running mod has `world`), so a read @@ -524,10 +549,11 @@ chat for the in-frame player and a system message for a connection; on, each of these points costs one branch (measured in the PR that added them). -**Not yet.** Clients aren't sent server mods' commands with vanilla's -command tree, so a player's chat box doesn't complete or colour them; typing -them works. Block events are a player's own breaking and placing, not -explosions, pistons or other mods. +**Not yet.** Block events are a player's own breaking and placing, not +explosions, pistons or other mods. Command arguments don't take entities, +items or block states yet, and `^` coordinates; in-frame single player's chat +box lists server mods' commands by name only (the server still parses their +arguments). ## Versions and compatibility From 574d65a03ca86775593d52472da4b1802f0a7d2a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:08:47 +0100 Subject: [PATCH 003/132] stability.md: server mods' row names world and typed commands Co-Authored-By: Claude Opus 5.5 --- docs/api/stability.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/stability.md b/docs/api/stability.md index 30d8c699c..f5b2da632 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -88,7 +88,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | --- | --- | --- | | Mod API: `log`, `game`, `chat`, `hud`, `storage`, `events` | preview | 0.1.0 | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | -| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` | +| Server mods: world `horizon-server-mod`, `players`, `server-events`, `world`, typed `server-command`s | experimental | manifest `api = "0.3"` | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | | `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 | | Shader API | not started | | From f98528bbfc49fbe1c92deef00b953623903302c8 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:46:18 +0000 Subject: [PATCH 004/132] Fix evoker fangs rendering on server clients Track fang entities and deliver their start event to the existing client renderer. Exercise warmup, animation, authoritative positions and removal in the LAN harness. Co-Authored-By: OpenAI Codex GPT-6.1 Sol --- crates/horizon-client/src/game/control.rs | 3 + crates/horizon-client/src/game/fangs.rs | 42 ++++++++-- .../horizon-client/src/game/lan_entities.rs | 3 + crates/horizon-client/src/game/remote.rs | 1 + .../src/game/remote_projectiles.rs | 10 +++ tools/lan_e2e.py | 83 +++++++++++++++++++ 6 files changed, 137 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 7a632e308..6139ccd37 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -1023,6 +1023,9 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + let mut fangs_vertices = Vec::new(); + self.fangs_geometry(glam::DVec3::ZERO, 0.5, &mut fangs_vertices); + status["fangs_vertices"] = json!(fangs_vertices.len()); status["maps"] = json!(self.maps_status()); // The particles made so far, by type. status["particles"] = json!(self.particles.made()); diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index cdf2d17a5..9aa687032 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -7,12 +7,13 @@ use std::sync::Arc; #[derive(Clone, Debug)] pub(super) struct Fangs { - pos: [f64; 3], - yaw: f32, + pub id: u32, + pub pos: [f64; 3], + pub yaw: f32, warmup: i32, - life: i32, + pub life: i32, owner: u32, - started: bool, + pub started: bool, } #[derive(Default)] pub(super) struct FangState { @@ -21,6 +22,11 @@ pub(super) struct FangState { } impl Game<'_> { pub(super) fn add_fangs(&mut self, at: [f64; 3], yaw: f32, delay: i32, owner: u32) { + self.next_entity += 1; + self.insert_fangs(self.next_entity, at, yaw, delay, owner); + } + + pub(super) fn insert_fangs(&mut self, id: u32, at: [f64; 3], yaw: f32, delay: i32, owner: u32) { if self.fangs.model.is_none() { self.fangs.model = horizon_client::mobs::load_model( &self.options.resources, @@ -29,6 +35,7 @@ impl Game<'_> { .map(Arc::new); } self.fangs.list.push(Fangs { + id, pos: at, yaw, warmup: delay, @@ -37,6 +44,30 @@ impl Game<'_> { started: false, }); } + /// `EvokerFangs.handleEntityEvent`: only event 4 starts a client attack. + pub(super) fn remote_fangs_event(&mut self, id: u32, event: i8) { + if event == 4 + && let Some(f) = self.fangs.list.iter_mut().find(|f| f.id == id) + { + f.started = true; + self.audio.play_unshared( + "minecraft:entity.evoker_fangs.attack", + Some(f.pos), + 1.0, + 1.0, + ); + } + } + + /// `EvokerFangs.tick`: clients only advance animation, never damage or discard. + pub(super) fn tick_remote_fangs(&mut self) { + for f in &mut self.fangs.list { + if f.started { + f.life -= 1; + } + } + } + /// `EvokerFangs.tick`. pub(super) fn tick_fangs(&mut self) { let mut list = std::mem::take(&mut self.fangs.list); @@ -50,7 +81,8 @@ impl Game<'_> { } if !f.started { f.started = true; - self.audio.play( + self.lan_entity_event(f.id as i32, 4, f.pos); + self.audio.play_unshared( "minecraft:entity.evoker_fangs.attack", Some(f.pos), 1.0, diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cd4ba2fb8..a389e6a99 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -290,6 +290,9 @@ impl Game<'_> { None => 0, }; let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z]; + for f in &self.fangs.list { + out.push(state(f.id, "minecraft:evoker_fangs", f.pos, f.yaw, false)); + } // LightningBolt: each client draws and flashes its own. for b in self.bolts.iter().filter(|b| b.id != 0) { out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false)); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 20c307720..88f36bdf2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2050,6 +2050,7 @@ impl Game<'_> { } } C::EntityEvent(p) => { + self.remote_fangs_event(p.id as u32, p.event); // LocalPlayer.setPermissions also refreshes an open World Options screen. if (24..=28).contains(&p.event) && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 2ba4510ea..f033c5a8b 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -54,6 +54,7 @@ impl Game<'_> { let (yaw, pitch) = rotation; self.remove_remote_projectile(id); match kind { + "minecraft:evoker_fangs" => self.insert_fangs(id, position, yaw, 0, 0), "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { id, position: at, @@ -220,6 +221,7 @@ impl Game<'_> { /// One tick of interpolation, as `tick_remote_objects`. pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + self.tick_remote_fangs(); // PrimedTnt.tick runs on a client too: it falls, bounces and burns its // fuse down (the swell and flash follow it) between the server's // updates (every 10 ticks), and a client discards it when the fuse @@ -311,6 +313,7 @@ impl Game<'_> { } pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.fangs.list.retain(|f| f.id != id); self.tnts.retain(|t| t.id != id); self.falling.retain(|f| f.id != id); self.creatures.projectiles.retain(|p| p.id != id); @@ -324,6 +327,7 @@ impl Game<'_> { /// Every one a server sent (a new connection, level or dimension). pub(super) fn clear_remote_projectiles(&mut self) { + self.fangs.list.clear(); self.tnts.clear(); self.falling.clear(); self.creatures.projectiles.clear(); @@ -340,6 +344,12 @@ impl Game<'_> { use serde_json::json; let at = |p: Vec3| [p.x, p.y, p.z]; let mut out = Vec::new(); + for f in &self.fangs.list { + out.push( + json!({"id": f.id, "kind": "minecraft:evoker_fangs", "position": f.pos, + "yaw": f.yaw, "started": f.started, "life": f.life}), + ); + } for t in &self.tnts { out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 804add98a..b4a89eb1d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6591,5 +6591,88 @@ CHECKS += ['replant'] CHECK_FNS['replant'] = check_replant + +def check_fangs(host, guest, out): + """EvokerFangs: authoritative spawn, event 4, client animation and server removal (#1482).""" + x, y, z = (int(v // 1) for v in pos_of(host)) + tag = 'lan_evoker_fangs' + selector = f'@e[type=minecraft:evoker,tag={tag},limit=1]' + paths = {g.name: {} for g in (host, guest)} + warmup = dict.fromkeys(paths, False) + drawn = dict.fromkeys(paths, False) + stopped = False + photographed = False + + def fangs(status): + return [p for p in status['projectiles'] if p['kind'] == 'minecraft:evoker_fangs'] + + try: + host('command', command='difficulty normal') + host('command', command='gamemode creative') + guest('command', command='gamemode survival') + guest('command', command='effect give @s minecraft:resistance 120 4 true') + host('command', command=f'fill {x - 10} {y - 1} {z - 10} {x + 10} {y - 1} {z + 18} minecraft:stone') + host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 8} {z + 18} minecraft:air') + host('command', command=f'tp @s {x + 4.5} {y} {z - 2.5}') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + guest.wait(10) + host('command', command=f'summon minecraft:evoker {x + 0.5} {y} {z + 9.5} ' + f'{{PersistenceRequired:1b,Tags:["{tag}"]}}') + for game in (host, guest): + game.raw('look-at', x + 0.5, y + 0.5, z + 5.5) + for _ in range(200): + guest.wait(2) + statuses = {g.name: g('status') for g in (host, guest)} + for name, status in statuses.items(): + live = fangs(status) + ids = [f['id'] for f in live] + assert all(ids) and len(ids) == len(set(ids)), f'{name}: invalid fang ids {ids}' + warmup[name] |= any(not f['started'] for f in live) + drawn[name] |= status['fangs_vertices'] > 0 + for f in live: + paths[name].setdefault(f['id'], []).append(f) + if paths['host'] and not stopped: + host('command', command=f'data merge entity {selector} {{NoAI:1b}}') + stopped = True + if (all(drawn.values()) and not photographed + and any(f['started'] and 8 <= f['life'] <= 16 + for f in fangs(statuses['guest']))): + host('command', command='tick freeze') + try: + for game in (host, guest): + game.raw('key', 'f1', 'tap') + try: + game.shot(out, 'evoker-fangs') + finally: + game.raw('key', 'f1', 'tap') + finally: + host('command', command='tick unfreeze') + photographed = True + if stopped and not any(fangs(s) for s in statuses.values()): + break + lab.write_json(out / 'evoker-fangs.json', {'paths': paths, 'warmup': warmup, 'drawn': drawn}) + assert all(warmup.values()), f'fang warmup not received: {warmup}' + assert all(drawn.values()), f'fang renderer produced no geometry: {drawn}' + assert paths['host'].keys() == paths['guest'].keys(), 'clients received different fang ids' + for id, samples in paths['host'].items(): + other = paths['guest'][id] + assert all(f['position'] == samples[0]['position'] for f in samples + other), \ + f'fang {id} is not at its authoritative position' + for name, frames in (('host', samples), ('guest', other)): + life = {f['life'] for f in frames if f['started']} + assert len(life) > 1, f'{name}: fang {id} did not animate: {frames}' + assert not any(fangs(g('status')) for g in (host, guest)), 'fangs survived server removal' + finally: + host('command', command='tick unfreeze') + host('command', command=f'kill @e[tag={tag}]') + guest('command', command='effect clear @s') + face_each_other(host, guest) + return {'fangs': len(paths['host']), 'warmup': warmup, 'drawn': drawn, 'removed': True} + + +CHECKS += ['fangs'] +CHECK_FNS.update(fangs=check_fangs) + + if __name__ == '__main__': main() From ebf3c1567cf408783e6adc08d76106b30fb82f20 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:34:31 +0100 Subject: [PATCH 005/132] parity: follow code into new crates when choosing harnesses Two changes so `parity.py --changed` keeps picking the right harnesses once code moves into a crate of its own: - A harness recorded before the move names the old paths. A changed Rust file of a crate the recorded crates link (their path dependencies, transitively) but don't name now counts, and the reach search decides. Before, such a file matched no record and selected nothing. - A library's root opens once reached code names the crate (`horizon_world::`, `pub use horizon_command as command`), instead of always. Every crate root was open, so any item of a new crate whose name matched a name used anywhere counted. On main the selection is the same for 15 of 16 sampled files; for horizon-world/src/nbt.rs one harness that reached it only through a name match drops out. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_reach.py | 20 +++++++++++++++++ tools/parity.py | 2 +- tools/parity_reach.py | 45 +++++++++++++++++++++++++++++++++----- 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/tests/test_parity_reach.py b/tests/test_parity_reach.py index 07e3df9e3..0e20f9174 100644 --- a/tests/test_parity_reach.py +++ b/tests/test_parity_reach.py @@ -111,6 +111,26 @@ class ReachTests(unittest.TestCase): self.assertIn("crates/a/src/display.rs", full) self.assertTrue(graph.results) + def test_a_module_moved_to_a_new_crate_counts_through_its_reexport(self): + # used.rs moves to crate b after the harness was recorded; a re-exports it under its old path. Crate c is + # a dependency nothing reached names: its items stay out even where their names match. + (self.root / "crates/a/src/used.rs").unlink() + workspace(self.root, { + "crates/a/Cargo.toml": (self.root / "crates/a/Cargo.toml").read_text() + + '\n[dependencies]\nb = { path = "../b" }\nc = { path = "../c" }\n', + "crates/a/src/lib.rs": "pub use b::used;\npub mod unused;\nmod methods;\nmod display;\n", + "crates/b/Cargo.toml": '[package]\nname = "b"\n', + "crates/b/src/lib.rs": "pub mod used;\n", + "crates/b/src/used.rs": "pub struct Thing;\npub fn helper() -> u32 { 1 }\n", + "crates/c/Cargo.toml": '[package]\nname = "c"\n', + "crates/c/src/lib.rs": "pub fn helper() -> u32 { 3 }\n", + }) + changed = {"crates/b/src/used.rs", "crates/c/src/lib.rs"} + self.assertEqual(parity_reach.unrecorded(self.root, self.dependencies, changed), changed) + kept = self.narrowed(changed=changed) + self.assertIn("crates/b/src/used.rs", kept) + self.assertNotIn("crates/c/src/lib.rs", kept) + def test_unknown_probes_keep_everything(self): self.assertEqual(set(self.narrowed(artifacts=[])), set(self.dependencies)) self.assertEqual(set(self.narrowed(artifacts=[["example", "missing", "release", ["-p", "a"], True]])), diff --git a/tools/parity.py b/tools/parity.py index dbff8c146..6cc61cfb4 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -1274,7 +1274,7 @@ def affected_harnesses(found, records, changed, reach=True, base=None): affected.add(name) continue plain = {path.split(KEEP)[0] for path in dependencies} - hit = plain & changed + hit = (plain & changed) | parity_reach.unrecorded(ROOT, plain, changed) if not hit: continue if graph is None or any(not path.startswith("crates/") for path in hit): diff --git a/tools/parity_reach.py b/tools/parity_reach.py index dc61f6215..b5be2a192 100644 --- a/tools/parity_reach.py +++ b/tools/parity_reach.py @@ -7,8 +7,8 @@ of the workspace's current sources whose nodes are items: - everything in an entry is reached, and so is everything in a Rust file the module tree doesn't place (an `include!`d source); -- a module is open when it is a crate root, holds reached code, or is named in a path (`name::`, `use ...name`) by - reached code while its parent is open; +- a module is open when it holds reached code, or is named in a path (`name::`, `use ...name`) by reached code while + its parent is open; a library's root once reached code names its crate (`horizon_world`); - a free item (fn, struct, enum, union, trait, type, const, static, an item-level macro call's items) is reached when reached code in its own module or below it mentions its name, or when its module is open and reached code names it in a path or an import, or when its module is glob-imported (`use m::*`) and its name is mentioned; @@ -608,8 +608,8 @@ class SourceGraph: try: for path in universe: - if path.endswith("/src/lib.rs") or path in entries or path not in self.parent: - open_module(path, "crate root or entry") + if path in entries or path not in self.parent and not path.endswith("/src/lib.rs"): + open_module(path, "entry, or a file no module places") for node in seeds: reach(node, "entry" if node[0] in entries else "always counted") for path in entries & universe: @@ -624,6 +624,12 @@ class SourceGraph: label = (item.get("names") or [item["kind"]])[0] if member is None else item["members"][member]["name"] source = sets_of(node, item) why = f"{path} ({label})" + # A library's root opens once reached code names the crate (`horizon_world::`, `use horizon_command + # as command`): its items are out of reach until then. + for word in (source["mentions"] | source["paths"]) & idents.keys(): + root = f"crates/{idents[word]}/src/lib.rs" + if root in universe and root not in opened: + open_module(root, f"{why} names {word}") # Plain mentions reach items of this file and of the modules above it. ancestor, new = path, source["mentions"] while ancestor is not None and new: @@ -709,6 +715,35 @@ def is_workspace_rust(path): return path.startswith("crates/") and path.endswith(".rs") and path.count("/") >= 2 +PATH_DEPENDENCY = re.compile(r'path\s*=\s*"\.\./([\w-]+)"') + + +@functools.cache +def _path_dependencies(root, crate): + manifest = Path(root) / "crates" / crate / "Cargo.toml" + text = manifest.read_text(encoding="utf-8") if manifest.is_file() else "" + return frozenset(PATH_DEPENDENCY.findall(text)) + + +def linked_crates(root, crates): + """The workspace crates (folders under crates/) that crates link, themselves included: their path dependencies, + transitively. A harness recorded before code moved to a new crate links that crate without naming its files.""" + found, queue = set(crates), list(crates) + while queue: + for dependency in _path_dependencies(str(root), queue.pop()): + if dependency not in found: + found.add(dependency) + queue.append(dependency) + return found + + +def unrecorded(root, plain, changed): + """Changed workspace Rust files of crates a harness's recorded crates link but its record doesn't name.""" + crates = {crate_of(path) for path in plain if path.startswith("crates/") and path.count("/") >= 2} + linked = linked_crates(root, crates) - crates + return {path for path in changed if is_workspace_rust(path) and crate_of(path) in linked} + + DECLARATION_LINE = re.compile(rf"\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+({IDENT})\s*;") @@ -758,7 +793,7 @@ def narrow(dependencies, artifacts, graph, changed=(), stop=frozenset()): plain = [dependency.split("#keep:")[0] for dependency in dependencies] crates = {crate_of(path) for path in plain if path.startswith("crates/") and path.count("/") >= 2} rust = {path for path in plain if is_workspace_rust(path)} - added = {path for path in changed if is_workspace_rust(path) and crate_of(path) in crates + added = {path for path in changed if is_workspace_rust(path) and crate_of(path) in linked_crates(graph.root, crates) and path not in rust and (graph.root / path).is_file()} entries = graph.entries(artifacts, rust) if entries is None: From 0a116d95234f09d1cd5867a0ee371e097e37ed5a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:34:31 +0100 Subject: [PATCH 006/132] Split horizon-command and horizon-client-core out of horizon-client A pure move, the first slice of splitting the client lib into crates: - horizon-command: the command/ module (Brigadier port, vanilla tree, argument types, selectors), as is. - horizon-client-core: what command needs from the lib, with no other dependency inside it: text, lang, snbt, nbt_path, component, scoreboard, bossbar, gamerules, block_entity_nbt, fastutil_order; plus items moved out of lib modules that sit in the cycle, unchanged: ParticleType (particles.rs), the key display name (keybinds.rs), SOUND_SOURCES (settings.rs), uuid_text/uuid_from_text (save.rs), Registries/RegistryIds and parse_identifier (command/args.rs). horizon-client re-exports every module and item under its old path (`horizon_client::text`, `crate::command::Registries`, `particles::ParticleType`...), so no caller changes. Inside the moved files only paths changed (`crate::snbt` -> `horizon_client_core::snbt` in command, `crate::command::args::parse_identifier` -> `crate::identifier::parse_identifier`...), `sign_side` became pub, lang.rs includes the lang files from horizon-client's assets, and gamerules' test that saves a Level moved to save.rs (it needs the client's save). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +- Cargo.lock | 19 ++ Cargo.toml | 2 +- crates/horizon-client-core/Cargo.toml | 14 + .../src/block_entity_nbt.rs | 2 +- .../src/bossbar.rs | 0 .../src/component.rs | 2 +- .../src/fastutil_order.rs | 0 .../src/gamerules.rs | 23 -- crates/horizon-client-core/src/identifier.rs | 18 ++ crates/horizon-client-core/src/key_display.rs | 38 +++ .../src/lang.rs | 8 +- crates/horizon-client-core/src/lib.rs | 23 ++ .../src/nbt_path.rs | 0 .../horizon-client-core/src/particle_type.rs | 209 +++++++++++++++ crates/horizon-client-core/src/registries.rs | 188 +++++++++++++ .../src/scoreboard.rs | 4 +- .../src/snbt.rs | 0 .../horizon-client-core/src/sound_source.rs | 7 + .../src/text.rs | 2 +- crates/horizon-client-core/src/uuid.rs | 24 ++ crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/keybinds.rs | 36 +-- crates/horizon-client/src/lib.rs | 24 +- crates/horizon-client/src/particles.rs | 207 +-------------- crates/horizon-client/src/save.rs | 47 ++-- crates/horizon-client/src/settings.rs | 6 +- crates/horizon-command/Cargo.toml | 15 ++ .../command => horizon-command/src}/args.rs | 248 ++---------------- .../command => horizon-command/src}/block.rs | 0 .../command => horizon-command/src}/codec.rs | 2 +- .../src}/component.rs | 4 +- .../command => horizon-command/src}/item.rs | 4 +- .../mod.rs => horizon-command/src/lib.rs} | 9 +- .../src}/network.rs | 0 .../src}/packrat.rs | 2 +- .../src}/selector.rs | 6 +- .../command => horizon-command/src}/snbt.rs | 0 .../command => horizon-command/src}/tests.rs | 0 .../src}/tree_data.rs | 0 .../src}/tree_execute.rs | 0 .../src}/tree_extra.rs | 0 .../src}/tree_misc.rs | 4 +- .../src}/tree_scoreboard.rs | 0 .../src}/tree_world.rs | 2 +- .../src}/vanilla.rs | 2 +- .../src}/vanilla_order.rs | 0 docs/architecture.md | 11 +- docs/version-ports.md | 2 +- tools/generate_command_order.py | 4 +- tools/port_regen.py | 2 +- tools/port_report.py | 2 +- tools/test_lore_tooltip_parity.py | 4 +- tools/test_resource_pack_parity.py | 2 +- 54 files changed, 678 insertions(+), 562 deletions(-) create mode 100644 crates/horizon-client-core/Cargo.toml rename crates/{horizon-client => horizon-client-core}/src/block_entity_nbt.rs (99%) rename crates/{horizon-client => horizon-client-core}/src/bossbar.rs (100%) rename crates/{horizon-client => horizon-client-core}/src/component.rs (99%) rename crates/{horizon-client => horizon-client-core}/src/fastutil_order.rs (100%) rename crates/{horizon-client => horizon-client-core}/src/gamerules.rs (90%) create mode 100644 crates/horizon-client-core/src/identifier.rs create mode 100644 crates/horizon-client-core/src/key_display.rs rename crates/{horizon-client => horizon-client-core}/src/lang.rs (96%) create mode 100644 crates/horizon-client-core/src/lib.rs rename crates/{horizon-client => horizon-client-core}/src/nbt_path.rs (100%) create mode 100644 crates/horizon-client-core/src/particle_type.rs create mode 100644 crates/horizon-client-core/src/registries.rs rename crates/{horizon-client => horizon-client-core}/src/scoreboard.rs (99%) rename crates/{horizon-client => horizon-client-core}/src/snbt.rs (100%) create mode 100644 crates/horizon-client-core/src/sound_source.rs rename crates/{horizon-client => horizon-client-core}/src/text.rs (99%) create mode 100644 crates/horizon-client-core/src/uuid.rs create mode 100644 crates/horizon-command/Cargo.toml rename crates/{horizon-client/src/command => horizon-command/src}/args.rs (87%) rename crates/{horizon-client/src/command => horizon-command/src}/block.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/codec.rs (99%) rename crates/{horizon-client/src/command => horizon-command/src}/component.rs (98%) rename crates/{horizon-client/src/command => horizon-command/src}/item.rs (99%) rename crates/{horizon-client/src/command/mod.rs => horizon-command/src/lib.rs} (99%) rename crates/{horizon-client/src/command => horizon-command/src}/network.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/packrat.rs (99%) rename crates/{horizon-client/src/command => horizon-command/src}/selector.rs (99%) rename crates/{horizon-client/src/command => horizon-command/src}/snbt.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/tests.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/tree_data.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/tree_execute.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/tree_extra.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/tree_misc.rs (99%) rename crates/{horizon-client/src/command => horizon-command/src}/tree_scoreboard.rs (100%) rename crates/{horizon-client/src/command => horizon-command/src}/tree_world.rs (99%) rename crates/{horizon-client/src/command => horizon-command/src}/vanilla.rs (99%) rename crates/{horizon-client/src/command => horizon-command/src}/vanilla_order.rs (100%) diff --git a/AGENTS.md b/AGENTS.md index dcd4ca595..24dc38b8e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,9 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se | Crate | Owns | |---|---| -| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-client` | The game: a lib (`src/lib.rs`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` | +| `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) | | `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | | `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) | | `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` | @@ -117,16 +119,16 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end | Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | | Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | | Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | -| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` | +| Commands | parse: crate `horizon-command` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`; `horizon-client-core`: `nbt_path.rs`, `scoreboard.rs`; G: `functions.rs`, `command_blocks.rs` | | UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | | Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) | | LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) | | Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` | | Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` | -| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | +| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | | Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | | Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` | -| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` | +| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`; `horizon-client-core/src/lang.rs`; crate `horizon-assets`; G: `packs.rs` | | Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | | Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` | | Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` | diff --git a/Cargo.lock b/Cargo.lock index 0e93bba0e..1d3b52a3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,6 +1365,8 @@ dependencies = [ "glam", "horizon-assets", "horizon-bench", + "horizon-client-core", + "horizon-command", "horizon-core", "horizon-dualsense", "horizon-friends", @@ -1395,6 +1397,23 @@ dependencies = [ "zip", ] +[[package]] +name = "horizon-client-core" +version = "0.1.0" +dependencies = [ + "horizon-world", + "serde_json", +] + +[[package]] +name = "horizon-command" +version = "0.1.0" +dependencies = [ + "horizon-client-core", + "horizon-protocol", + "horizon-world", +] + [[package]] name = "horizon-core" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index e4628f962..181ab1832 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", "crates/horizon-command", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client-core/Cargo.toml b/crates/horizon-client-core/Cargo.toml new file mode 100644 index 000000000..8809a5216 --- /dev/null +++ b/crates/horizon-client-core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "horizon-client-core" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "The client's lowest layer: chat text and translations, SNBT and NBT paths, the scoreboard, boss bars, game rules and the registry and particle tables commands name" + +[dependencies] +horizon-world = { path = "../horizon-world" } +serde_json = { version = "1.0.151", features = ["raw_value"] } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client-core/src/block_entity_nbt.rs similarity index 99% rename from crates/horizon-client/src/block_entity_nbt.rs rename to crates/horizon-client-core/src/block_entity_nbt.rs index 54d230eb4..93f290515 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client-core/src/block_entity_nbt.rs @@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool { matches!(tag, Tag::IntArray(v) if v.len() == 3) } /// The loaded `SignText` of one side, or the empty text. -pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag { +pub fn sign_side(tag: Option<&Tag>) -> Tag { let empty = || string(""); let mut messages: Vec = match tag.and_then(|t| t.get("messages")) { Some(Tag::List(list)) => list.iter().filter_map(component).collect(), diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client-core/src/bossbar.rs similarity index 100% rename from crates/horizon-client/src/bossbar.rs rename to crates/horizon-client-core/src/bossbar.rs diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client-core/src/component.rs similarity index 99% rename from crates/horizon-client/src/component.rs rename to crates/horizon-client-core/src/component.rs index fced49898..5b828b305 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -252,7 +252,7 @@ pub fn to_text_with( } else if let Some(sel) = o.get("selector").and_then(Value::as_str) { resolve(sel) } else if let Some(key) = o.get("keybind").and_then(Value::as_str) { - crate::keybinds::display_name(key) + crate::key_display::display_name(key) } else { Text::empty() }; diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client-core/src/fastutil_order.rs similarity index 100% rename from crates/horizon-client/src/fastutil_order.rs rename to crates/horizon-client-core/src/fastutil_order.rs diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client-core/src/gamerules.rs similarity index 90% rename from crates/horizon-client/src/gamerules.rs rename to crates/horizon-client-core/src/gamerules.rs index 7198fd202..6715e01ec 100644 --- a/crates/horizon-client/src/gamerules.rs +++ b/crates/horizon-client-core/src/gamerules.rs @@ -292,27 +292,4 @@ mod tests { assert_eq!(GameRules::load(&dir), rules); let _ = fs::remove_dir_all(dir); } - /// The world's save (Level.write) writes the rules as they are now, and a - /// world opened again reads them back (#74). - #[test] - fn level_save_keeps_changed_rules() { - let dir = - std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - let mut level = crate::save::Level::default(); - level.write(&dir).unwrap(); - // Rules changed while playing, then saved and loaded again. - let mut rules = GameRules::load(&dir); - assert_eq!(rules, GameRules::default()); - assert!(rules.set("advance_time", Value::Bool(false))); - assert!(rules.set("advance_weather", Value::Bool(false))); - assert!(rules.set("random_tick_speed", Value::Int(0))); - level.game_rules = rules.by_name(); - level.write(&dir).unwrap(); - assert_eq!(GameRules::load(&dir), rules); - let read = crate::save::Level::read(&dir).unwrap(); - assert_eq!(read.game_rules, rules.by_name()); - assert_eq!(read.game_rule("advance_time"), 0); - let _ = fs::remove_dir_all(dir); - } } diff --git a/crates/horizon-client-core/src/identifier.rs b/crates/horizon-client-core/src/identifier.rs new file mode 100644 index 000000000..1e76f7731 --- /dev/null +++ b/crates/horizon-client-core/src/identifier.rs @@ -0,0 +1,18 @@ +//! Resource identifiers (`Identifier`). + +/// Identifier.parse: `ns:path` or `path`, validated. +pub fn parse_identifier(raw: &str) -> Option { + let (ns, path) = match raw.split_once(':') { + Some(("", path)) => ("minecraft", path), + Some((ns, path)) => (ns, path), + None => ("minecraft", raw), + }; + let ns_ok = ns != ".." + && ns + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); + (ns_ok && path_ok).then(|| format!("{ns}:{path}")) +} diff --git a/crates/horizon-client-core/src/key_display.rs b/crates/horizon-client-core/src/key_display.rs new file mode 100644 index 000000000..fc57c97bd --- /dev/null +++ b/crates/horizon-client-core/src/key_display.rs @@ -0,0 +1,38 @@ +//! Key display names (`InputConstants.Key.getDisplayName`), shared by key +//! mappings and `keybind` text components. +use crate::text::Text; + +/// InputConstants.Key.getDisplayName: one-character keys as the upper-case +/// character, others by translation. +pub fn display_name(key: &str) -> Text { + if let Some(rest) = key.strip_prefix("key.keyboard.") + && rest.chars().count() == 1 + { + let c = rest.to_uppercase(); + return Text::literal(c); + } + let symbol = match key { + "key.keyboard.minus" => Some("-"), + "key.keyboard.equal" => Some("="), + "key.keyboard.left.bracket" => Some("["), + "key.keyboard.right.bracket" => Some("]"), + "key.keyboard.backslash" => Some("\\"), + "key.keyboard.semicolon" => Some(";"), + "key.keyboard.apostrophe" => Some("'"), + "key.keyboard.grave.accent" => Some("`"), + "key.keyboard.comma" => Some(","), + "key.keyboard.period" => Some("."), + "key.keyboard.slash" => Some("/"), + _ => None, + }; + if let Some(s) = symbol { + return Text::literal(s); + } + if let Some(n) = key.strip_prefix("key.mouse.") + && n.parse::().is_ok() + && !crate::lang::has(key) + { + return Text::translate("key.mouse", &[Text::literal(n)]); + } + Text::translate(key, &[]) +} diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client-core/src/lang.rs similarity index 96% rename from crates/horizon-client/src/lang.rs rename to crates/horizon-client-core/src/lang.rs index cb96cc373..6213cedc8 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client-core/src/lang.rs @@ -42,8 +42,12 @@ struct Bundled; impl ResourceSource for Bundled { fn read(&self, path: &str) -> Option> { let body = match path { - "assets/horizon/lang/en_us.json" => include_str!("../assets/horizon/lang/en_us.json"), - "assets/horizon/lang/ru_ru.json" => include_str!("../assets/horizon/lang/ru_ru.json"), + "assets/horizon/lang/en_us.json" => { + include_str!("../../horizon-client/assets/horizon/lang/en_us.json") + } + "assets/horizon/lang/ru_ru.json" => { + include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json") + } _ => return None, }; Some(body.as_bytes().to_vec()) diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs new file mode 100644 index 000000000..ca40141d1 --- /dev/null +++ b/crates/horizon-client-core/src/lib.rs @@ -0,0 +1,23 @@ +//! The client's lowest layer, below commands and gameplay: chat text and +//! translations, SNBT and NBT paths, text components, the scoreboard, boss +//! bars, game rules, block entity NBT tables, and the registry, particle and +//! sound source tables commands name. horizon-client re-exports each module +//! under its old path (`horizon_client::text`, ...). +#![forbid(unsafe_code)] +pub mod block_entity_nbt; +pub mod bossbar; +pub mod component; +pub mod fastutil_order; +pub mod gamerules; +pub mod identifier; +pub mod key_display; +pub mod lang; +pub mod nbt_path; +pub mod particle_type; +pub mod registries; +pub mod scoreboard; +pub mod snbt; +pub mod sound_source; +pub mod text; +pub mod uuid; +pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/nbt_path.rs b/crates/horizon-client-core/src/nbt_path.rs similarity index 100% rename from crates/horizon-client/src/nbt_path.rs rename to crates/horizon-client-core/src/nbt_path.rs diff --git a/crates/horizon-client-core/src/particle_type.rs b/crates/horizon-client-core/src/particle_type.rs new file mode 100644 index 000000000..98de2380b --- /dev/null +++ b/crates/horizon-client-core/src/particle_type.rs @@ -0,0 +1,209 @@ +//! Particle types (`ParticleTypes`): the vanilla particle types with a client +//! implementation, by registry name, and their per-type flags. + +macro_rules! particle_types { + ($($variant:ident = $name:literal),* $(,)?) => { + /// Vanilla particle types with a client implementation here. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum ParticleType { $($variant),* } + impl ParticleType { + pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; + /// Registry path (`minecraft:`), also the sprite-set file name. + pub fn name(self) -> &'static str { + match self { $(ParticleType::$variant => $name),* } + } + pub fn from_name(name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + match name { $($name => Some(ParticleType::$variant),)* _ => None } + } + } + }; +} +particle_types! { + Block = "block", + BlockCrumble = "block_crumble", + Trail = "trail", + DustPillar = "dust_pillar", + FallingDust = "falling_dust", + Smoke = "smoke", + LargeSmoke = "large_smoke", + WhiteSmoke = "white_smoke", + Flame = "flame", + SoulFireFlame = "soul_fire_flame", + CopperFireFlame = "copper_fire_flame", + SmallFlame = "small_flame", + Lava = "lava", + DrippingWater = "dripping_water", + FallingWater = "falling_water", + DrippingLava = "dripping_lava", + FallingLava = "falling_lava", + LandingLava = "landing_lava", + DrippingHoney = "dripping_honey", + FallingHoney = "falling_honey", + LandingHoney = "landing_honey", + FallingNectar = "falling_nectar", + FallingSporeBlossom = "falling_spore_blossom", + SporeBlossomAir = "spore_blossom_air", + DrippingObsidianTear = "dripping_obsidian_tear", + FallingObsidianTear = "falling_obsidian_tear", + LandingObsidianTear = "landing_obsidian_tear", + DrippingDripstoneWater = "dripping_dripstone_water", + FallingDripstoneWater = "falling_dripstone_water", + DrippingDripstoneLava = "dripping_dripstone_lava", + FallingDripstoneLava = "falling_dripstone_lava", + Splash = "splash", + Rain = "rain", + Bubble = "bubble", + SulfurBubbles = "sulfur_bubbles", + BubblePop = "bubble_pop", + BubbleColumnUp = "bubble_column_up", + CurrentDown = "current_down", + Underwater = "underwater", + Portal = "portal", + ReversePortal = "reverse_portal", + Enchant = "enchant", + Nautilus = "nautilus", + VaultConnection = "vault_connection", + Crit = "crit", + EnchantedHit = "enchanted_hit", + DamageIndicator = "damage_indicator", + Heart = "heart", + AngryVillager = "angry_villager", + HappyVillager = "happy_villager", + Composter = "composter", + Mycelium = "mycelium", + Dolphin = "dolphin", + EggCrack = "egg_crack", + Poof = "poof", + Explosion = "explosion", + ExplosionEmitter = "explosion_emitter", + CampfireCosySmoke = "campfire_cosy_smoke", + CampfireSignalSmoke = "campfire_signal_smoke", + Note = "note", + Dust = "dust", + TotemOfUndying = "totem_of_undying", + Firework = "firework", + EndRod = "end_rod", + Ash = "ash", + WhiteAsh = "white_ash", + CrimsonSpore = "crimson_spore", + WarpedSpore = "warped_spore", + CherryLeaves = "cherry_leaves", + PaleOakLeaves = "pale_oak_leaves", + TintedLeaves = "tinted_leaves", + Effect = "effect", + InstantEffect = "instant_effect", + EntityEffect = "entity_effect", + Witch = "witch", + Infested = "infested", + Cloud = "cloud", + Sneeze = "sneeze", + Snowflake = "snowflake", + Soul = "soul", + SculkSoul = "sculk_soul", + DragonBreath = "dragon_breath", + Gust = "gust", + SmallGust = "small_gust", + GustEmitterLarge = "gust_emitter_large", + GustEmitterSmall = "gust_emitter_small", + DustColorTransition = "dust_color_transition", + SculkCharge = "sculk_charge", + SculkChargePop = "sculk_charge_pop", + Shriek = "shriek", + SonicBoom = "sonic_boom", + Vibration = "vibration", + SweepAttack = "sweep_attack", + Glow = "glow", + WaxOn = "wax_on", + WaxOff = "wax_off", + ElectricSpark = "electric_spark", + Scrape = "scrape", + SquidInk = "squid_ink", + GlowSquidInk = "glow_squid_ink", + Item = "item", + ItemSlime = "item_slime", + ItemSnowball = "item_snowball", + ItemCobweb = "item_cobweb", + SulfurCubeGoo = "sulfur_cube_goo", + Flash = "flash", + Firefly = "firefly", + TrialSpawnerDetection = "trial_spawner_detection", + TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", + TrialOmen = "trial_omen", + RaidOmen = "raid_omen", + OminousSpawning = "ominous_spawning", + Spit = "spit", + Fishing = "fishing", + DustPlume = "dust_plume", + RedPoplarLeaves = "red_poplar_leaves", + OrangePoplarLeaves = "orange_poplar_leaves", + YellowPoplarLeaves = "yellow_poplar_leaves", + PauseMobGrowth = "pause_mob_growth", + ResetMobGrowth = "reset_mob_growth", + BlockMarker = "block_marker", +} +impl ParticleType { + /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): + /// spawned regardless of distance. + pub fn override_limiter(self) -> bool { + matches!( + self, + Self::BlockMarker + | Self::DamageIndicator + | Self::ExplosionEmitter + | Self::Explosion + | Self::Gust + | Self::GustEmitterLarge + | Self::GustEmitterSmall + | Self::SonicBoom + | Self::SculkCharge + | Self::SculkChargePop + | Self::Vibration + | Self::Poof + | Self::Spit + | Self::SquidInk + | Self::SweepAttack + | Self::CampfireCosySmoke + | Self::CampfireSignalSmoke + | Self::GlowSquidInk + | Self::Glow + | Self::WaxOn + | Self::WaxOff + | Self::ElectricSpark + | Self::Scrape + | Self::TrialSpawnerDetection + | Self::TrialSpawnerDetectionOminous + | Self::VaultConnection + | Self::OminousSpawning + ) + } + /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class + /// hardcodes the translucent layer, drawn after translucent terrain. + /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their + /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` + /// sprite set on the engine. + pub fn translucent_layer(self) -> bool { + match self { + // CampfireSmokeParticle. + Self::CampfireCosySmoke | Self::CampfireSignalSmoke + // PlayerCloudParticle. + | Self::Cloud | Self::Sneeze + // SpellParticle. + | Self::Effect | Self::InstantEffect | Self::EntityEffect + | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen + // EmissiveRisingParticle. + | Self::Soul | Self::SculkSoul + // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, + // VibrationSignalParticle, FireflyParticle, OverlayParticle. + | Self::SculkCharge | Self::SculkChargePop | Self::Shriek + | Self::Vibration | Self::Firefly | Self::Flash + // SimpleAnimatedParticle and its subclasses: EndRodParticle, + // SparkParticle (firework), SquidInkParticle, TotemParticle. + | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk + | Self::TotemOfUndying + // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. + | Self::VaultConnection => true, + _ => false, + } + } +} diff --git a/crates/horizon-client-core/src/registries.rs b/crates/horizon-client-core/src/registries.rs new file mode 100644 index 000000000..310115cf8 --- /dev/null +++ b/crates/horizon-client-core/src/registries.rs @@ -0,0 +1,188 @@ +//! Registry contents and source state that commands validate and complete +//! arguments against (what the server's registry access holds). +use std::collections::BTreeMap; + +/// Registry contents and source state used to validate and complete arguments. +#[derive(Clone, Debug, Default)] +pub struct Registries { + /// Permission level of the command source. + pub permission: u8, + pub items: Vec, + pub item_tags: Vec, + /// Block id -> (property, allowed values). + pub blocks: BTreeMap)>>, + pub block_tags: Vec, + /// Entity types that `summon` can create. + pub summonable: Vec, + /// Every entity type (selector `type=`). + pub entity_types: Vec, + pub effects: Vec, + pub enchantments: Vec, + pub structures: Vec, + pub biomes: Vec, + pub dimensions: Vec, + pub clocks: Vec, + pub timelines: Vec, + pub time_markers: Vec, + pub advancements: Vec, + /// Game rule name -> integer-valued. + pub game_rules: Vec<(String, bool)>, + pub players: Vec, + /// Scoreboard objective names, team names and tracked score holders. + pub objectives: Vec, + pub teams: Vec, + pub tracked: Vec, + /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). + pub functions: Vec, + /// `/data ... storage` ids. + pub storages: Vec, + /// Boss bar ids and datapack predicate ids. + pub bossbars: Vec, + pub predicates: Vec, + pub item_modifiers: Vec, + pub schedules: Vec, + pub stopwatches: Vec, + pub recipes: Vec, + pub sounds: Vec, + pub damage_types: Vec, + pub attributes: Vec, + pub loot_tables: Vec, + pub templates: Vec, + pub random_sequences: Vec, + pub datapacks_enabled: Vec, + pub datapacks_disabled: Vec, + pub function_tags: Vec, + /// The block the source is looking at (relevant coordinates). + pub target_block: Option<[i32; 3]>, + /// Every registry's element and tag ids (`minecraft:item` -> ...), as + /// the server's registry access and reloadable registries hold them. + pub by_registry: BTreeMap, + /// Blocks whose default state has a block entity. + pub block_entities: std::collections::BTreeSet, + /// Block tag -> member blocks. + pub block_tag_members: BTreeMap>, + /// Data component types with a codec (not transient). + pub persistent_components: Vec, + /// Recipes `/recipe` can give (not special). + pub learnable_recipes: Vec, + /// Advancement id -> criterion names. + pub advancement_criteria: BTreeMap>, + /// World clock -> time markers shown in commands. + pub clock_time_markers: BTreeMap>, + /// Trigger objectives the source may use (`/trigger` suggestions). + pub trigger_objectives: Vec, + /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. + pub trigger_scores: BTreeMap>, +} +/// The ids and tag ids of one registry. +#[derive(Clone, Debug, Default)] +pub struct RegistryIds { + pub ids: Vec, + pub tags: Vec, +} +const EMPTY: &[String] = &[]; +impl Registries { + /// Fill what the game did not build itself from vanilla's exported + /// registries (`command-registries.json`, written by + /// `VanillaCommandParseOracle registries`): built-in registries such as + /// mob effects, data component types and dialogs, block entities and tag + /// members. Registries that data packs reload stay with the game. + pub fn fill_from_export(&mut self, r: &serde_json::Value) { + fn strings(v: &serde_json::Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() + } + let fill = |field: &mut Vec, key: &str| { + if field.is_empty() { + *field = strings(&r[key]); + } + }; + fill(&mut self.effects, "effects"); + fill(&mut self.enchantments, "enchantments"); + fill(&mut self.attributes, "attributes"); + fill(&mut self.damage_types, "damage_types"); + fill(&mut self.templates, "templates"); + fill(&mut self.persistent_components, "persistent_components"); + fill(&mut self.learnable_recipes, "learnable_recipes"); + const RELOADED: [&str; 5] = [ + "minecraft:advancement", + "minecraft:recipe", + "minecraft:loot_table", + "minecraft:predicate", + "minecraft:item_modifier", + ]; + for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { + if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { + continue; + } + self.by_registry.insert( + name.clone(), + RegistryIds { + ids: strings(&entry["ids"]), + tags: strings(&entry["tags"]), + }, + ); + } + if self.block_entities.is_empty() { + self.block_entities = strings(&r["block_entities"]).into_iter().collect(); + } + if self.block_tag_members.is_empty() { + for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { + self.block_tag_members.insert(tag.clone(), strings(members)); + } + } + if self.clock_time_markers.is_empty() { + for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { + self.clock_time_markers + .insert(clock.clone(), strings(markers)); + } + } + if self.advancement_criteria.is_empty() { + for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { + self.advancement_criteria + .insert(id.clone(), strings(criteria)); + } + } + } + /// The element ids of a registry (sorted). + pub fn ids(&self, registry: &str) -> &[String] { + if let Some(r) = self.by_registry.get(registry) { + return &r.ids; + } + match registry { + "minecraft:item" => &self.items, + "minecraft:entity_type" => &self.entity_types, + "minecraft:mob_effect" => &self.effects, + "minecraft:enchantment" => &self.enchantments, + "minecraft:worldgen/structure" => &self.structures, + "minecraft:worldgen/biome" => &self.biomes, + "minecraft:world_clock" => &self.clocks, + "minecraft:timeline" => &self.timelines, + "minecraft:attribute" => &self.attributes, + "minecraft:damage_type" => &self.damage_types, + "minecraft:sound_event" => &self.sounds, + "minecraft:predicate" => &self.predicates, + "minecraft:item_modifier" => &self.item_modifiers, + "minecraft:loot_table" => &self.loot_tables, + "minecraft:recipe" => &self.recipes, + "minecraft:advancement" => &self.advancements, + _ => EMPTY, + } + } + /// The tag ids of a registry (sorted). + pub fn tags(&self, registry: &str) -> &[String] { + if let Some(r) = self.by_registry.get(registry) { + return &r.tags; + } + match registry { + "minecraft:item" => &self.item_tags, + "minecraft:block" => &self.block_tags, + _ => EMPTY, + } + } +} diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client-core/src/scoreboard.rs similarity index 99% rename from crates/horizon-client/src/scoreboard.rs rename to crates/horizon-client-core/src/scoreboard.rs index 4796be51a..3e820e4eb 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client-core/src/scoreboard.rs @@ -2,9 +2,9 @@ //! `ObjectiveCriteria`, `NumberFormat`) and its saved data //! (`data/minecraft/scoreboard.dat`, `ScoreboardSaveData.Packed`). use crate::{ - command::Registries, component, fastutil_order::{HashSetOrder, OpenOrder}, + registries::Registries, text::{self, Style, Text}, }; use horizon_world::nbt::Tag; @@ -1266,7 +1266,7 @@ fn entity_uuids(tag: &mut Tag) { }) .collect::>>(), Tag::String(s) => { - crate::save::uuid_from_text(&s.to_string_lossy()).map(Vec::from) + crate::uuid::uuid_from_text(&s.to_string_lossy()).map(Vec::from) } _ => None, }; diff --git a/crates/horizon-client/src/snbt.rs b/crates/horizon-client-core/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/snbt.rs rename to crates/horizon-client-core/src/snbt.rs diff --git a/crates/horizon-client-core/src/sound_source.rs b/crates/horizon-client-core/src/sound_source.rs new file mode 100644 index 000000000..d181d6ac5 --- /dev/null +++ b/crates/horizon-client-core/src/sound_source.rs @@ -0,0 +1,7 @@ +//! Sound sources (`SoundSource`), by name. + +/// SoundSource names in vanilla order. +pub const SOUND_SOURCES: [&str; 11] = [ + "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", + "voice", "ui", +]; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client-core/src/text.rs similarity index 99% rename from crates/horizon-client/src/text.rs rename to crates/horizon-client-core/src/text.rs index 4c04c9da5..0a2b6eadb 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client-core/src/text.rs @@ -67,7 +67,7 @@ pub struct Style { } /// A style's `font` field: an identifier (`alt` is `minecraft:alt`). pub fn font_id(v: &Value) -> Option { - crate::command::args::parse_identifier(v.as_str()?) + crate::identifier::parse_identifier(v.as_str()?) } impl Style { pub fn color(c: u32) -> Self { diff --git a/crates/horizon-client-core/src/uuid.rs b/crates/horizon-client-core/src/uuid.rs new file mode 100644 index 000000000..4ede9b141 --- /dev/null +++ b/crates/horizon-client-core/src/uuid.rs @@ -0,0 +1,24 @@ +//! UUIDs as vanilla's four-int form, to and from their text form. + +pub fn uuid_text(u: [i32; 4]) -> String { + let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} +pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { + let hex: String = s.chars().filter(|c| *c != '-').collect(); + if hex.len() != 32 { + return None; + } + let mut out = [0i32; 4]; + for (i, v) in out.iter_mut().enumerate() { + *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; + } + Some(out) +} diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index d7c6d812b..923a48a34 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -9,6 +9,8 @@ description = "Horizon native development client" [dependencies] horizon-assets = { path = "../horizon-assets" } +horizon-client-core = { path = "../horizon-client-core" } +horizon-command = { path = "../horizon-command" } horizon-core = { path = "../horizon-core" } # The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority). horizon-threads = { path = "../horizon-threads" } diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index a59aa627c..fb0d04344 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -2,7 +2,6 @@ //! defaults, `key_:key.keyboard.x` persistence, display names, and the //! translation of rebound physical keys back to the default keys the game //! logic listens for. -use crate::text::Text; use std::collections::BTreeMap; use winit::{event::MouseButton, keyboard::KeyCode}; @@ -225,40 +224,7 @@ pub fn mouse_button(name: &str) -> Option { _ => return None, }) } -/// InputConstants.Key.getDisplayName: one-character keys as the upper-case -/// character, others by translation. -pub fn display_name(key: &str) -> Text { - if let Some(rest) = key.strip_prefix("key.keyboard.") - && rest.chars().count() == 1 - { - let c = rest.to_uppercase(); - return Text::literal(c); - } - let symbol = match key { - "key.keyboard.minus" => Some("-"), - "key.keyboard.equal" => Some("="), - "key.keyboard.left.bracket" => Some("["), - "key.keyboard.right.bracket" => Some("]"), - "key.keyboard.backslash" => Some("\\"), - "key.keyboard.semicolon" => Some(";"), - "key.keyboard.apostrophe" => Some("'"), - "key.keyboard.grave.accent" => Some("`"), - "key.keyboard.comma" => Some(","), - "key.keyboard.period" => Some("."), - "key.keyboard.slash" => Some("/"), - _ => None, - }; - if let Some(s) = symbol { - return Text::literal(s); - } - if let Some(n) = key.strip_prefix("key.mouse.") - && n.parse::().is_ok() - && !crate::lang::has(key) - { - return Text::translate("key.mouse", &[Text::literal(n)]); - } - Text::translate(key, &[]) -} +pub use horizon_client_core::key_display::display_name; /// Current bindings by mapping name. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6bf40d1f0..232904b7a 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -19,13 +19,11 @@ pub mod biome; pub mod block_entities; pub mod block_entity_anim; pub mod block_entity_item; -pub mod block_entity_nbt; pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod border_render; pub mod boss_overlay; -pub mod bossbar; pub mod breaking; pub mod brewing; pub mod bundle; @@ -38,10 +36,8 @@ pub mod clipboard; pub mod clock; pub mod clouds; pub mod collisions; -pub mod command; pub mod command_block; pub mod command_storage; -pub mod component; pub mod confirm_screen; pub mod container_screen; pub mod containers; @@ -70,7 +66,6 @@ pub mod extras; pub mod extras_hud; pub mod falling_block; pub mod fast_hash; -pub mod fastutil_order; pub mod fire_render; pub mod first_person; pub mod flatgen; @@ -79,7 +74,6 @@ pub mod font; pub mod friends_screen; pub mod game_mode_switcher; pub mod gamepad; -pub mod gamerules; pub mod gfx; pub mod gizmos; pub mod gossip; @@ -108,7 +102,6 @@ pub mod keybinds; pub mod keymapping; pub mod lan; pub mod landing; -pub mod lang; pub mod level_loading; pub mod light; pub mod locator_bar; @@ -130,7 +123,6 @@ pub mod mouse; pub mod moved_extras; pub mod multiplayer; pub mod music; -pub mod nbt_path; pub mod net; pub mod nether_portal; pub mod offline_name; @@ -159,7 +151,6 @@ pub mod recipe_book; pub mod recipe_book_screen; pub mod reconnect; pub mod save; -pub mod scoreboard; pub mod scoreboard_cmd; pub mod screen_draw; pub mod screen_effects; @@ -172,7 +163,6 @@ pub mod shader_pack_list; pub mod shadows; pub mod signs; pub mod skins; -pub mod snbt; pub mod sound_engine; pub mod sound_events; pub mod spans; @@ -185,7 +175,6 @@ pub mod structure_blocks; pub mod tab_list; pub mod telemetry; pub mod testgen; -pub mod text; pub mod text_display; pub mod tick_chunk_membership; pub mod ticket_levels; @@ -205,4 +194,15 @@ pub mod world; pub mod world_spawn; pub mod worldborder; pub mod zip; -pub type Result = std::result::Result>; +pub use horizon_client_core::Result; +pub use horizon_client_core::block_entity_nbt; +pub use horizon_client_core::bossbar; +pub use horizon_client_core::component; +pub use horizon_client_core::fastutil_order; +pub use horizon_client_core::gamerules; +pub use horizon_client_core::lang; +pub use horizon_client_core::nbt_path; +pub use horizon_client_core::scoreboard; +pub use horizon_client_core::snbt; +pub use horizon_client_core::text; +pub use horizon_command as command; diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..17064c163 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -23,212 +23,7 @@ use std::{ path::Path, }; -macro_rules! particle_types { - ($($variant:ident = $name:literal),* $(,)?) => { - /// Vanilla particle types with a client implementation here. - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] - pub enum ParticleType { $($variant),* } - impl ParticleType { - pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; - /// Registry path (`minecraft:`), also the sprite-set file name. - pub fn name(self) -> &'static str { - match self { $(ParticleType::$variant => $name),* } - } - pub fn from_name(name: &str) -> Option { - let name = name.strip_prefix("minecraft:").unwrap_or(name); - match name { $($name => Some(ParticleType::$variant),)* _ => None } - } - } - }; -} -particle_types! { - Block = "block", - BlockCrumble = "block_crumble", - Trail = "trail", - DustPillar = "dust_pillar", - FallingDust = "falling_dust", - Smoke = "smoke", - LargeSmoke = "large_smoke", - WhiteSmoke = "white_smoke", - Flame = "flame", - SoulFireFlame = "soul_fire_flame", - CopperFireFlame = "copper_fire_flame", - SmallFlame = "small_flame", - Lava = "lava", - DrippingWater = "dripping_water", - FallingWater = "falling_water", - DrippingLava = "dripping_lava", - FallingLava = "falling_lava", - LandingLava = "landing_lava", - DrippingHoney = "dripping_honey", - FallingHoney = "falling_honey", - LandingHoney = "landing_honey", - FallingNectar = "falling_nectar", - FallingSporeBlossom = "falling_spore_blossom", - SporeBlossomAir = "spore_blossom_air", - DrippingObsidianTear = "dripping_obsidian_tear", - FallingObsidianTear = "falling_obsidian_tear", - LandingObsidianTear = "landing_obsidian_tear", - DrippingDripstoneWater = "dripping_dripstone_water", - FallingDripstoneWater = "falling_dripstone_water", - DrippingDripstoneLava = "dripping_dripstone_lava", - FallingDripstoneLava = "falling_dripstone_lava", - Splash = "splash", - Rain = "rain", - Bubble = "bubble", - SulfurBubbles = "sulfur_bubbles", - BubblePop = "bubble_pop", - BubbleColumnUp = "bubble_column_up", - CurrentDown = "current_down", - Underwater = "underwater", - Portal = "portal", - ReversePortal = "reverse_portal", - Enchant = "enchant", - Nautilus = "nautilus", - VaultConnection = "vault_connection", - Crit = "crit", - EnchantedHit = "enchanted_hit", - DamageIndicator = "damage_indicator", - Heart = "heart", - AngryVillager = "angry_villager", - HappyVillager = "happy_villager", - Composter = "composter", - Mycelium = "mycelium", - Dolphin = "dolphin", - EggCrack = "egg_crack", - Poof = "poof", - Explosion = "explosion", - ExplosionEmitter = "explosion_emitter", - CampfireCosySmoke = "campfire_cosy_smoke", - CampfireSignalSmoke = "campfire_signal_smoke", - Note = "note", - Dust = "dust", - TotemOfUndying = "totem_of_undying", - Firework = "firework", - EndRod = "end_rod", - Ash = "ash", - WhiteAsh = "white_ash", - CrimsonSpore = "crimson_spore", - WarpedSpore = "warped_spore", - CherryLeaves = "cherry_leaves", - PaleOakLeaves = "pale_oak_leaves", - TintedLeaves = "tinted_leaves", - Effect = "effect", - InstantEffect = "instant_effect", - EntityEffect = "entity_effect", - Witch = "witch", - Infested = "infested", - Cloud = "cloud", - Sneeze = "sneeze", - Snowflake = "snowflake", - Soul = "soul", - SculkSoul = "sculk_soul", - DragonBreath = "dragon_breath", - Gust = "gust", - SmallGust = "small_gust", - GustEmitterLarge = "gust_emitter_large", - GustEmitterSmall = "gust_emitter_small", - DustColorTransition = "dust_color_transition", - SculkCharge = "sculk_charge", - SculkChargePop = "sculk_charge_pop", - Shriek = "shriek", - SonicBoom = "sonic_boom", - Vibration = "vibration", - SweepAttack = "sweep_attack", - Glow = "glow", - WaxOn = "wax_on", - WaxOff = "wax_off", - ElectricSpark = "electric_spark", - Scrape = "scrape", - SquidInk = "squid_ink", - GlowSquidInk = "glow_squid_ink", - Item = "item", - ItemSlime = "item_slime", - ItemSnowball = "item_snowball", - ItemCobweb = "item_cobweb", - SulfurCubeGoo = "sulfur_cube_goo", - Flash = "flash", - Firefly = "firefly", - TrialSpawnerDetection = "trial_spawner_detection", - TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", - TrialOmen = "trial_omen", - RaidOmen = "raid_omen", - OminousSpawning = "ominous_spawning", - Spit = "spit", - Fishing = "fishing", - DustPlume = "dust_plume", - RedPoplarLeaves = "red_poplar_leaves", - OrangePoplarLeaves = "orange_poplar_leaves", - YellowPoplarLeaves = "yellow_poplar_leaves", - PauseMobGrowth = "pause_mob_growth", - ResetMobGrowth = "reset_mob_growth", - BlockMarker = "block_marker", -} -impl ParticleType { - /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): - /// spawned regardless of distance. - pub fn override_limiter(self) -> bool { - matches!( - self, - Self::BlockMarker - | Self::DamageIndicator - | Self::ExplosionEmitter - | Self::Explosion - | Self::Gust - | Self::GustEmitterLarge - | Self::GustEmitterSmall - | Self::SonicBoom - | Self::SculkCharge - | Self::SculkChargePop - | Self::Vibration - | Self::Poof - | Self::Spit - | Self::SquidInk - | Self::SweepAttack - | Self::CampfireCosySmoke - | Self::CampfireSignalSmoke - | Self::GlowSquidInk - | Self::Glow - | Self::WaxOn - | Self::WaxOff - | Self::ElectricSpark - | Self::Scrape - | Self::TrialSpawnerDetection - | Self::TrialSpawnerDetectionOminous - | Self::VaultConnection - | Self::OminousSpawning - ) - } - /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class - /// hardcodes the translucent layer, drawn after translucent terrain. - /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their - /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` - /// sprite set on the engine. - pub fn translucent_layer(self) -> bool { - match self { - // CampfireSmokeParticle. - Self::CampfireCosySmoke | Self::CampfireSignalSmoke - // PlayerCloudParticle. - | Self::Cloud | Self::Sneeze - // SpellParticle. - | Self::Effect | Self::InstantEffect | Self::EntityEffect - | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen - // EmissiveRisingParticle. - | Self::Soul | Self::SculkSoul - // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, - // VibrationSignalParticle, FireflyParticle, OverlayParticle. - | Self::SculkCharge | Self::SculkChargePop | Self::Shriek - | Self::Vibration | Self::Firefly | Self::Flash - // SimpleAnimatedParticle and its subclasses: EndRodParticle, - // SparkParticle (firework), SquidInkParticle, TotemParticle. - | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk - | Self::TotemOfUndying - // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. - | Self::VaultConnection => true, - _ => false, - } - } -} +pub use horizon_client_core::particle_type::ParticleType; /// `ParticleOptions` with the parameters of the option classes used here. #[derive(Clone, Debug)] diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..6f4082ec3 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1988,28 +1988,7 @@ fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> { Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]), ) } -pub fn uuid_text(u: [i32; 4]) -> String { - let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - format!( - "{}-{}-{}-{}-{}", - &hex[0..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..32] - ) -} -pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { - let hex: String = s.chars().filter(|c| *c != '-').collect(); - if hex.len() != 32 { - return None; - } - let mut out = [0i32; 4]; - for (i, v) in out.iter_mut().enumerate() { - *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; - } - Some(out) -} +pub use horizon_client_core::uuid::{uuid_from_text, uuid_text}; /// A random (version 4) UUID as vanilla's four-int form. pub fn random_uuid() -> [i32; 4] { let t = std::time::SystemTime::now() @@ -4382,4 +4361,28 @@ mod tests { }; assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3)); } + /// The world's save (Level.write) writes the rules as they are now, and a + /// world opened again reads them back (#74). + #[test] + fn level_save_keeps_changed_rules() { + use crate::gamerules::{GameRules, Value}; + let dir = + std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut level = super::Level::default(); + level.write(&dir).unwrap(); + // Rules changed while playing, then saved and loaded again. + let mut rules = GameRules::load(&dir); + assert_eq!(rules, GameRules::default()); + assert!(rules.set("advance_time", Value::Bool(false))); + assert!(rules.set("advance_weather", Value::Bool(false))); + assert!(rules.set("random_tick_speed", Value::Int(0))); + level.game_rules = rules.by_name(); + level.write(&dir).unwrap(); + assert_eq!(GameRules::load(&dir), rules); + let read = super::Level::read(&dir).unwrap(); + assert_eq!(read.game_rules, rules.by_name()); + assert_eq!(read.game_rule("advance_time"), 0); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 74c428923..2308794d3 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -5,11 +5,7 @@ use crate::keybinds::KeyBinds; use crate::options_file::{OptionsFile, V}; use std::{fs, path::Path}; -/// SoundSource names in vanilla order. -pub const SOUND_SOURCES: [&str; 11] = [ - "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", - "voice", "ui", -]; +pub use horizon_client_core::sound_source::SOUND_SOURCES; /// Per-source volumes for the mixer (soundCategory_* except master). static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); diff --git a/crates/horizon-command/Cargo.toml b/crates/horizon-command/Cargo.toml new file mode 100644 index 000000000..10191ed6f --- /dev/null +++ b/crates/horizon-command/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-command" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "Commands (Brigadier): the vanilla command tree, argument types, selectors, parsing, suggestions and the network form of the tree" + +[dependencies] +horizon-client-core = { path = "../horizon-client-core" } +horizon-protocol = { path = "../horizon-protocol" } +horizon-world = { path = "../horizon-world" } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-command/src/args.rs similarity index 87% rename from crates/horizon-client/src/command/args.rs rename to crates/horizon-command/src/args.rs index ccced67a7..9d24d672f 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-command/src/args.rs @@ -1,192 +1,8 @@ //! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with //! the vanilla error messages and completion suggestions. use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder}; -use std::collections::BTreeMap; -/// Registry contents and source state used to validate and complete arguments. -#[derive(Clone, Debug, Default)] -pub struct Registries { - /// Permission level of the command source. - pub permission: u8, - pub items: Vec, - pub item_tags: Vec, - /// Block id -> (property, allowed values). - pub blocks: BTreeMap)>>, - pub block_tags: Vec, - /// Entity types that `summon` can create. - pub summonable: Vec, - /// Every entity type (selector `type=`). - pub entity_types: Vec, - pub effects: Vec, - pub enchantments: Vec, - pub structures: Vec, - pub biomes: Vec, - pub dimensions: Vec, - pub clocks: Vec, - pub timelines: Vec, - pub time_markers: Vec, - pub advancements: Vec, - /// Game rule name -> integer-valued. - pub game_rules: Vec<(String, bool)>, - pub players: Vec, - /// Scoreboard objective names, team names and tracked score holders. - pub objectives: Vec, - pub teams: Vec, - pub tracked: Vec, - /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). - pub functions: Vec, - /// `/data ... storage` ids. - pub storages: Vec, - /// Boss bar ids and datapack predicate ids. - pub bossbars: Vec, - pub predicates: Vec, - pub item_modifiers: Vec, - pub schedules: Vec, - pub stopwatches: Vec, - pub recipes: Vec, - pub sounds: Vec, - pub damage_types: Vec, - pub attributes: Vec, - pub loot_tables: Vec, - pub templates: Vec, - pub random_sequences: Vec, - pub datapacks_enabled: Vec, - pub datapacks_disabled: Vec, - pub function_tags: Vec, - /// The block the source is looking at (relevant coordinates). - pub target_block: Option<[i32; 3]>, - /// Every registry's element and tag ids (`minecraft:item` -> ...), as - /// the server's registry access and reloadable registries hold them. - pub by_registry: BTreeMap, - /// Blocks whose default state has a block entity. - pub block_entities: std::collections::BTreeSet, - /// Block tag -> member blocks. - pub block_tag_members: BTreeMap>, - /// Data component types with a codec (not transient). - pub persistent_components: Vec, - /// Recipes `/recipe` can give (not special). - pub learnable_recipes: Vec, - /// Advancement id -> criterion names. - pub advancement_criteria: BTreeMap>, - /// World clock -> time markers shown in commands. - pub clock_time_markers: BTreeMap>, - /// Trigger objectives the source may use (`/trigger` suggestions). - pub trigger_objectives: Vec, - /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. - pub trigger_scores: BTreeMap>, -} -/// The ids and tag ids of one registry. -#[derive(Clone, Debug, Default)] -pub struct RegistryIds { - pub ids: Vec, - pub tags: Vec, -} -const EMPTY: &[String] = &[]; -impl Registries { - /// Fill what the game did not build itself from vanilla's exported - /// registries (`command-registries.json`, written by - /// `VanillaCommandParseOracle registries`): built-in registries such as - /// mob effects, data component types and dialogs, block entities and tag - /// members. Registries that data packs reload stay with the game. - pub fn fill_from_export(&mut self, r: &serde_json::Value) { - fn strings(v: &serde_json::Value) -> Vec { - v.as_array() - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_owned)) - .collect() - }) - .unwrap_or_default() - } - let fill = |field: &mut Vec, key: &str| { - if field.is_empty() { - *field = strings(&r[key]); - } - }; - fill(&mut self.effects, "effects"); - fill(&mut self.enchantments, "enchantments"); - fill(&mut self.attributes, "attributes"); - fill(&mut self.damage_types, "damage_types"); - fill(&mut self.templates, "templates"); - fill(&mut self.persistent_components, "persistent_components"); - fill(&mut self.learnable_recipes, "learnable_recipes"); - const RELOADED: [&str; 5] = [ - "minecraft:advancement", - "minecraft:recipe", - "minecraft:loot_table", - "minecraft:predicate", - "minecraft:item_modifier", - ]; - for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { - if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { - continue; - } - self.by_registry.insert( - name.clone(), - RegistryIds { - ids: strings(&entry["ids"]), - tags: strings(&entry["tags"]), - }, - ); - } - if self.block_entities.is_empty() { - self.block_entities = strings(&r["block_entities"]).into_iter().collect(); - } - if self.block_tag_members.is_empty() { - for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { - self.block_tag_members.insert(tag.clone(), strings(members)); - } - } - if self.clock_time_markers.is_empty() { - for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { - self.clock_time_markers - .insert(clock.clone(), strings(markers)); - } - } - if self.advancement_criteria.is_empty() { - for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { - self.advancement_criteria - .insert(id.clone(), strings(criteria)); - } - } - } - /// The element ids of a registry (sorted). - pub fn ids(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.ids; - } - match registry { - "minecraft:item" => &self.items, - "minecraft:entity_type" => &self.entity_types, - "minecraft:mob_effect" => &self.effects, - "minecraft:enchantment" => &self.enchantments, - "minecraft:worldgen/structure" => &self.structures, - "minecraft:worldgen/biome" => &self.biomes, - "minecraft:world_clock" => &self.clocks, - "minecraft:timeline" => &self.timelines, - "minecraft:attribute" => &self.attributes, - "minecraft:damage_type" => &self.damage_types, - "minecraft:sound_event" => &self.sounds, - "minecraft:predicate" => &self.predicates, - "minecraft:item_modifier" => &self.item_modifiers, - "minecraft:loot_table" => &self.loot_tables, - "minecraft:recipe" => &self.recipes, - "minecraft:advancement" => &self.advancements, - _ => EMPTY, - } - } - /// The tag ids of a registry (sorted). - pub fn tags(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.tags; - } - match registry { - "minecraft:item" => &self.item_tags, - "minecraft:block" => &self.block_tags, - _ => EMPTY, - } - } -} +pub use horizon_client_core::registries::{Registries, RegistryIds}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Resource { @@ -637,22 +453,7 @@ pub fn read_identifier(reader: &mut Reader) -> CmdResult { } } } -/// Identifier.parse: `ns:path` or `path`, validated. -pub fn parse_identifier(raw: &str) -> Option { - let (ns, path) = match raw.split_once(':') { - Some(("", path)) => ("minecraft", path), - Some((ns, path)) => (ns, path), - None => ("minecraft", raw), - }; - let ns_ok = ns != ".." - && ns - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); - let path_ok = path.chars().all(|c| { - c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') - }); - (ns_ok && path_ok).then(|| format!("{ns}:{path}")) -} +pub use horizon_client_core::identifier::parse_identifier; pub fn normalize(id: &str) -> String { match id.split_once(':') { Some(("", path)) => format!("minecraft:{path}"), @@ -1220,7 +1021,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.low", - &[&crate::snbt::java_float(*min), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*min), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1228,7 +1032,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.big", - &[&crate::snbt::java_float(*max), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*max), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1241,8 +1048,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.low", &[ - &crate::snbt::java_double(*min), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*min), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1252,8 +1059,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.big", &[ - &crate::snbt::java_double(*max), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*max), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1597,7 +1404,7 @@ impl ArgType { return Err(CommandError::tr_at(key, &[&m], reader)); } let text = &reader.string[start..reader.cursor]; - match crate::component::parse_snbt(text) { + match horizon_client_core::component::parse_snbt(text) { Ok((v, _)) => Arg::Str(v.to_string()), Err(_) => Arg::Str(text.to_owned()), } @@ -1645,7 +1452,7 @@ impl ArgType { } let id = &reader.string[start..reader.cursor]; // ObjectiveCriteria.byName: statistics resolve to their canonical name. - match crate::scoreboard::criteria_by_name(id, reg) { + match horizon_client_core::scoreboard::criteria_by_name(id, reg) { Ok(Some(canonical)) => Arg::Str(canonical), Ok(None) => { reader.cursor = start; @@ -1667,7 +1474,7 @@ impl ArgType { } ArgType::ScoreboardSlot => { let name = reader.read_unquoted_string(); - if !crate::scoreboard::display_slot_valid(name) { + if !horizon_client_core::scoreboard::display_slot_valid(name) { return Err(CommandError::tr_at( "argument.scoreboardDisplaySlot.invalid", &[&name], @@ -1695,7 +1502,7 @@ impl ArgType { } ArgType::TeamColor => { let name = reader.read_unquoted_string(); - if crate::scoreboard::team_color_rgb(name).is_none() { + if horizon_client_core::scoreboard::team_color_rgb(name).is_none() { return Err(CommandError::tr_at( "argument.color.invalid", &[&name], @@ -1743,7 +1550,7 @@ impl ArgType { let id = read_identifier(reader)?; let known = reg.ids("minecraft:particle_type"); let exists = if known.is_empty() { - crate::particles::ParticleType::from_name(&id).is_some() + horizon_client_core::particle_type::ParticleType::from_name(&id).is_some() } else { known.contains(&id) }; @@ -1931,15 +1738,16 @@ impl ArgType { } ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), ArgType::Criteria => { - let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + let mut ids: Vec = horizon_client_core::scoreboard::CUSTOM_CRITERIA .iter() .map(|s| (*s).to_owned()) .collect(); - for c in crate::scoreboard::team_colors() { + for c in horizon_client_core::scoreboard::team_colors() { ids.push(format!("teamkill.{c}")); ids.push(format!("killedByTeam.{c}")); } - let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + let stat = + |ty: &str, key: &str| horizon_client_core::scoreboard::stat_criteria(ty, key); ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { ids.extend(reg.items.iter().map(|i| stat(ty, i))); @@ -1948,14 +1756,14 @@ impl ArgType { ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); } ids.extend( - crate::scoreboard::CUSTOM_STATS + horizon_client_core::scoreboard::CUSTOM_STATS .iter() .map(|c| stat("custom", &format!("minecraft:{c}"))), ); builder.suggest_matching(ids.iter().map(String::as_str)); } ArgType::ScoreboardSlot => { - let slots = crate::scoreboard::display_slots(); + let slots = horizon_client_core::scoreboard::display_slots(); builder.suggest_matching(slots.iter().map(String::as_str)); } ArgType::Operation => builder.suggest_matching(OPERATIONS), @@ -1963,7 +1771,7 @@ impl ArgType { ArgType::Particle => { let known = reg.ids("minecraft:particle_type"); if known.is_empty() { - let names: Vec = crate::particles::ParticleType::ALL + let names: Vec = horizon_client_core::particle_type::ParticleType::ALL .iter() .map(|t| format!("minecraft:{}", t.name())) .collect(); @@ -1999,7 +1807,9 @@ impl ArgType { suggest_resources(builder, reg.ids("minecraft:slot_source"), ""); } ArgType::ResourceOrId(registry) => suggest_resources(builder, reg.ids(registry), ""), - ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), + ArgType::TeamColor => { + builder.suggest_matching(horizon_client_core::scoreboard::team_colors()) + } ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Component | ArgType::Style | ArgType::NbtTag => super::snbt::suggest(builder), ArgType::Swizzle | ArgType::Message | ArgType::Nbt => {} diff --git a/crates/horizon-client/src/command/block.rs b/crates/horizon-command/src/block.rs similarity index 100% rename from crates/horizon-client/src/command/block.rs rename to crates/horizon-command/src/block.rs diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-command/src/codec.rs similarity index 99% rename from crates/horizon-client/src/command/codec.rs rename to crates/horizon-command/src/codec.rs index 7c4d26682..40f5c1ce0 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-command/src/codec.rs @@ -6,7 +6,7 @@ use super::{CmdResult, CommandError, Reader}; use horizon_world::nbt::{Compound, JavaString, Tag}; pub fn snbt(t: &Tag) -> String { - crate::snbt::to_snbt(t) + horizon_client_core::snbt::to_snbt(t) } pub fn not_map(t: &Tag) -> String { format!("Not a map: {}", snbt(t)) diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-command/src/component.rs similarity index 98% rename from crates/horizon-client/src/command/component.rs rename to crates/horizon-command/src/component.rs index 15a8fa6a0..2933afeca 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-command/src/component.rs @@ -164,7 +164,7 @@ fn color(t: &Tag) -> R { _ => partial(format!("Invalid color value: {s}")), }; } - if crate::text::named_color(&s).is_some() { + if horizon_client_core::text::named_color(&s).is_some() { Ok(()) } else { partial(format!("Invalid color name: {s}")) @@ -278,7 +278,7 @@ fn content(kind: &str, map: &Compound) -> bool { "nbt" => { let path_ok = get(map, "nbt") .and_then(string_of) - .is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); + .is_some_and(|p| horizon_client_core::nbt_path::NbtPath::parse(&p).is_ok()); let source = if let Some(e) = get(map, "entity") { selector_string(e) } else if let Some(b) = get(map, "block") { diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-command/src/item.rs similarity index 99% rename from crates/horizon-client/src/command/item.rs rename to crates/horizon-command/src/item.rs index f2abc91ef..da9c4b8b0 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-command/src/item.rs @@ -72,9 +72,9 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> { } else { format!("minecraft:{id}") }; - let known = crate::block_entity_nbt::TYPES + let known = horizon_client_core::block_entity_nbt::TYPES .iter() - .chain(&crate::block_entity_nbt::NEWEST) + .chain(&horizon_client_core::block_entity_nbt::NEWEST) .any(|k| *k == id); if known { Ok(()) diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-command/src/lib.rs similarity index 99% rename from crates/horizon-client/src/command/mod.rs rename to crates/horizon-command/src/lib.rs index a61c8c08d..838c8de87 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-command/src/lib.rs @@ -3,6 +3,7 @@ //! relevant child and keeps the best result, completion suggestions, smart //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. +#![forbid(unsafe_code)] pub mod args; pub mod block; pub mod codec; @@ -21,8 +22,8 @@ pub mod tree_world; pub mod vanilla; mod vanilla_order; -use crate::text::Text; pub use args::{Arg, ArgType, Registries}; +use horizon_client_core::text::Text; /// The command id of a mod's command (`Dispatcher::with_mod_commands`). pub const MOD_COMMAND: &str = "mod"; @@ -623,8 +624,10 @@ impl Suggests { for id in ®.summonable { if args::resource_matches(&contents, id) { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - let name = - crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); + let name = horizon_client_core::lang::get(&format!( + "entity.{ns}.{}", + path.replace('/', ".") + )); builder.suggest_tooltip(id.clone(), name); } } diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-command/src/network.rs similarity index 100% rename from crates/horizon-client/src/command/network.rs rename to crates/horizon-command/src/network.rs diff --git a/crates/horizon-client/src/command/packrat.rs b/crates/horizon-command/src/packrat.rs similarity index 99% rename from crates/horizon-client/src/command/packrat.rs rename to crates/horizon-command/src/packrat.rs index 42f42d9f4..ebe9df09d 100644 --- a/crates/horizon-client/src/command/packrat.rs +++ b/crates/horizon-command/src/packrat.rs @@ -402,7 +402,7 @@ impl<'g, V: Value> State<'g, V> { Reason::Error(e) => e.clone(), }; } - CommandError::new(crate::text::Text::literal("Failed to parse")) + CommandError::new(horizon_client_core::text::Text::literal("Failed to parse")) } /// CachedParseState.parse: a named rule, memoised per position. pub fn parse(&mut self, rule: RuleId) -> Option { diff --git a/crates/horizon-client/src/command/selector.rs b/crates/horizon-command/src/selector.rs similarity index 99% rename from crates/horizon-client/src/command/selector.rs rename to crates/horizon-command/src/selector.rs index eb4e637a4..777124f60 100644 --- a/crates/horizon-client/src/command/selector.rs +++ b/crates/horizon-command/src/selector.rs @@ -687,7 +687,7 @@ impl<'r, 'a> SelectorParser<'r, 'a> { fn fill_selectors(builder: &mut SuggestionsBuilder) { for (s, tip) in SELECTOR_KINDS { - builder.suggest_tooltip(s, crate::lang::get(tip)); + builder.suggest_tooltip(s, horizon_client_core::lang::get(tip)); } } @@ -785,7 +785,9 @@ impl<'r, 'a> SelectorParser<'r, 'a> { if self.can_use(o) && o.starts_with(&lower) { b.suggest_tooltip( format!("{o}="), - crate::lang::get(&format!("argument.entity.options.{o}.description")), + horizon_client_core::lang::get(&format!( + "argument.entity.options.{o}.description" + )), ); } } diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-command/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/command/snbt.rs rename to crates/horizon-command/src/snbt.rs diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-command/src/tests.rs similarity index 100% rename from crates/horizon-client/src/command/tests.rs rename to crates/horizon-command/src/tests.rs diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-command/src/tree_data.rs similarity index 100% rename from crates/horizon-client/src/command/tree_data.rs rename to crates/horizon-command/src/tree_data.rs diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-command/src/tree_execute.rs similarity index 100% rename from crates/horizon-client/src/command/tree_execute.rs rename to crates/horizon-command/src/tree_execute.rs diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-command/src/tree_extra.rs similarity index 100% rename from crates/horizon-client/src/command/tree_extra.rs rename to crates/horizon-command/src/tree_extra.rs diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-command/src/tree_misc.rs similarity index 99% rename from crates/horizon-client/src/command/tree_misc.rs rename to crates/horizon-command/src/tree_misc.rs index a66fd5f37..1bcd880bb 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-command/src/tree_misc.rs @@ -230,12 +230,12 @@ fn bossbar(d: &mut Dispatcher, root: usize) { let name = d.argument(name_l, "name", ArgType::Component); d.executes(name, "bossbar.set.name"); let color = d.literal(id, "color"); - for c in crate::bossbar::COLORS { + for c in horizon_client_core::bossbar::COLORS { let l = d.literal(color, c); d.executes(l, "bossbar.set.color"); } let style = d.literal(id, "style"); - for s in crate::bossbar::STYLES { + for s in horizon_client_core::bossbar::STYLES { let l = d.literal(style, s); d.executes(l, "bossbar.set.style"); } diff --git a/crates/horizon-client/src/command/tree_scoreboard.rs b/crates/horizon-command/src/tree_scoreboard.rs similarity index 100% rename from crates/horizon-client/src/command/tree_scoreboard.rs rename to crates/horizon-command/src/tree_scoreboard.rs diff --git a/crates/horizon-client/src/command/tree_world.rs b/crates/horizon-command/src/tree_world.rs similarity index 99% rename from crates/horizon-client/src/command/tree_world.rs rename to crates/horizon-command/src/tree_world.rs index 0bd2edd3b..86ebba0ca 100644 --- a/crates/horizon-client/src/command/tree_world.rs +++ b/crates/horizon-command/src/tree_world.rs @@ -7,7 +7,7 @@ use super::{ args::{ArgType, integer}, vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS}, }; -use crate::settings::SOUND_SOURCES; +use horizon_client_core::sound_source::SOUND_SOURCES; fn float(min: f32) -> ArgType { ArgType::Float { min, max: f32::MAX } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-command/src/vanilla.rs similarity index 99% rename from crates/horizon-client/src/command/vanilla.rs rename to crates/horizon-command/src/vanilla.rs index 2ce892077..37ec1c3de 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-command/src/vanilla.rs @@ -5,7 +5,7 @@ use super::{ Dispatcher, args::{ArgType, Resource, integer}, }; -use crate::gamerules::{RULES, Value}; +use horizon_client_core::gamerules::{RULES, Value}; /// Permission levels (Commands.LEVEL_*). pub const ALL: u8 = 0; diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-command/src/vanilla_order.rs similarity index 100% rename from crates/horizon-client/src/command/vanilla_order.rs rename to crates/horizon-command/src/vanilla_order.rs diff --git a/docs/architecture.md b/docs/architecture.md index 0350bd1ea..7646ccc17 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,8 +5,9 @@ counted only for the game loop because nearly every gameplay change touches it). organised and how to build and test are in [AGENTS.md](../AGENTS.md). Paths: `L/` = `crates/horizon-client/src/`, `G/` = `crates/horizon-client/src/game/`, `W/` = -`crates/horizon-world/src/`. Checks: a bare name is a harness (`python3 tools/parity.py `, script -`tools/test__parity.py`); `lan_e2e ` is `python3 tools/lan_e2e.py --check `. +`crates/horizon-world/src/`, `K/` = `crates/horizon-client-core/src/`, `C/` = `crates/horizon-command/src/`. +Checks: a bare name is a harness (`python3 tools/parity.py `, script `tools/test__parity.py`); +`lan_e2e ` is `python3 tools/lan_e2e.py --check `. For the full set of harnesses a file can affect, ask the runner: `printf '%s\n' > /tmp/p.txt && python3 tools/parity.py --changed-files /tmp/p.txt --list`. @@ -17,7 +18,7 @@ file selects ~103. |---|---|---|---| | 1 | Game loop, tick order, frame pacing (554) | `L/game.rs` (`fn tick`, `fn tick_world`, `fn render`, `about_to_wait`), `L/clock.rs`, `L/window.rs`, `L/spans.rs` | game_loop, frame_limiter, interaction_input, tick | | 2 | Mobs in the game loop, spawning (166) | `G/creatures.rs`, `G/natural_spawning.rs`, `L/mobs/spawning.rs`, `L/mobs/spawn_rules.rs`, `L/mobs/spawn_selection.rs`, `L/mobs/finalize.rs`, `G/spawner.rs`, `G/trial_spawner.rs` | natural_spawn, spawn_rules, finalize_spawn, spawner, trial_spawner, mob_ai | -| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `L/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | +| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `K/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | | 4 | World generation (153) | `W/worldgen.rs`, `W/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `placement/`), `L/vanillagen.rs` | chunk_generation, worldgen, server_world_gen, world_spawn, feature_graph, feature_placement, decoration and the other worldgen harnesses | | 5 | Multiplayer client, packets in (145) | `G/remote.rs` (`fn handle_packet`, `fn tick_remote`), `G/remote_*.rs`, `L/net.rs` | dedicated_server, server_entities, lan_e2e (all) | | 6 | Agent control, horizon-ctl (145) | `L/control.rs`, `L/bin/horizon-ctl/`, `G/control.rs`, `G/agent.rs`, `G/events.rs`, `G/ui_control.rs` | `python3 tools/agent_control_e2e.py`; `cargo test -p horizon-client --bin horizon-ctl` | @@ -32,7 +33,7 @@ file selects ~103. | 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | | 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | | 17 | HUD, chat, tab list (93) | `L/hud.rs`, `L/hud_layout.rs`, `L/hud_overlays.rs`, `L/chat.rs`, `G/chat.rs`, `L/tab_list.rs`, `L/locator_bar.rs`, `G/locator_bar.rs` | hud, tab_list, locator_bar, chat_screen, secure_chat | -| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | +| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `K/scoreboard.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | | 19 | Chunk streaming, light, tickets (85) | `L/streaming.rs`, `L/world.rs`, `L/chunk.rs`, `L/chunk_map.rs`, `L/light.rs`, `L/ticket_levels.rs`, `L/tick_chunk_membership.rs`, `G/world_loading.rs` | light, chunk_status, random_tick_sections; `cargo test -p horizon-client --test streaming_meshes` | | 20 | Mob models and animation (78) | `L/mobs/render.rs`, `L/mobs/anim.rs`, `L/mobs/body_anim.rs`, `L/mobs/keyframes.rs`, `L/entity.wgsl` | entity_model | | 21 | Block behaviour, server side (78) | `W/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `data.rs`, `redstone.rs`, `place.rs`), `G/block_entity_ticks.rs`, `G/moving_pistons.rs` | block_update, redstone, random_tick, simple_block, piston_movement, block_entity_tickers | @@ -52,6 +53,6 @@ file selects ~103. | 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser | | 36 | Audio and music (38) | `L/audio.rs`, `L/sound_engine.rs`, `L/sound_events.rs`, `L/music.rs`, `G/music.rs`, `L/ambience.rs`, `G/subtitle_hud.rs` | sound_engine, sound_event, music, situational_music, ambient_sound, subtitle | | 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e` (server-thread by default; portals, levels, distance, lava) | -| 38 | Command parsing (34) | `L/command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`) | command_parse (corpus `tools/command_parse_corpus.py`) | +| 38 | Command parsing (34) | `C/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); `cargo test -p horizon-command` | command_parse (corpus `tools/command_parse_corpus.py`) | | 39 | Benchmarks and telemetry (34) | `L/benchmark.rs`, `tools/perf_bench.py`, `L/telemetry.rs`, `crates/horizon-telemetry*/`, `crates/horizon-bench/` | `python3 -m unittest tests.test_perf_bench`; [benchmark.md](benchmark.md) | | 40 | Explosions and TNT (31) | `G/explosion.rs`, `G/tnt.rs` | lan_e2e blast; no dedicated harness yet | diff --git a/docs/version-ports.md b/docs/version-ports.md index 623e3c082..4ecad210f 100644 --- a/docs/version-ports.md +++ b/docs/version-ports.md @@ -43,7 +43,7 @@ to players. Players still prepare their own copy from their official launcher (` | `crates/horizon-client/src/lan/tracking.rs` | `generate_entity_tracking.py` | decompiled `EntityTypes` | | `crates/horizon-client/src/lan/command_suggestions.rs` | `generate_command_suggestions.py` | `VanillaCommandSuggestionsExporter` | | `crates/horizon-client/src/lan/command_order.rs` | `generate_lan_command_order.py` | vanilla's command tree | - | `crates/horizon-client/src/command/vanilla_order.rs` | `generate_command_order.py` | command-parse harness export | + | `crates/horizon-command/src/vanilla_order.rs` | `generate_command_order.py` | command-parse harness export | | `crates/horizon-world/src/datafix/block_state_data.txt` | `gen_block_state_data.py` | decompiled `BlockStateData` | | `crates/horizon-world/src/datafix/flat_tables.rs` | `gen_flat_tables.py` | 1.13 flattening fixers (never change) | diff --git a/tools/generate_command_order.py b/tools/generate_command_order.py index ab78b3ada..e7e1175ae 100644 --- a/tools/generate_command_order.py +++ b/tools/generate_command_order.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Generate crates/horizon-client/src/command/vanilla_order.rs: the order of +"""Generate crates/horizon-command/src/vanilla_order.rs: the order of the children of each node of vanilla's command tree where Horizon's tree registers them in a different order. Brigadier keeps children in registration order, and /help (smart usage) lists them that way. @@ -19,7 +19,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("vanilla", type=Path) parser.add_argument("rust", type=Path) - parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/command/vanilla_order.rs") + parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-command/src/vanilla_order.rs") args = parser.parse_args() vanilla = json.loads(args.vanilla.read_text()) rust = json.loads(args.rust.read_text()) diff --git a/tools/port_regen.py b/tools/port_regen.py index 8ce639f21..4d69b0986 100644 --- a/tools/port_regen.py +++ b/tools/port_regen.py @@ -251,7 +251,7 @@ GENERATORS = [ ("lan_command_order", ["crates/horizon-client/src/lan/command_order.rs"], lambda root, version, store, build: [python(), "tools/generate_lan_command_order.py"]), ("command_suggestions", ["crates/horizon-client/src/lan/command_suggestions.rs"], gen_suggestions), - ("vanilla_command_order", ["crates/horizon-client/src/command/vanilla_order.rs"], gen_vanilla_order), + ("vanilla_command_order", ["crates/horizon-command/src/vanilla_order.rs"], gen_vanilla_order), ] diff --git a/tools/port_report.py b/tools/port_report.py index 9006576dd..f8e81b6ee 100644 --- a/tools/port_report.py +++ b/tools/port_report.py @@ -40,7 +40,7 @@ GENERATORS = [ lambda d: bool(d["commands"]["added"] or d["commands"]["removed"] or d["commands"]["changed"])), ("crates/horizon-client/src/lan/command_order.rs", "python3 tools/generate_lan_command_order.py", lambda d: bool(d["commands"]["added"] or d["commands"]["removed"])), - ("crates/horizon-client/src/command/vanilla_order.rs", "python3 tools/generate_command_order.py", + ("crates/horizon-command/src/vanilla_order.rs", "python3 tools/generate_command_order.py", lambda d: bool(d["commands"]["added"] or d["commands"]["removed"])), ("crates/horizon-world/src/datafix/block_state_data.txt", "python3 tools/gen_block_state_data.py", lambda d: "net/minecraft/util/datafix/fixes/BlockStateData" in d["classes"]["changed"]), diff --git a/tools/test_lore_tooltip_parity.py b/tools/test_lore_tooltip_parity.py index d262a3542..e6869f7e9 100644 --- a/tools/test_lore_tooltip_parity.py +++ b/tools/test_lore_tooltip_parity.py @@ -35,7 +35,7 @@ if __name__ == '__main__': sources=[ lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs', - lab.ROOT / 'crates/horizon-client/src/text.rs', - lab.ROOT / 'crates/horizon-client/src/component.rs', + lab.ROOT / 'crates/horizon-client-core/src/text.rs', + lab.ROOT / 'crates/horizon-client-core/src/component.rs', ], expected_lines=len(CASES)) diff --git a/tools/test_resource_pack_parity.py b/tools/test_resource_pack_parity.py index 2d9ae2a85..a935e0b34 100644 --- a/tools/test_resource_pack_parity.py +++ b/tools/test_resource_pack_parity.py @@ -129,7 +129,7 @@ def main(): "Pack discovery, overlays, filters and the resource stacks vanilla merges.", sources=[lab.ROOT / "crates/horizon-client/src/packs.rs", lab.ROOT / "crates/horizon-client/src/sound_events.rs", - lab.ROOT / "crates/horizon-client/src/lang.rs"]) + lab.ROOT / "crates/horizon-client-core/src/lang.rs"]) total += len(QUERIES) print(f"{total} resource pack queries match the pinned client over {len(SELECTIONS)} selections") From 3e788469756ab71a5208394bbc0f4c888c290fb4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:31:28 +0100 Subject: [PATCH 007/132] Soul Speed: speed, no soul sand slowdown, boots wear, soul particles The enchantment's location_changed effects now run for the player: the movement_speed and movement_efficiency modifiers turn on over soul sand and soul soil and stay on while airborne, the boots wear with a 4% chance per block change, and walking on those blocks spawns soul particles and the soul escape sound. --- crates/horizon-client/src/game.rs | 1 + .../src/game/enchant_effects.rs | 157 +++++++++++++++++- crates/horizon-client/src/motion.rs | 37 +++++ 3 files changed, 192 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..515a69cc8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4342,6 +4342,7 @@ impl Game<'_> { }; self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; + self.tick_soul_speed(); self.tick_avatar(before, riding); self.end_spin_attack(spin_hit); self.record_combat(&events); diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index aa9f75e06..6550ba9d5 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -3,10 +3,15 @@ //! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power //! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`), //! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and -//! the armor attribute effects (respiration, depth strider, ...). +//! the armor attribute effects (respiration, depth strider, ...) and Soul +//! Speed's `location_changed` and `tick` effects. use super::Game; -use horizon_client::{enchant::EffectContext, items::ItemStack}; -use horizon_core::random::RandomSource; +use horizon_client::{ + enchant::{EffectContext, Enchantments, level_value}, + items::ItemStack, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; /// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`). #[derive(Clone, Copy)] @@ -460,6 +465,127 @@ impl Game<'_> { } ignite } + /// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of + /// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The + /// `location_changed` effects run when the player enters a new block, lands, + /// or its boots change: + /// - the speed and movement efficiency modifiers turn on over a soul speed + /// block (not flying, not riding) and stay on while airborne, then off + /// (`enchantment_active_check`); + /// - the boots lose 1 durability with a 4% chance when on such a block. + /// + /// Every fifth tick the player walking on one also gets soul particles and + /// sometimes a sound. A remote server applies and syncs all of this itself. + pub(super) fn tick_soul_speed(&mut self) { + const ID: &str = "minecraft:soul_speed"; + let Some(player) = self.player.as_mut() else { + return; + }; + if player.client_side { + return; + } + let level = self.armor[3] + .as_ref() + .map_or(0, |s| s.enchantment_level(ID)); + let position = player.position; + let (on_ground, flying) = (player.ground.on_ground, player.flying); + let moved = position.subtract(player.old_position); + let (tick, width) = (player.health.tick_count, player.dimensions.width); + let fx = &mut player.location_effects; + let on_soul = fx.on_soul_speed_block; + let block = BlockPos::containing(position); + let changed_block = fx.block.replace(block) != Some(block); + let landed = std::mem::take(&mut fx.landed); + // Changed boots: `stopLocationBasedEffects`, then the effects run again. + let equipped = std::mem::replace(&mut fx.boots_level, level) != level; + let was_active = fx.applied_level; + let mut active = was_active > 0 && !equipped; + let mut wear = false; + if level > 0 && (changed_block || landed || equipped) { + let riding = self.riding.is_some(); + let wanted = !riding && !flying && (on_soul || (active && !on_ground)); + active = wanted; + wear = on_ground && on_soul && self.world.random.next_float() < 0.04; + } + fx.applied_level = if active { level } else { 0 }; + // `Entity.getKnownMovement` horizontal speed of at least 1.0E-5. + let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10; + let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0; + // The attribute effects were applied to the player before: swap them. + if was_active > 0 && (!active || equipped) { + for (attribute, id, _, op) in + soul_speed_modifiers(&self.res.stations().enchantments, was_active) + { + let _ = player.set_modifier(&attribute, &id, 0.0, &op, false); + } + } + if active && (was_active == 0 || equipped) { + for (attribute, id, amount, op) in + soul_speed_modifiers(&self.res.stations().enchantments, level) + { + let _ = player.set_modifier(&attribute, &id, amount, &op, true); + } + } + if wear && !self.creative { + self.wear_boots(1); + } + if tick_effects { + // `spawn_particles`: in the bounding box, 0.1 above the feet, thrown + // back against the movement (-0.2) and up (0.1). + let r = &mut self.world.random; + let x = position.x + (r.next_double() - 0.5) * f64::from(width); + let z = position.z + (r.next_double() - 0.5) * f64::from(width); + self.particles.send_particles( + &ParticleOptions::simple(ParticleType::Soul), + [x, position.y + 0.1, z], + [moved.x * -0.2, 0.1, moved.z * -0.2], + 1.0, + 0, + ); + // `play_sound`: 35% chance, volume 0.6, pitch 0.6 to 1.0. + if r.next_float() < 0.35 { + let pitch = r.next_float() * 0.4 + 0.6; + self.audio.play( + "minecraft:particle.soul_escape", + Some([position.x, position.y, position.z]), + 0.6, + pitch, + ); + } + } + } + /// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`): + /// Unbreaking applies, and they break when worn out. + fn wear_boots(&mut self, amount: u32) { + let Some(stack) = self.armor[3].clone() else { + return; + }; + let loss = self.durability_loss(&stack, amount); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |info| info.max_damage); + if max == 0 { + return; + } + let Some(boots) = self.armor[3].as_mut() else { + return; + }; + boots.damage += loss; + if boots.damage >= max { + self.armor[3] = None; + if let Some(eye) = self.eye_position() { + self.audio.play( + "minecraft:entity.item.break", + Some(eye), + 0.8, + 0.8 + self.world.random.next_float() * 0.4, + ); + } + self.apply_equipment(); + } + } /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). /// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`), /// so the same enchantment on two pieces stacks instead of replacing itself. @@ -483,3 +609,28 @@ impl Game<'_> { self.potions.enchant_modifiers = wanted; } } + +/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation), +/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`. +fn soul_speed_modifiers( + enchantments: &Enchantments, + level: u32, +) -> Vec<(String, String, f64, String)> { + let Some(e) = enchantments.get("minecraft:soul_speed") else { + return Vec::new(); + }; + e.effects["minecraft:location_changed"][0]["effect"]["effects"] + .as_array() + .into_iter() + .flatten() + .filter(|a| a["type"] == "minecraft:attribute") + .map(|a| { + ( + a["attribute"].as_str().unwrap_or("").to_owned(), + format!("{}/feet", a["id"].as_str().unwrap_or("")), + f64::from(level_value(&a["amount"], level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + ) + }) + .collect() +} diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..156fc2549 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -50,6 +50,8 @@ pub struct MotionResources { pub attributes: Arc, pub blocks: BoundMovementProperties, pub climbable: BTreeSet, + /// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for. + pub soul_speed_blocks: BTreeSet, pub fall_reset: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, @@ -108,11 +110,29 @@ impl MotionResources { suppresses_bounce: tag("minecraft:suppresses_bounce")?, })?, climbable: tag("minecraft:climbable")?, + soul_speed_blocks: tag("minecraft:soul_speed_blocks")?, fall_reset: tag("minecraft:fall_damage_resetting")?, }) } } +/// What the `location_changed` enchantment effects (Soul Speed) need to know +/// between ticks. +#[derive(Clone, Debug, Default)] +pub struct LocationEffects { + /// `MovementAffectedByPredicate`: the block under the player + /// (`getBlockPosBelowThatAffectsMyMovement`) is in `#minecraft:soul_speed_blocks`. + pub on_soul_speed_block: bool, + /// `LivingEntity.lastPos`: the block the player was in last tick. + pub block: Option, + /// A landing ran `onChangedBlock` (`LivingEntity.checkFallDamage`). + pub landed: bool, + /// The Soul Speed level of the boots seen last tick (0: none). + pub boots_level: u32, + /// The Soul Speed level whose attribute modifiers are on the player (0: none). + pub applied_level: u32, +} + /// Ordered requests and phase records for world/audio/network consumers. Landing /// hurt dispatch updates stored health synchronously before these are drained. #[derive(Clone, Copy, Debug)] @@ -255,6 +275,8 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// Soul Speed's `location_changed` bookkeeping. + pub location_effects: LocationEffects, /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's /// spin. The damage stays until the game has dealt the hit. pub auto_spin_attack_ticks: i32, @@ -443,6 +465,7 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + location_effects: LocationEffects::default(), auto_spin_attack_ticks: 0, auto_spin_attack_dmg: 0.0, spin_targets: Vec::new(), @@ -984,6 +1007,7 @@ impl MotionWorld<'_, '_, '_> { ) }); self.player.try_add_frost(on_air)?; + self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?; if self.player.health.tick_count % 40 == 0 && self.player.is_fully_frozen() && self.player.can_freeze() @@ -996,6 +1020,15 @@ impl MotionWorld<'_, '_, '_> { } Ok(()) } + /// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`. + fn on_soul_speed_block(&mut self) -> Result { + let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?; + Ok(self + .assets + .registry + .state(self.block(on)) + .is_some_and(|s| self.resources.soul_speed_blocks.contains(&s.name))) + } /// Player.travel: swim steering, then LivingEntity.travel (fluids first, /// then gliding, then air), keeping 0.6 of the vertical speed while flying. fn player_travel(&mut self, input: Vec3) -> Result<()> { @@ -1834,6 +1867,10 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { if self.player.status.slow_falling || self.player.status.levitation.is_some() { self.player.fall_distance = 0.0; } + // LivingEntity.checkFallDamage: a landing runs onChangedBlock. + if grounded && self.player.fall_distance > 0.0 { + self.player.location_effects.landed = true; + } if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0 { self.player.events.push(MotionEvent::SmashLanding { From fd0cb002962ed5d1ae9488b913a4329f850532e1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:31:58 +0100 Subject: [PATCH 008/132] Axolotls dry out on land, squid squirt ink when a living entity hurts them --- .../src/game/commands/world_cmds.rs | 1 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/mobs.rs | 15 +++++- crates/horizon-client/src/mobs/ai.rs | 32 +++++++++++- crates/horizon-client/src/mobs/aquatic.rs | 52 +++++++++++++++++++ crates/horizon-client/src/mobs/axolotl.rs | 2 + 6 files changed, 101 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 30f019997..eac6f125f 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -108,6 +108,7 @@ impl Game<'_> { "in_fire" | "campfire" | "hot_floor" => DamageKind::InFire, "lava" => DamageKind::Lava, "drown" => DamageKind::Drown, + "dry_out" => DamageKind::DryOut, "magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic, "sting" => DamageKind::Sting, "cactus" | "sweet_berry_bush" => DamageKind::Cactus, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..b784b4c98 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3272,6 +3272,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) K::InFire => "minecraft:in_fire", K::Lava => "minecraft:lava", K::Drown => "minecraft:drown", + K::DryOut => "minecraft:dry_out", K::Magic => "minecraft:magic", K::Sting => "minecraft:sting", K::Cactus => "minecraft:cactus", diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..de9c7dfac 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -515,6 +515,8 @@ pub enum DamageKind { InFire, Lava, Drown, + /// `dry_out`: an axolotl out of water for too long. + DryOut, Magic, Sting, Cactus, @@ -573,7 +575,11 @@ impl Damage { pub fn causes_panic(&self) -> bool { !matches!( self.kind, - DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall + DamageKind::Fall + | DamageKind::Drown + | DamageKind::DryOut + | DamageKind::Generic + | DamageKind::InWall ) } /// DamageTypeTags.BYPASSES_ARMOR @@ -606,6 +612,7 @@ impl Damage { | DamageKind::InFire | DamageKind::Lava | DamageKind::Drown + | DamageKind::DryOut | DamageKind::Magic | DamageKind::Cactus | DamageKind::Generic @@ -1789,6 +1796,12 @@ impl Mob { } } } + // Squid.hurtServer: a squid hurt after a living entity hit it squirts ink. + if matches!(self.species(), Species::Squid | Species::GlowSquid) + && self.ai.last_hurt_by.is_some() + { + aquatic::spawn_ink(self); + } true } /// LivingEntity.knockback(power, xd, zd) towards the negative direction. diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..403f63101 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -441,6 +441,34 @@ pub fn tick_swing(m: &mut Mob) { } m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; } +/// `LivingEntity.baseTick` refills a breather's air by 4, then +/// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills +/// it, anywhere else it runs down from the pre-tick value, and at -20 the +/// axolotl dries out. +fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) { + let before = m.air; + m.air = (m.air + 4).min(super::axolotl::MAX_AIR); + if m.no_ai { + return; + } + // Entity.isInRain: rain at the block, or at the top of the box. + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let top = (m.position.y + f64::from(m.height())).floor() as i32; + let in_rain = w.raining && (w.can_see_sky(x, y, z) || w.can_see_sky(x, top, z)); + if m.fluids.in_water || in_rain { + m.air = super::axolotl::MAX_AIR; + } else { + m.air = before - 1; + if m.air <= -20 { + m.air = 0; + m.damage(2.0, Damage::of(DamageKind::DryOut)); + } + } +} /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.was_eye_in_water = m.fluids.eye_in_water; @@ -500,7 +528,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.damage(1.0, Damage::of(DamageKind::InWall)); } // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). - if m.kind.flags.needs_water { + if m.species() == Species::Axolotl { + axolotl_air_supply(m, w); + } else if m.kind.flags.needs_water { if !m.fluids.in_water { m.air -= 1; if m.air == -20 { diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index dc80c6ea4..9603d5e58 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -24,6 +24,57 @@ const Z_BODY_ROT: usize = 3; const TENTACLE_SPEED: usize = 4; const ROTATE_SPEED: usize = 5; +/// `Squid.spawnInk`: the squirt sound and 30 ink particles shot from under +/// the squid, turned by its body rotation. +pub fn spawn_ink(m: &mut Mob) { + let sound = if m.species() == Species::GlowSquid { + "entity.glow_squid.squirt" + } else { + "entity.squid.squirt" + }; + let kind = if m.species() == Species::GlowSquid { + "glow_squid_ink" + } else { + "squid_ink" + }; + if !m.silent { + let pitch = m.voice_pitch(); + let at = [m.position.x, m.position.y, m.position.z]; + m.outbox.push(MobEvent::Sound( + sound, + at, + super::ai::sound_volume(m), + pitch, + )); + } + // rotateVector: xRot(xBodyRotO), then yRot(-yBodyRotO). + let to_radians = (std::f64::consts::PI / 180.0) as f32; + let (x_rot, y_rot) = ( + m.anim.vo[X_BODY_ROT] * to_radians, + -m.previous_body_yaw * to_radians, + ); + let rotate = |v: Vec3| v.rotate_x(x_rot).rotate_y(y_rot); + let pos = rotate(Vec3::new(0.0, -1.0, 0.0)).add_vector(m.position); + let offset_scale: f32 = if m.is_baby() { 0.1 } else { 0.3 }; + for _ in 0..30 { + let x = f64::from(m.random.next_float()) * 0.6 - 0.3; + let z = f64::from(m.random.next_float()) * 0.6 - 0.3; + let dir = rotate(Vec3::new(x, -1.0, z)); + let d = dir.scale(f64::from(offset_scale + m.random.next_float() * 2.0)); + // ServerLevel.sendParticles with a count of 0 and speed 0.1: one + // particle moving at the float offset times the float speed. + let speed = f64::from(0.1f32); + m.outbox.push(MobEvent::ParticleAt { + kind, + at: [pos.x, pos.y + 0.5, pos.z], + velocity: [ + speed * f64::from(d.x as f32), + speed * f64::from(d.y as f32), + speed * f64::from(d.z as f32), + ], + }); + } +} pub fn register(m: &mut Mob) { use Species as S; match m.species() { @@ -36,6 +87,7 @@ pub fn register(m: &mut Mob) { m.anim.v[TENTACLE_SPEED] = speed; } S::Axolotl => { + m.air = super::axolotl::MAX_AIR; // Native controller scaling is essential: the base speed attribute is 1.0. m.ai.mov.kind = MoveKind::SmoothSwimming { max_turn_x: 85.0, diff --git a/crates/horizon-client/src/mobs/axolotl.rs b/crates/horizon-client/src/mobs/axolotl.rs index 55f15717c..2815418e3 100644 --- a/crates/horizon-client/src/mobs/axolotl.rs +++ b/crates/horizon-client/src/mobs/axolotl.rs @@ -3,6 +3,8 @@ use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::Anim use horizon_core::random::RandomSource; pub const PLAY_DEAD_TICKS: i32 = 200; pub const HUNTING_COOLDOWN: i64 = 2400; +/// `Axolotl.getMaxAirSupply`. +pub const MAX_AIR: i32 = 6000; /// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown. pub fn prey_eligible( From 628ff01a44d74c43c2e0a2db4afbec532f4fab95 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:35:52 +0100 Subject: [PATCH 009/132] Only zombies that break doors and raiding vindicators get through doors Mobs no longer open or break doors on their own except villagers and copper golems. Zombies that rolled canBreakDoors break doors on hard, and vindicators break doors on normal and hard and open them during a raid, as BreakDoorGoal, VindicatorBreakDoorGoal and RaiderOpenDoorGoal do. A zombie's CanBreakDoors value is now saved and loaded. --- crates/horizon-client/src/entity_nbt.rs | 12 +- crates/horizon-client/src/game.rs | 10 +- crates/horizon-client/src/game/creatures.rs | 15 ++ crates/horizon-client/src/game/raids.rs | 2 + crates/horizon-client/src/mobs.rs | 19 ++ crates/horizon-client/src/mobs/ai.rs | 1 + crates/horizon-client/src/mobs/doors.rs | 252 ++++++++++++++++++++ crates/horizon-client/src/mobs/finalize.rs | 5 +- crates/horizon-client/src/mobs/illager.rs | 9 + crates/horizon-client/src/mobs/raider.rs | 3 + crates/horizon-client/src/mobs/spawning.rs | 5 + crates/horizon-client/src/mobs/undead.rs | 4 + 12 files changed, 333 insertions(+), 4 deletions(-) create mode 100644 crates/horizon-client/src/mobs/doors.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 00576ea02..ba0a62489 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -482,7 +482,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "minecraft:zombie" => { map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); for (key, value) in [ - ("CanBreakDoors", Tag::Byte(0)), ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1)), ] { @@ -507,6 +506,13 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } _ => {} } + // Zombie.addAdditionalSaveData: CanBreakDoors. + if crate::mobs::doors::is_zombie(m.species()) { + map.insert( + "CanBreakDoors".into(), + Tag::Byte(i8::from(m.extra.can_break_doors)), + ); + } crate::mobs::raider::write_nbt(m, map); crate::mobs::riders::write_nbt(m, map); // LivingEntity equipment: what the mob holds now. @@ -925,6 +931,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") { crate::mobs::finalize::set_baby(&mut m, true); } + // Zombie.readAdditionalSaveData: setCanBreakDoors. + if crate::mobs::doors::is_zombie(m.species()) { + crate::mobs::doors::set_can_break_doors(&mut m, flag(tag, "CanBreakDoors")); + } crate::mobs::raider::read_nbt(&mut m, tag); crate::mobs::riders::read_nbt(&mut m, tag); // A mob saved mid-death finishes dying; one saved dead is dropped. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..a3400f252 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2817,6 +2817,9 @@ impl Game<'_> { 1501 => Some(("minecraft:block.lava.extinguish", 0.5)), 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), + // LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break). + 1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)), + 1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), @@ -2836,9 +2839,14 @@ impl Game<'_> { 1029 | 1030 | 1042 | 1043 | 1044 => { self.world.random.next_float() * 0.1 + 0.9 } + 1019 | 1021 => { + (self.world.random.next_float() - self.world.random.next_float()) + * 0.2 + + 1.0 + } _ => 1.0, }; - if matches!(id, 1029 | 1030) { + if matches!(id, 1019 | 1021 | 1029 | 1030) { // Clients play the anvil sound from its level event; // capturing it also sends a duplicate sound packet. self.audio.play_unshared(name, c, volume, pitch); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..4613ad5f7 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1043,6 +1043,21 @@ impl Game<'_> { self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open)); self.process_level_events()?; } + MobEvent::BreakDoor { pos } => { + // BreakDoorGoal.tick: removeBlock, then level events 1021 + // and 2001 with the state that is there now. + let air = self.world.air; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, air, 3)); + self.process_level_events()?; + self.level_event_at(1021, pos, 0); + let left = self.world.block(pos[0], pos[1], pos[2]); + self.level_event_at(2001, pos, left.0 as i32); + } + MobEvent::DestroyProgress { mob, pos, progress } => { + self.destroy_block_progress(mob as i32, pos, progress); + } + MobEvent::LevelEvent { id, pos, data } => self.level_event_at(id, pos, data), MobEvent::SetBlockName { pos, name, effect } => { if effect { let old = self.world.block(pos[0], pos[1], pos[2]); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index bedca5708..743f02f44 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -796,6 +796,8 @@ impl Game<'_> { let s = m.extra.raider.get_or_insert_with(Box::default); s.rider = has_rider; s.in_village = in_village; + // Vindicator.customServerAiStep: `ServerLevel.isRaided`. + s.raided = species == Species::Vindicator && raids.nearby(block).is_some(); if s.raid_id.is_some_and(|id| raids.get(id).is_none()) { s.raid_id = None; s.ticks_outside_raid = 0; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..1d7f337e1 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -25,6 +25,7 @@ pub mod creaking; pub mod creaking_heart; pub mod cube; pub mod data; +pub mod doors; pub mod drops; pub mod enderman; pub mod equine; @@ -1001,6 +1002,24 @@ pub enum MobEvent { pos: [i32; 3], open: bool, }, + /// `BreakDoorGoal.tick` at its end: the door is removed (`removeBlock`), + /// then level events 1021 and 2001 with the state that is left there. + BreakDoor { + pos: [i32; 3], + }, + /// `Level.destroyBlockProgress` for a mob's crack on a block (`-1` + /// clears it). + DestroyProgress { + mob: u32, + pos: [i32; 3], + progress: i32, + }, + /// `Level.levelEvent`: the game plays and sends the event. + LevelEvent { + id: i32, + pos: [i32; 3], + data: i32, + }, /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). BreakBlock { pos: [i32; 3], diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..d5eb76202 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -944,6 +944,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { | Species::Parched | Species::WitherSkeleton | Species::ZombifiedPiglin => undead::custom_server_ai_step(m, cx), + Species::Vindicator => super::illager::vindicator_server_ai_step(m), Species::Enderman => super::enderman::custom_server_ai_step(m, cx), Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), diff --git a/crates/horizon-client/src/mobs/doors.rs b/crates/horizon-client/src/mobs/doors.rs new file mode 100644 index 000000000..a55ab9863 --- /dev/null +++ b/crates/horizon-client/src/mobs/doors.rs @@ -0,0 +1,252 @@ +//! Doors a mob gets through on its own: `DoorInteractGoal` with its two +//! users, `BreakDoorGoal` (zombies that can break doors, vindicators in a +//! raid) and `OpenDoorGoal` (`AbstractIllager.RaiderOpenDoorGoal`). +use super::{ + Mob, MobEvent, MobWorld, Species, + goals::{Cx, Goal, MOVE, goal_clone, reduced}, + nav::NavKind, + raider, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// `DefaultDoorBreakTime`: `BreakDoorGoal.getDoorBreakTime` is +/// `max(240, doorBreakTime)`, and the vindicator's 6 is below it. +const DOOR_BREAK_TIME: i32 = 240; + +/// `GoalUtils.hasGroundPathNavigation`: ground, wall-climbing and +/// amphibious navigations walk. +pub fn can_navigate_ground(m: &Mob) -> bool { + matches!( + m.ai.nav.kind, + NavKind::Ground | NavKind::WallClimber | NavKind::Amphibious + ) +} +/// `Zombie.setCanBreakDoors`: only a mob that walks can break doors, and +/// then its navigation opens them. +pub fn set_can_break_doors(m: &mut Mob, can_break: bool) { + let can_break = can_break && can_navigate_ground(m); + m.extra.can_break_doors = can_break; + m.ai.nav.can_open_doors = can_break; +} +/// The species that extend `Zombie` (`CanBreakDoors` is theirs to save). +pub fn is_zombie(s: Species) -> bool { + matches!( + s, + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + ) +} +/// `DoorBlock.isWoodenDoor`: a door a hand opens, which is any but iron. +fn wooden_door(w: &MobWorld, p: [i32; 3]) -> bool { + let name = w.block_name(p[0], p[1], p[2]); + name.ends_with("_door") && name != "minecraft:iron_door" +} +/// `DoorInteractGoal`'s door: where it is and whether one is there. +#[derive(Clone, Debug, Default)] +struct Interact { + door: [i32; 3], + has_door: bool, +} +impl Interact { + /// `DoorInteractGoal.canUse`: the mob bumped into something and a + /// wooden door is on its path within 1.5 blocks, or at its own head. + fn can_use(&mut self, m: &Mob, w: &MobWorld) -> bool { + if !can_navigate_ground(m) || !m.horizontal_collision { + return false; + } + let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) else { + return false; + }; + for node in path + .nodes + .iter() + .take((path.next + 2).min(path.nodes.len())) + { + self.door = [node.x, node.y + 1, node.z]; + let dx = m.position.x - f64::from(node.x); + let dz = m.position.z - f64::from(node.z); + if dx * dx + dz * dz <= 2.25 { + self.has_door = wooden_door(w, self.door); + if self.has_door { + return true; + } + } + } + let at = m.position; + self.door = [ + at.x.floor() as i32, + at.y.floor() as i32 + 1, + at.z.floor() as i32, + ]; + self.has_door = wooden_door(w, self.door); + self.has_door + } + /// `DoorInteractGoal.isOpen`: the door is still there and open. + fn is_open(&mut self, w: &MobWorld) -> bool { + if !self.has_door { + return false; + } + let d = self.door; + if !w.block_name(d[0], d[1], d[2]).ends_with("_door") { + self.has_door = false; + return false; + } + w.prop(d[0], d[1], d[2], "open") == Some("true") + } + /// `DoorInteractGoal.setOpen`. + fn set_open(&self, cx: &mut Cx, open: bool) { + let d = self.door; + if self.has_door && cx.w.block_name(d[0], d[1], d[2]).ends_with("_door") { + cx.events.push(MobEvent::SetDoorOpen { pos: d, open }); + } + } +} +/// `BlockPos.closerToCenterThan`. +fn closer_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ) + .distance_squared(at) + < distance * distance +} + +/// `BreakDoorGoal`: crack the door in the way for 240 ticks, then remove it. +/// A zombie does it on hard only; `Vindicator.VindicatorBreakDoorGoal` on +/// normal and hard, in a raid, and holds the mob's movement. +#[derive(Clone, Debug)] +pub struct BreakDoor { + interact: Interact, + vindicator: bool, + break_time: i32, + last_break_progress: i32, +} +impl BreakDoor { + /// `Zombie.breakDoorGoal`, added when the zombie can break doors. + pub fn zombie() -> Self { + Self::new(false) + } + /// `Vindicator.VindicatorBreakDoorGoal`. + pub fn vindicator() -> Self { + Self::new(true) + } + fn new(vindicator: bool) -> Self { + Self { + interact: Interact::default(), + vindicator, + break_time: 0, + last_break_progress: -1, + } + } + /// `DOOR_BREAKING_PREDICATE`. + fn valid_difficulty(&self, w: &MobWorld) -> bool { + if self.vindicator { + w.difficulty.normal || w.difficulty.hard + } else { + w.difficulty.hard + } + } + /// `BreakDoorGoal.canUse` after `DoorInteractGoal.canUse`. + fn can_break(&mut self, m: &Mob, w: &MobWorld) -> bool { + self.interact.can_use(m, w) + && w.mob_griefing + && self.valid_difficulty(w) + && !self.interact.is_open(w) + } +} +impl Goal for BreakDoor { + goal_clone!(); + fn flags(&self) -> u8 { + if self.vindicator { MOVE } else { 0 } + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.vindicator { + return raider::has_active_raid(m) + && m.random.next_int_bound(reduced(10)).unwrap_or(1) == 0 + && self.can_break(m, cx.w); + } + m.extra.can_break_doors && self.can_break(m, cx.w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (!self.vindicator || raider::has_active_raid(m)) + && self.break_time <= DOOR_BREAK_TIME + && !self.interact.is_open(cx.w) + && closer_to_center(self.interact.door, m.position, 2.0) + && self.valid_difficulty(cx.w) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.break_time = 0; + if self.vindicator { + m.ai.no_action_time = 0; + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + cx.events.push(MobEvent::DestroyProgress { + mob: m.id, + pos: self.interact.door, + progress: -1, + }); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let door = self.interact.door; + if m.random.next_int_bound(20).unwrap_or(1) == 0 { + cx.events.push(MobEvent::LevelEvent { + id: 1019, + pos: door, + data: 0, + }); + if !m.ai.swinging { + m.swing(); + } + } + self.break_time += 1; + let progress = (self.break_time as f32 / DOOR_BREAK_TIME as f32 * 10.0) as i32; + if progress != self.last_break_progress { + cx.events.push(MobEvent::DestroyProgress { + mob: m.id, + pos: door, + progress, + }); + self.last_break_progress = progress; + } + if self.break_time == DOOR_BREAK_TIME && self.valid_difficulty(cx.w) { + cx.events.push(MobEvent::BreakDoor { pos: door }); + } + } +} + +/// `AbstractIllager.RaiderOpenDoorGoal` (`OpenDoorGoal` that does not wait +/// to close): open the door in the way during a raid. It never continues, so +/// it closes the door again as soon as it stops. +#[derive(Clone, Debug, Default)] +pub struct RaiderOpenDoor { + interact: Interact, +} +impl Goal for RaiderOpenDoor { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.interact.can_use(m, cx.w) && raider::has_active_raid(m) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } + fn start(&mut self, _m: &mut Mob, cx: &mut Cx) { + self.interact.set_open(cx, true); + } + fn stop(&mut self, _m: &mut Mob, cx: &mut Cx) { + self.interact.set_open(cx, false); + } +} diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 4eeed885b..4e58e9475 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1144,7 +1144,8 @@ impl Ctx<'_, L, R> { } } } - m.extra.can_break_doors = self.float() < special * 0.1; + let can_break_doors = self.float() < special * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); if reason != Reason::Conversion { self.populate(m); self.enchant(m); @@ -1205,7 +1206,7 @@ impl Ctx<'_, L, R> { ) { m.health = max_health(m); } - m.extra.can_break_doors = true; + super::doors::set_can_break_doors(m, true); } } fn husk(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 45ef076d3..641a474f6 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -72,6 +72,8 @@ pub fn register_vindicator(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, Float); g.add(1, avoid_creaking(1.0, 1.2)); + g.add(2, super::doors::BreakDoor::vindicator()); + g.add(3, super::doors::RaiderOpenDoor::default()); g.add(4, super::raider::HoldGroundAttack::new(10.0)); g.add(5, MeleeAttack::new(1.0, false)); g.add(8, Stroll::new(0.6)); @@ -86,6 +88,13 @@ pub fn register_vindicator(m: &mut Mob) { .when(|m, _| m.custom_name.as_deref() == Some("Johnny")), ); } +/// `Vindicator.customServerAiStep`: its navigation opens doors while a raid +/// is at its position. +pub fn vindicator_server_ai_step(m: &mut Mob) { + if super::doors::can_navigate_ground(m) { + m.ai.nav.can_open_doors = super::raider::state(m).is_some_and(|s| s.raided); + } +} // Evoker state: `counter` spellCastingTickCount, `variant2` the spell // being cast (0 none, 1 vexes, 2 fangs, 3 wololo), `counter2` the wololo // sheep's id. diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 6c3ab9b64..d2ed62374 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -30,6 +30,9 @@ pub struct State { pub celebrating: bool, /// The raid is active (`hasActiveRaid`); set by the game every tick. pub active_raid: bool, + /// A raid is active within 96 blocks (`ServerLevel.isRaided`); set by + /// the game every tick for vindicators. + pub raided: bool, /// The raid is won or lost (`Raid.isOver`), lost (`isLoss`). pub raid_over: bool, pub raid_loss: bool, diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..f4e55e7d0 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -35,6 +35,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b #[derive(Clone, Copy, Debug)] pub struct LocalDifficulty { pub effective: f32, + /// The world difficulty is normal. + pub normal: bool, /// The world difficulty is hard. pub hard: bool, } @@ -45,9 +47,11 @@ impl LocalDifficulty { /// the overworld clock, the chunk's inhabited time and the moon. pub fn new(base: u8, total: i64, inhabited: i64, moon: f32) -> Self { let hard = base == 3; + let normal = base == 2; if base == 0 { return Self { effective: 0.0, + normal, hard, }; } @@ -60,6 +64,7 @@ impl LocalDifficulty { } Self { effective: f32::from(base) * (0.75 + global + local), + normal, hard, } } diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index e77a37641..b96ad2091 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -2,6 +2,7 @@ //! stray, bogged, wither skeleton): goals, bow attacks, water conversion. use super::{ Mob, MobEvent, Species, Who, + doors::BreakDoor, goals::{ Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone, @@ -15,6 +16,7 @@ pub fn register(m: &mut Mob) { match m.species() { S::Zombie | S::Husk | S::ZombieVillager => { let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); @@ -42,6 +44,7 @@ pub fn register(m: &mut Mob) { S::ZombifiedPiglin => { // ZombifiedPiglin.addBehaviourGoals: neutral until provoked. let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); g.add(2, MeleeAttack::new(1.0, false).zombie()); @@ -58,6 +61,7 @@ pub fn register(m: &mut Mob) { S::Drowned => { // Zombie.registerGoals, then Drowned.addBehaviourGoals. let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); From bd59cdc25cc3da28287933f55aa0aaf0a5608cd0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:39:16 +0100 Subject: [PATCH 010/132] Let turtles lay eggs that hatch into baby turtles A bred turtle now carries an egg instead of the baby appearing at once. She walks home, digs into sand for a while and lays a turtle egg there. A hatching egg gives one baby turtle per egg with the egg as its home, and a baby that grows up drops a scute. --- crates/horizon-client/src/entity_nbt.rs | 14 ++ crates/horizon-client/src/game.rs | 5 + crates/horizon-client/src/game/creatures.rs | 63 +++++- crates/horizon-client/src/mobs.rs | 7 + crates/horizon-client/src/mobs/ai.rs | 11 ++ crates/horizon-client/src/mobs/body_anim.rs | 4 +- crates/horizon-client/src/mobs/goals.rs | 8 + crates/horizon-client/src/mobs/turtle.rs | 209 ++++++++++++++++++++ 8 files changed, 318 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/mobs/turtle.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 00576ea02..f7c843264 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -357,6 +357,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "minecraft:bat" => { map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag))); } + "minecraft:turtle" => { + map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag))); + if let Some(home) = m.extra.home { + map.insert("home_pos".into(), Tag::IntArray(home.to_vec())); + } + } "minecraft:creaking" => { // home_pos: the heart it is bound to. if let Some(home) = m.extra.home { @@ -847,6 +853,14 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - { crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]); } + if m.species() == crate::mobs::Species::Turtle { + // Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`. + m.extra.flag = flag(tag, "has_egg"); + m.extra.home = match tag.get("home_pos") { + Some(Tag::IntArray(home)) if home.len() == 3 => Some([home[0], home[1], home[2]]), + _ => None, + }; + } if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..f29a71f20 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2968,6 +2968,11 @@ impl Game<'_> { kind: "hatch_sniffer", .. } => self.hatch_sniffer([pos.x, pos.y, pos.z]), + LevelEvent::BlockEvent { + pos, + state, + kind: "hatch_turtles", + } => self.hatch_turtles([pos.x, pos.y, pos.z], state), LevelEvent::BlockEvent { pos, kind: "portal_spawn", diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..03911ffda 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1185,6 +1185,10 @@ impl Game<'_> { self.mob_vibration_particle(from, to, ticks) } MobEvent::DigParticles { at } => self.warden_dig_particles(at), + MobEvent::BlockBreakEffect { pos, block } => { + let state = self.world.block(block[0], block[1], block[2]); + self.destroy_particles(pos, state); + } MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius), MobEvent::CreakingHurt { home, @@ -1222,6 +1226,11 @@ impl Game<'_> { } } MobEvent::GiftLoot { table, at } => { + // Turtle.ageBoundaryReached: only with mob loot on. + if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops") + { + continue; + } let drops = self.res .items() @@ -1234,6 +1243,39 @@ impl Game<'_> { } Ok(()) } + /// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle + /// per egg, a day from grown, with the egg as its home (the sound, the + /// crumbs and the block's removal came from the level). + pub(super) fn hatch_turtles( + &mut self, + pos: [i32; 3], + state: horizon_world::registry::BlockStateId, + ) { + let eggs = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("eggs")) + .and_then(|v| v.parse::().ok()) + .unwrap_or(1); + for i in 0..eggs { + let at = [ + f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2, + f64::from(pos[1]), + f64::from(pos[2]) + 0.3, + ]; + if let Some(id) = self.spawn_mob("minecraft:turtle", at, true) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.extra.age = -24000; + m.extra.home = Some(pos); + m.yaw = 0.0; + m.body_yaw = 0.0; + m.head_yaw = 0.0; + } + } + } fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) { let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { return; @@ -1289,6 +1331,8 @@ impl Game<'_> { .unwrap_or_else(|| parent.clone()); let mut child = parent.clone(); child.baby = true; + // TurtleBreedGoal.breed triggers it without a child. + let turtle = p.species() == Species::Turtle; if matches!( ( p.species(), @@ -1301,7 +1345,7 @@ impl Game<'_> { ) { child.kind = "minecraft:mule".into(); } - self.trigger_bred(&parent, &partner_view, Some(&child)); + self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child)); } if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) { q.extra.age = 6000; @@ -1313,6 +1357,15 @@ impl Game<'_> { self.lay_sniffer_egg(&p); return; } + // TurtleBreedGoal.breed: the goal gave the mother her egg; only the + // experience is left, and only with mob loot on. + if p.species() == Species::Turtle { + if self.ui.rules.bool("mob_drops") { + let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; + self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + } + return; + } let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0; let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0; // A horse and a donkey have a mule. @@ -2542,6 +2595,7 @@ impl Game<'_> { let mut handled = true; let mut drops: Vec<(String, u32)> = Vec::new(); let is_food = m.kind.food.contains(&item); + let baby_turtle = species == Species::Turtle && m.is_baby(); match species { Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => { give = Some("minecraft:milk_bucket"); @@ -2820,6 +2874,13 @@ impl Game<'_> { if !handled { return Ok(false); } + // Turtle.ageBoundaryReached: food that finishes a baby's growth. + if baby_turtle && !self.mobs[index].is_baby() { + self.handle_mob_events(vec![MobEvent::GiftLoot { + table: "minecraft:gameplay/turtle_grow", + at: feet, + }])?; + } self.swing_arm(); if let Some(s) = sound { let pitch = diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..0a158333d 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -68,6 +68,7 @@ pub mod tame; pub mod trader; pub mod transport_items; pub mod trial_spawner; +pub mod turtle; pub mod undead; pub mod vex; pub mod villager; @@ -1151,6 +1152,12 @@ pub enum MobEvent { DigParticles { at: [f64; 3], }, + /// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at + /// `block`: a turtle's digging. + BlockBreakEffect { + pos: [i32; 3], + block: [i32; 3], + }, /// `Warden.applyDarknessAround`: darkness for survival players nearby. Darkness { at: [f64; 3], diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..f0d5db934 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -183,6 +183,9 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Rabbit { super::rabbit::register(m); } + if m.species() == Species::Turtle { + super::turtle::register(m); + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -712,6 +715,13 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // setAge at the age boundary: refreshDimensions. if m.extra.age >= 0 { m.fudge_position_after_size_change(w, bw, bh); + // Turtle.ageBoundaryReached: a grown turtle drops a scute. + if m.species() == Species::Turtle { + events.push(MobEvent::GiftLoot { + table: "minecraft:gameplay/turtle_grow", + at: [m.position.x, m.position.y, m.position.z], + }); + } } } else if m.extra.age > 0 { m.extra.age -= 1; @@ -999,6 +1009,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Turtle => super::turtle::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; } diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 4411d347b..bbb44c5ab 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { s, &Turtle { on_land: !m.fluids.in_water && m.on_ground, - laying_egg: false, - has_egg: false, + laying_egg: m.extra.flag2, + has_egg: m.extra.flag, }, ), Species::Strider => strider(p, s, m.rider.is_some()), diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 7f73e32c4..7cb3011c9 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1762,6 +1762,10 @@ impl Goal for Breed { if tamable && (!m.extra.tame || m.extra.sitting) { return false; } + // TurtleBreedGoal.canUse: not while carrying an egg. + if species == Species::Turtle && super::turtle::has_egg(m) { + return false; + } let id = m.id; // Horses and donkeys breed together (AbstractHorse.canParent: tame). // Sniffer.canMate: calm states only. @@ -1832,6 +1836,10 @@ impl Goal for Breed { }); m.extra.in_love = 0; m.extra.age = 6000; + // TurtleBreedGoal.breed: the mother carries an egg, not a baby. + if m.species() == Species::Turtle { + m.extra.flag = true; + } cx.events.push(MobEvent::Breed { parent: m.id, partner: p.id, diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs new file mode 100644 index 000000000..0596adfdf --- /dev/null +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -0,0 +1,209 @@ +//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her +//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand +//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`, +//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. +use super::{ + Mob, MobEvent, MobWorld, + goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced}, +}; +use horizon_core::random::RandomSource; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(1, Breed::new(1.0)); + g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1))); + g.add(4, GoHome::default()); +} +/// `Turtle.hasEgg`. +pub fn has_egg(m: &Mob) -> bool { + m.extra.flag +} +/// `Turtle.setLayingEgg`. +fn set_laying_egg(m: &mut Mob, on: bool) { + m.extra.counter = i32::from(on); + m.extra.flag2 = on; +} +/// `homePos.closerToCenterThan(position, distance)`; a turtle that never +/// had a home is at home where it stands. +fn close_to_home(m: &Mob, distance: f64) -> bool { + let home = m.extra.home.unwrap_or([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]); + let d = [ + f64::from(home[0]) + 0.5 - m.position.x, + f64::from(home[1]) + 0.5 - m.position.y, + f64::from(home[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance +} +fn block_of(m: &Mob) -> [i32; 3] { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] +} +/// `TurtleEggBlock.isSand`. +fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool { + w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2])) +} +/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 { + let at = block_of(m); + let below = [at[0], at[1] - 1, at[2]]; + if is_sand(w, below) { + events.push(MobEvent::BlockBreakEffect { + pos: at, + block: below, + }); + } + } +} + +/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home +/// walks to sand with air above, digs for 200 ticks and lays it. +#[derive(Clone, Debug)] +struct LayEgg(MoveToBlock); +impl LayEgg { + /// `isValidTarget`: sand with air above it. + fn valid(w: &MobWorld, p: [i32; 3]) -> bool { + w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p) + } +} +impl Goal for LayEgg { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn name(&self) -> &'static str { + "TurtleLayEggGoal" + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !(has_egg(m) && close_to_home(m, 9.0)) { + return false; + } + // MoveToBlockGoal.canUse. + if self.0.next_start > 0 { + self.0.next_start -= 1; + return false; + } + self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.0.find_nearest(m, cx.w, Self::valid) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx.w); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx.w); + if m.fluids.in_water || !self.0.reached { + return; + } + if m.extra.counter < 1 { + set_laying_egg(m, true); + } else if m.extra.counter > 200 { + let at = [m.position.x, m.position.y, m.position.z]; + let pitch = 0.9 + m.random.next_float() * 0.2; + cx.events + .push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch)); + // Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand. + let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1; + let registry = cx.w.registry; + let state = registry + .default_state("minecraft:turtle_egg") + .and_then(|d| registry.state(d).cloned()) + .and_then(|mut s| { + s.properties.insert("eggs".into(), eggs.to_string()); + registry.resolve(&s).ok() + }); + let b = self.0.block; + if let Some(state) = state { + cx.events.push(MobEvent::SetBlock { + pos: [b[0], b[1] + 1, b[2]], + state, + }); + } + m.extra.flag = false; + set_laying_egg(m, false); + m.extra.in_love = 600; + } + if m.extra.flag2 { + m.extra.counter += 1; + } + } +} + +/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult +/// that strayed 64 blocks away does now and then. +#[derive(Clone, Debug, Default)] +struct GoHome { + stuck: bool, + close_to_home_try_ticks: i32, +} +impl Goal for GoHome { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn name(&self) -> &'static str { + "TurtleGoHomeGoal" + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + if m.is_baby() { + false + } else if has_egg(m) { + true + } else { + m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0) + } + } + fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) { + self.stuck = false; + self.close_to_home_try_ticks = 0; + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let home = m.extra.home.unwrap_or(block_of(m)); + let close = close_to_home(m, 16.0); + if close { + self.close_to_home_try_ticks += 1; + } + if !m.ai.nav.is_done() { + return; + } + let to = [ + f64::from(home[0]) + 0.5, + f64::from(home[1]), + f64::from(home[2]) + 0.5, + ]; + let mut next = m + .default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0) + .or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2)); + if let Some(at) = next + && !close + && cx.w.block_name( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ) != "minecraft:water" + { + next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2); + } + match next { + Some(at) => { + m.nav_move_to(cx.w, at, 1.0); + } + None => self.stuck = true, + } + } +} From 5eef2bea0c1ed8ea945ce84fff9d391f97d45329 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:45:59 +0000 Subject: [PATCH 011/132] Clean up evoker summons after fang integration check Remove the test arena's surviving vexes so later checks receive no stray attacks. Co-Authored-By: OpenCode GPT-6.1 Sol --- tools/lan_e2e.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 816fe9b82..1b2a7219b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6977,6 +6977,8 @@ def check_fangs(host, guest, out): finally: host('command', command='tick unfreeze') host('command', command=f'kill @e[tag={tag}]') + # The evoker can summon vexes before fangs; killing it leaves those summons alive. + host('command', command=f'kill @e[type=minecraft:vex,x={x},y={y},z={z},distance=..32]') guest('command', command='effect clear @s') face_each_other(host, guest) return {'fangs': len(paths['host']), 'warmup': warmup, 'drawn': drawn, 'removed': True} From 1d51f9d873b7ec024f9ceba69b57c9e2b3178977 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:48:30 +0100 Subject: [PATCH 012/132] Soul Speed: draw the random chances in vanilla's order Both random_chance terms come first in their all_of conditions, so the level random is drawn before the block and movement checks: the boots' 4% on every location change, and the sound's 35% on every tick the boots are worn. Co-Authored-By: Claude Opus 5.5 --- .../src/game/enchant_effects.rs | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 6550ba9d5..8ae54dba7 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -505,7 +505,10 @@ impl Game<'_> { let riding = self.riding.is_some(); let wanted = !riding && !flying && (on_soul || (active && !on_ground)); active = wanted; - wear = on_ground && on_soul && self.world.random.next_float() < 0.04; + // `random_chance` is the first term of the wear's `all_of`: it + // draws from the level random before the block is looked at. + let roll = self.world.random.next_float() < 0.04; + wear = roll && on_ground && on_soul; } fx.applied_level = if active { level } else { 0 }; // `Entity.getKnownMovement` horizontal speed of at least 1.0E-5. @@ -529,10 +532,13 @@ impl Game<'_> { if wear && !self.creative { self.wear_boots(1); } + if level == 0 { + return; + } + let r = &mut self.world.random; if tick_effects { // `spawn_particles`: in the bounding box, 0.1 above the feet, thrown // back against the movement (-0.2) and up (0.1). - let r = &mut self.world.random; let x = position.x + (r.next_double() - 0.5) * f64::from(width); let z = position.z + (r.next_double() - 0.5) * f64::from(width); self.particles.send_particles( @@ -542,16 +548,18 @@ impl Game<'_> { 1.0, 0, ); - // `play_sound`: 35% chance, volume 0.6, pitch 0.6 to 1.0. - if r.next_float() < 0.35 { - let pitch = r.next_float() * 0.4 + 0.6; - self.audio.play( - "minecraft:particle.soul_escape", - Some([position.x, position.y, position.z]), - 0.6, - pitch, - ); - } + } + // `play_sound`: its `random_chance` (35%) comes first in its `all_of`, + // so the level random is drawn every tick the boots are worn; volume + // 0.6, pitch 0.6 to 1.0. + if r.next_float() < 0.35 && tick_effects { + let pitch = r.next_float() * 0.4 + 0.6; + self.audio.play( + "minecraft:particle.soul_escape", + Some([position.x, position.y, position.z]), + 0.6, + pitch, + ); } } /// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`): From 75f7029d016b0ff1109f030d20c28471242ce5e1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:48:37 +0100 Subject: [PATCH 013/132] Squid ink: draw the squirt's voice pitch even when silent Mob.makeSound calls getVoicePitch before Entity.playSound checks isSilent, so the squid's random advances either way. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/aquatic.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 9603d5e58..f09f7c3b3 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -37,8 +37,9 @@ pub fn spawn_ink(m: &mut Mob) { } else { "squid_ink" }; + // makeSound draws the voice pitch even for a silent squid. + let pitch = m.voice_pitch(); if !m.silent { - let pitch = m.voice_pitch(); let at = [m.position.x, m.position.y, m.position.z]; m.outbox.push(MobEvent::Sound( sound, From 608a6d9bee44680bb640777663d2c3258e5590b4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:50:47 +0100 Subject: [PATCH 014/132] Turtles: a fixed home from spawn or load, one breeding orb Turtle.finalizeSpawn sets homePos to where it spawns, and loading falls back to the block it stands on; the home no longer moves with a turtle that had none, which let it lay eggs anywhere. TurtleBreedGoal.breed adds one ExperienceOrb of 1 to 7 drawn from the mother's random. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 12 ++++++++---- crates/horizon-client/src/game/creatures.rs | 10 +++++++--- crates/horizon-client/src/mobs/spawning.rs | 8 ++++++++ crates/horizon-client/src/mobs/turtle.rs | 4 ++-- 4 files changed, 25 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index f7c843264..73bc580bc 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -856,10 +856,14 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if m.species() == crate::mobs::Species::Turtle { // Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`. m.extra.flag = flag(tag, "has_egg"); - m.extra.home = match tag.get("home_pos") { - Some(Tag::IntArray(home)) if home.len() == 3 => Some([home[0], home[1], home[2]]), - _ => None, - }; + m.extra.home = Some(match tag.get("home_pos") { + Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]], + _ => [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ], + }); } if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 03911ffda..d9764288b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1360,9 +1360,13 @@ impl Game<'_> { // TurtleBreedGoal.breed: the goal gave the mother her egg; only the // experience is left, and only with mob loot on. if p.species() == Species::Turtle { - if self.ui.rules.bool("mob_drops") { - let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + // One `new ExperienceOrb` of 1 to 7 from the mother's random (not + // split up as `ExperienceOrb.award` does). + if self.ui.rules.bool("mob_drops") + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent) + { + let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32; + self.add_orb([p.position.x, p.position.y, p.position.z], xp); } return; } diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..d58fa35c3 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -148,6 +148,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index, S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random), S::Mooshroom => m.extra.variant = 0, + // Turtle.finalizeSpawn: home is where it spawned. + S::Turtle => { + m.extra.home = Some([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]) + } S::Frog => m.extra.variant = biome.frog, S::Wolf => m.extra.variant = biome.wolf, S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon), diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs index 0596adfdf..98dd5b558 100644 --- a/crates/horizon-client/src/mobs/turtle.rs +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -23,8 +23,8 @@ fn set_laying_egg(m: &mut Mob, on: bool) { m.extra.counter = i32::from(on); m.extra.flag2 = on; } -/// `homePos.closerToCenterThan(position, distance)`; a turtle that never -/// had a home is at home where it stands. +/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and +/// loading all set a home; one made any other way is at home where it stands. fn close_to_home(m: &Mob, distance: f64) -> bool { let home = m.extra.home.unwrap_or([ m.position.x.floor() as i32, From c75854a9683fc63045dc8b16fbd0f6d345c6262b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:07:11 +0100 Subject: [PATCH 015/132] Send mob door cracks to nearby players --- crates/horizon-client/src/game/creatures.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 4613ad5f7..8e11f3103 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1056,6 +1056,25 @@ impl Game<'_> { } MobEvent::DestroyProgress { mob, pos, progress } => { self.destroy_block_progress(mob as i32, pos, progress); + // ServerLevel.destroyBlockProgress: every player nearby sees it. + if let Some(host) = self.lan.as_ref() { + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &horizon_protocol::packets::play::Clientbound::BlockDestruction( + horizon_protocol::packets::play::BlockDestruction { + id: mob as i32, + pos, + progress: if (0..10).contains(&progress) { + progress as u8 + } else { + 255 + }, + }, + ), + None, + ); + } } MobEvent::LevelEvent { id, pos, data } => self.level_event_at(id, pos, data), MobEvent::SetBlockName { pos, name, effect } => { 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 016/132] 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 bf2c8679660a72f3377e809ece12eb6aeaac32b9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:49:55 +0100 Subject: [PATCH 017/132] Zombies: roll canBreakDoors when the game spawns them Zombie.finalizeSpawn calls setCanBreakDoors(nextFloat() < special * 0.1) after the baby roll; the game's spawn finalize never rolled it, so only the finalize probe's zombies could break doors. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/spawning.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index f4e55e7d0..f362139cd 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -163,6 +163,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { if m.random.next_float() < 0.05 { m.extra.age = i32::MIN / 2; } + // setCanBreakDoors(nextFloat() < special * 0.1), before the gear. + let can_break_doors = m.random.next_float() < difficulty.special() * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); if m.species() != S::Drowned { populate_armor(m, difficulty); } @@ -196,6 +199,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { // ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword, or // one time in 20 a golden spear. S::ZombifiedPiglin => { + // Zombie.finalizeSpawn's setCanBreakDoors. + let can_break_doors = m.random.next_float() < difficulty.special() * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); let spear = m.random.next_int_bound(20).unwrap_or(1) == 0; m.extra.main_hand = Some( if spear { From 4471e59132dd8af6248d8685d066aa86ae6c15a6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:41:23 +0100 Subject: [PATCH 018/132] Load the loot tables before a world's first chunks are read A loaded container with a loot table is rolled as its chunk is decoded, but the loot tables were loaded lazily by the first level tick. The spawn chunks are decoded while the world opens, so a loot chest in them came out empty and lost its table on the next save. WorldRequest::prepare, which every world opens through (in-frame, server thread, dedicated server), now loads them first. spawn_loot: vanilla writes a flat world with a seeded loot chest by the spawn and rolls it; Horizon opens it in a fresh process, in-frame and on the server thread, and must hold the same stacks in the same slots. Without the fix both modes hold nothing. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/world_loading.rs | 4 + tools/test_spawn_loot_parity.py | 117 ++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 tools/test_spawn_loot_parity.py diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 0cea31fd0..44c903737 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -46,6 +46,10 @@ impl WorldRequest { options: &Options, settings: &Settings, ) -> Result { + // Before any chunk is read: a loaded container with a loot table is rolled as its chunk + // is decoded (`save::roll_loaded_loot`), and the spawn chunks are read while the world + // opens. Every world opens here: in-frame, on the server thread, on a dedicated server. + horizon_client::structure_blocks::loot_data(&options.resources); let Self { save_root, folder, diff --git a/tools/test_spawn_loot_parity.py b/tools/test_spawn_loot_parity.py new file mode 100644 index 000000000..896cfab0e --- /dev/null +++ b/tools/test_spawn_loot_parity.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""A vanilla loot chest at spawn has its loot when Horizon opens the world. + +Vanilla rolls a container's loot table when a player first opens it +(`RandomizableContainer.unpackLootTable`). Horizon rolls a loaded container with a loot table +and no items as its chunk is read from disk (`save::roll_loaded_loot`), so a container nobody +opens still saves as vanilla wrote it. The loot tables have to be loaded before the first chunks +are read: the spawn chunks are read while the world opens, and a chest read before the tables +came out empty, its loot table lost on the next save. + +The vanilla 26.3 server writes a flat world with a seeded loot chest beside the world spawn, then +rolls the chest itself in a copy of that world (`execute if items` unpacks it). Horizon opens the +untouched world in a new process, so nothing was loaded before the world, and must hold the same +items in the same slots. Both single-player paths: the default server thread and in-frame. + + test_spawn_loot_parity.py [--bin-dir DIR] [--keep] +""" +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_save_roundtrip_parity import Vanilla # noqa: E402 +from test_world_reopen_parity import game_env # noqa: E402 + +ROOT = Path(__file__).resolve().parent.parent +RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3' +RUN = ROOT / '.local' / 'spawn-loot' +CHEST = (2, -60, 1) +LOOT = '{LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:42L}' +MODES = {'server thread': [], 'in-frame': ['--in-frame']} + + +def vanilla_world(): + """The world with the unopened chest, and what vanilla rolls from it: [(slot, id, count)].""" + server = Vanilla(RUN / 'v0') + try: + server.run('setworldspawn 0 -60 0') + server.run('forceload add 0 0') + time.sleep(2) + server.run('setblock {} {} {} minecraft:chest{}'.format(*CHEST, LOOT)) + server.run('save-all flush') + time.sleep(2) + finally: + server.stop() + shutil.copytree(RUN / 'v0', RUN / 'vv') + server = Vanilla(RUN / 'vv') + try: + server.run('forceload add 0 0') + time.sleep(2) + server.run('execute if items block {} {} {} container.* *'.format(*CHEST)) + text = ' '.join(server.run('data get block {} {} {} Items'.format(*CHEST))) + finally: + server.stop() + rolled = [] + for item in re.finditer(r'\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}', text.split('data:', 1)[-1]): + found = item.group(0) + count = re.search(r'count: (\d+)', found) + rolled.append((int(re.search(r'Slot: (\d+)b', found).group(1)), re.search(r'id: "([^"]+)"', found).group(1), + int(count.group(1)) if count else 1)) + return sorted(rolled) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build them with the fast profile)') + parser.add_argument('--keep', action='store_true', help='keep the run folder') + args = parser.parse_args() + bin_dir = Path(args.bin_dir).resolve() if args.bin_dir else None + if bin_dir is None: + subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'], cwd=ROOT, check=True) + bin_dir = ROOT / os.environ.get('CARGO_TARGET_DIR', 'target') / 'fast' + shutil.rmtree(RUN, ignore_errors=True) + RUN.mkdir(parents=True) + expected = vanilla_world() + print('vanilla rolls:', expected) + if not expected: + sys.exit('vanilla rolled nothing from the chest') + env, extra = game_env() + failures = 0 + for index, (mode, flags) in enumerate(MODES.items()): + folder = RUN / f'h{index}' + shutil.copytree(RUN / 'v0' / 'world', folder / 'saves' / 'world') + socket = Path(tempfile.mkdtemp(prefix='hzsl')) / 'control.sock' # sockets need short paths + + def ctl(*words, check=True): + result = subprocess.run([str(bin_dir / 'horizon-ctl'), '--socket', str(socket), '--timeout', '600', + *map(str, words)], cwd=folder, env=env, capture_output=True, text=True) + if check and result.returncode: + sys.exit(f'horizon-ctl {" ".join(map(str, words))} failed: {result.stdout}{result.stderr}') + return json.loads(result.stdout) if result.stdout.strip().startswith('{') else result.stdout + + ctl('launch', '--resources', RESOURCES, '--world', 'world', '--render-distance', '4', *flags, *extra) + try: + ctl('wait-ready', '300') + slots = ctl('container', *CHEST)['slots'] + finally: + ctl('quit', check=False) + got = sorted((slot, stack['item'], stack['count']) for slot, stack in enumerate(slots) if stack) + ok = got == expected + failures += not ok + print(f'{mode}: {len(got)} stacks', 'ok' if ok else f'FAIL: {got}') + if not args.keep and not failures: + shutil.rmtree(RUN, ignore_errors=True) + print('spawn loot:', 'PASS' if not failures else f'{failures} FAILED') + sys.exit(1 if failures else 0) + + +if __name__ == '__main__': + main() From 96984300d380c7dffba31cdc991bde8e332502f3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:07:20 +0100 Subject: [PATCH 019/132] mods: the UI guest's level is 3 now that world is level 4 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mods/tests/sandbox.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 1d4297ba3..a5e95ddfa 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -255,8 +255,8 @@ experimental = ["ui", "render", "input"] needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 }; assert_eq!(level("coords_hud.hmod"), 0); - // The UI guest shows a minimap (`render.set-minimap`). - assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); + // The UI guest runs quiet commands (`command.run-quiet`, level 3). + assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 3); } #[test] From aa839fa99a28e2649d31d807bc032942a4ec739e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:39:02 +0100 Subject: [PATCH 020/132] mods: browser, a recipe viewer's item panel (API level 5) A new interface under capability ui. browser.set-items lists the items of a panel the game shows right of the inventory and container screens (an empty list hides it); browser.poll returns what the player did since the last poll: a click on an item, the search text, or one of the mod's own keys pressed over an item (a slot's or the panel's), with that stack. The slot-clicked, action, page and back events are there now for the recipe pages to come, since adding variant cases later would break mods. At most 8192 items and 256 waiting events. The game side is the next PR. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mod-sdk/src/lib.rs | 4 +- crates/horizon-mod-sdk/wit/horizon.wit | 56 ++++++++++++ crates/horizon-mods/src/api_level.rs | 6 +- crates/horizon-mods/src/manifest.rs | 4 + crates/horizon-mods/src/runtime.rs | 87 ++++++++++++++++++- crates/horizon-mods/tests/sandbox.rs | 65 ++++++++++++++ crates/horizon-mods/tests/ui_guest/src/lib.rs | 58 ++++++++++++- docs/api/mods-reference.md | 66 +++++++++++++- docs/api/stability.md | 2 +- docs/mods.md | 2 +- 10 files changed, 340 insertions(+), 10 deletions(-) diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index b00d06ecf..c87c2dbc4 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -39,7 +39,9 @@ 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, recipes, render, storage, ui}; +pub use horizon::mods::{ + browser, 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 7d7adaa0d..ab20648d8 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -509,6 +509,60 @@ interface recipes { known: func() -> list; } +/// Capability `ui` (experimental): a recipe viewer's panel beside the +/// game's inventory and container screens (not the creative inventory), on +/// the right of the screen. The game draws it with its own widgets and +/// slots, pages it and keeps its search box; the mod says what it holds. +/// The first loaded mod with a panel shows. +interface browser { + /// An item to show: its id, a count (1 draws none) and its components + /// beyond the item's own, in vanilla's item syntax, or "". + record stack { + item: string, + count: u32, + components: string, + } + /// A click on an item of the panel, by its index in `set-items`'s list. + record click { + index: u32, + right: bool, + } + /// A key the mod registered (`input.register-key`) went down while the + /// pointer was on an item: a slot of the screen's, or the panel's. + record item-key { + key: string, + stack: stack, + } + /// A click on a slot of the recipe the panel shows (`set-recipes`). + record slot-click { + /// The recipe's index on the page and the slot's in it; the + /// results come after the slots. + recipe: u32, + slot: u32, + /// The stack the slot showed at that moment. + stack: stack, + right: bool, + } + variant event { + clicked(click), + /// The search box's text, each time the player changes it. + search(string), + key(item-key), + slot-clicked(slot-click), + /// The action button of the recipe at this index on the page. + action(u32), + /// The page arrows of `set-recipes`: -1 or 1. + page(s32), + /// The back button of `set-recipes`. + back, + } + /// The panel's items, at most 8192 (an empty list hides the panel). + set-items: func(items: list); + /// What the player did on the panel since the last poll, at most 256 + /// kept. + poll: func() -> list; +} + /// Capability `players`, server mods only (manifest `api = "0.3"`, /// experimental): the players on the server, and messages to them. interface players { @@ -616,6 +670,7 @@ world horizon-ui-mod { import render; import input; import recipes; + import browser; export ui-events; } @@ -634,4 +689,5 @@ world render-host { /// The game's side of capability `recipes` (imports only). world recipes-host { import recipes; + import browser; } diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index ff06a94ae..2474dfddd 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 = 4; +pub const LEVEL: u32 = 5; /// 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); 37] = [ +pub const FUNCTIONS: [(&str, u32); 39] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -51,6 +51,8 @@ pub const FUNCTIONS: [(&str, u32); 37] = [ ("recipes.items", 4), ("recipes.all", 4), ("recipes.known", 4), + ("browser.set-items", 5), + ("browser.poll", 5), ]; /// 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 05cf96447..4c12fd805 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -173,6 +173,10 @@ impl Capability { if interface == "log" { return Ok(None); } + // A recipe viewer's panel is part of capability `ui`. + if interface == "browser" { + return Ok(Some(Capability::Ui)); + } Capability::ALL .into_iter() .filter(|c| *c != Capability::Registries) diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ebce03944..0f2de0246 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -85,11 +85,16 @@ mod recipes_bindings { world: "recipes-host", }); } +/// Capability `ui`'s recipe viewer panel (WIT `interface browser`). +pub use recipes_bindings::horizon::mods::browser::{ + Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey, + SlotClick as BrowserSlotClick, Stack as BrowserStack, +}; /// 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}; +use recipes_bindings::{RecipesHost, horizon::mods::browser, horizon::mods::recipes}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -309,6 +314,28 @@ struct UiState { close: bool, } +/// Capability `ui`'s panel beside container screens (`browser`). +#[derive(Default)] +struct BrowserState { + items: Vec, + /// Which `set-items` call the items are from, unique across mods and + /// reloads, so the game converts them once. + version: u64, + events: std::collections::VecDeque, +} +static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +/// Items a panel may hold, and events kept for `browser.poll`. +const BROWSER_ITEMS: usize = 8192; +const BROWSER_EVENTS: usize = 256; +impl BrowserState { + fn push(&mut self, event: BrowserEvent) { + if self.events.len() == BROWSER_EVENTS { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + struct State { name: String, id: String, @@ -325,6 +352,7 @@ struct State { /// Capability `render`'s minimap, when the mod shows one. minimap: Option, input: InputState, + browser: BrowserState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, /// Bytes `storage::set` may still write before this hook call ends @@ -490,6 +518,7 @@ impl Mods { zoom: None, minimap: None, input: InputState::default(), + browser: BrowserState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() @@ -799,6 +828,40 @@ impl Mods { .iter() .any(|e| e.run.as_ref().is_some_and(|r| r.raycasts)) } + /// The panel beside container screens (`browser.set-items`): the first + /// running mod with items, its index, the items' version and the items. + pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> { + self.entries.iter().enumerate().find_map(|(i, e)| { + let b = &e.run.as_ref()?.store.data().browser; + (!b.items.is_empty()).then_some((i, b.version, b.items.as_slice())) + }) + } + /// The player did `event` on mod `owner`'s panel. + pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) { + if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) { + run.store.data_mut().browser.push(event); + } + } + /// The key `key` went down with the pointer on `stack` in a container + /// screen: each mod with a key on it hears its own name for it. + pub fn browser_key(&mut self, key: &str, stack: &BrowserStack) { + for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) { + let data = run.store.data_mut(); + let names: Vec = data + .input + .keys + .iter() + .filter(|k| k.key == key) + .map(|k| k.name.clone()) + .collect(); + for key in names { + data.browser.push(BrowserEvent::Key(BrowserItemKey { + key, + stack: stack.clone(), + })); + } + } + } /// Some running mod reads capability `recipes`: the snapshot needs /// [`Snapshot::recipes`] and [`Snapshot::known_recipes`]. pub fn wants_recipes(&self) -> bool { @@ -1101,7 +1164,10 @@ fn reason(e: &wasmtime::Error) -> String { } fn clip(text: String) -> String { - match text.char_indices().nth(LINE_CHARS) { + clip_to(text, LINE_CHARS) +} +fn clip_to(text: String, chars: usize) -> String { + match text.char_indices().nth(chars) { Some((at, _)) => text[..at].to_string(), None => text, } @@ -1162,6 +1228,23 @@ impl game::Host for State { (*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone()) } } +impl browser::Host for State { + fn set_items(&mut self, items: Vec) { + self.browser.items = items + .into_iter() + .take(BROWSER_ITEMS) + .map(|s| BrowserStack { + item: clip(s.item), + components: clip_to(s.components, 4096), + ..s + }) + .collect(); + self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn poll(&mut self) -> Vec { + self.browser.events.drain(..).collect() + } +} impl recipes::Host for State { fn items(&mut self) -> Vec { self.snapshot diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 06a8e6aa2..576dc5942 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1098,3 +1098,68 @@ fn recipes_reads_the_tables() { ["0 items, 0 recipes, 0 known, 0 brewing"] ); } + +#[test] +fn browser_lists_items_and_hears_the_player() { + use horizon_mods::{BrowserClick, BrowserEvent, BrowserStack}; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + 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!(mods.browser_items().is_none()); + let potion = "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]"; + assert_eq!( + said( + &mut mods, + &format!("browser minecraft:stone minecraft:potion{potion}") + ), + ["panel of 2"] + ); + let (owner, version, items) = mods.browser_items().unwrap(); + assert_eq!( + (items[0].item.as_str(), items[1].components.as_str()), + ("minecraft:stone", potion) + ); + mods.browser_event( + owner, + BrowserEvent::Clicked(BrowserClick { + index: 1, + right: true, + }), + ); + mods.browser_event(owner, BrowserEvent::Search("oak".into())); + let log = BrowserStack { + item: "minecraft:oak_log".into(), + count: 3, + components: String::new(), + }; + // R is the guest's `recipe`; X is none of its keys. + mods.browser_key("key.keyboard.r", &log); + mods.browser_key("key.keyboard.x", &log); + assert_eq!( + said(&mut mods, "browser_poll"), + [ + "3 events", + "clicked 1 right", + "search \"oak\"", + "key recipe on minecraft:oak_log x3" + ] + ); + // Each `set-items` is a new version; an empty list hides the panel. + said(&mut mods, "browser minecraft:dirt"); + assert_ne!(mods.browser_items().unwrap().1, version); + assert_eq!(said(&mut mods, "browser"), ["panel of 0"]); + assert!(mods.browser_items().is_none()); + // At most 256 events wait for a poll: the oldest go. + for _ in 0..300 { + mods.browser_event(owner, BrowserEvent::Page(1)); + } + assert_eq!(said(&mut mods, "browser_poll")[0], "256 events"); +} diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 2fd835d3c..4fc2ee2c4 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -8,8 +8,11 @@ //! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs //! lines with `command.run-quiet` (`/quiet_many N`: N of them). `/recipes` //! counts what `recipes` reads; `/recipes ID` describes that recipe. +//! `/browser ID...` fills `browser`'s panel (`/browser N`: the first N +//! items, `/browser` alone empties it) and registers the keys `recipe` (R) +//! and `uses` (U); `/browser_poll` says what the player did on it. use horizon_mod_sdk::{ - Mod, Registration, chat, command, game, + Mod, Registration, browser, chat, command, game, input::{self, Event}, recipes, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, @@ -105,6 +108,8 @@ impl Mod for Guest { "quiet", "quiet_many", "recipes", + "browser", + "browser_poll", "corner", "readings", ] @@ -279,6 +284,57 @@ impl Mod for Guest { ), }); } + "browser" => { + let stack = |item: &str| { + let (item, components) = match item.find('[') { + Some(at) => (&item[..at], &item[at..]), + None => (item, ""), + }; + browser::Stack { + item: item.into(), + count: 1, + components: components.into(), + } + }; + let items: Vec = match args.parse::() { + Ok(n) => recipes::items() + .iter() + .skip(1) + .take(n) + .map(|i| stack(&i.id)) + .collect(), + Err(_) => args.split_whitespace().map(stack).collect(), + }; + browser::set_items(&items); + input::register_key("recipe", "Show recipes", "key.keyboard.r")?; + input::register_key("uses", "Show uses", "key.keyboard.u")?; + chat::show(&format!("panel of {}", items.len())); + } + "browser_poll" => { + let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components); + // A hook shows at most 8 chat lines: the count, then the first 7. + let events = browser::poll(); + chat::show(&format!("{} events", events.len())); + for event in events.into_iter().take(7) { + chat::show(&match event { + browser::Event::Clicked(c) => { + format!( + "clicked {} {}", + c.index, + if c.right { "right" } else { "left" } + ) + } + browser::Event::Search(text) => format!("search {text:?}"), + browser::Event::Key(k) => format!("key {} on {}", k.key, stack(&k.stack)), + browser::Event::SlotClicked(c) => { + format!("slot {} {} {}", c.recipe, c.slot, stack(&c.stack)) + } + browser::Event::Action(i) => format!("action {i}"), + browser::Event::Page(step) => format!("page {step}"), + browser::Event::Back => "back".into(), + }); + } + } // 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 1ee54e70f..111fefd5c 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -37,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`, `recipes`, `log`, `game`, `chat`, `hud`, `storage`, `command` +- Imports (what the game offers): `ui`, `render`, `input`, `recipes`, `browser`, `log`, `game`, `chat`, `hud`, `storage`, `command` - Exports (what the mod provides): `ui-events`, `events` ## World `ui-host` @@ -58,7 +58,7 @@ The game's side of capability `render` (imports only). The game's side of capability `recipes` (imports only). -- Imports (what the game offers): `recipes` +- Imports (what the game offers): `recipes`, `browser` - Exports (what the mod provides): ## `log` @@ -531,6 +531,68 @@ The station a recipe is made at. | `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. | +## `browser` + +Access: not granted by any capability. + +Capability `ui` (experimental): a recipe viewer's panel beside the game's inventory and container screens (not the creative inventory), on the right of the screen. The game draws it with its own widgets and slots, pages it and keeps its search box; the mod says what it holds. The first loaded mod with a panel shows. + +### record `stack` + +An item to show: its id, a count (1 draws none) and its components beyond the item's own, in vanilla's item syntax, or "". + +| Field | Type | | +| --- | --- | --- | +| `item` | `string` | | +| `count` | `u32` | | +| `components` | `string` | | + +### record `click` + +A click on an item of the panel, by its index in `set-items`'s list. + +| Field | Type | | +| --- | --- | --- | +| `index` | `u32` | | +| `right` | `bool` | | + +### record `item-key` + +A key the mod registered (`input.register-key`) went down while the pointer was on an item: a slot of the screen's, or the panel's. + +| Field | Type | | +| --- | --- | --- | +| `key` | `string` | | +| `stack` | `stack` | | + +### record `slot-click` + +A click on a slot of the recipe the panel shows (`set-recipes`). + +| Field | Type | | +| --- | --- | --- | +| `recipe` | `u32` | The recipe's index on the page and the slot's in it; the results come after the slots. | +| `slot` | `u32` | | +| `stack` | `stack` | The stack the slot showed at that moment. | +| `right` | `bool` | | + +### variant `event` + +| Case | Payload | | +| --- | --- | --- | +| `clicked` | `click` | | +| `search` | `string` | The search box's text, each time the player changes it. | +| `key` | `item-key` | | +| `slot-clicked` | `slot-click` | | +| `action` | `u32` | The action button of the recipe at this index on the page. | +| `page` | `s32` | The page arrows of `set-recipes`: -1 or 1. | +| `back` | | The back button of `set-recipes`. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `set-items` | `func(items: list)` | The panel's items, at most 8192 (an empty list hides the panel). | +| `poll` | `func() -> list` | What the player did on the panel since the last poll, at most 256 kept. | + ## `players` Access: capability `players`. diff --git a/docs/api/stability.md b/docs/api/stability.md index 00b5541a9..bb0ddf501 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`, level 4 `recipes` (`items`, `all`, `known`). 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`), level 5 `browser` (`set-items`, `poll`). 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 73ecfb9a5..9aed4897b 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -88,7 +88,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code; `browser.set-items`, `browser.poll`: a recipe viewer's panel of items right of the inventory and container screens (not the creative one), which the game pages and draws with its own slots and search box, and the mod hears its clicks, its searches and the mod's own keys (`input.register-key`) pressed over any item on the screen. **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"]` | From 487a461a8a7454871aaf92e11466cadc9504699b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:39:12 +0100 Subject: [PATCH 021/132] game: the item panel of a mod's browser beside container screens The panel sits right of the inventory or container window, from the top of the screen to a search box at its foot, in up to 12 columns of the game's own item slots, with the recipe book's page arrows. It shows on the survival inventory and every container screen (not the creative one) while a running mod has items in it, and hides when there is no room for two columns. Clicks on it never throw the carried stack; the carried stack and tooltips are drawn again above it. The mod hears clicks on items, the search text as it changes, and its own keys pressed with the pointer on an item, the panel's or a slot's. The search box takes every key but Escape while focused, as the recipe book's. Each set-items is turned into stacks once. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 56 ++- crates/horizon-client/src/game/control.rs | 3 + crates/horizon-client/src/game/mod_browser.rs | 440 ++++++++++++++++++ crates/horizon-client/src/game/mod_input.rs | 12 + crates/horizon-client/src/game/mod_recipes.rs | 2 +- crates/horizon-client/src/game/mods.rs | 3 + 6 files changed, 496 insertions(+), 20 deletions(-) create mode 100644 crates/horizon-client/src/game/mod_browser.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 826ea73c1..6779d367a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -99,6 +99,7 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mod_browser; mod mod_input; #[cfg(feature = "mods")] mod mod_recipes; @@ -5217,6 +5218,7 @@ impl Game<'_> { Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); + self.draw_mod_browser(&mut batch); } Screen::Creative => { self.draw_creative(&mut batch); @@ -5595,6 +5597,7 @@ impl Game<'_> { } } pub(super) fn close_container(&mut self) { + self.mod_browser_closed(); self.close_station(); self.mount_closed(); self.recipe_ui.reset_screen(); @@ -6319,6 +6322,9 @@ impl Game<'_> { fn inventory_press(&mut self, right: bool) { use horizon_client::container_screen::Target; use horizon_client::menu::Input; + if self.mod_browser_press(right) { + return; + } if !right && self.sort_press() { return; } @@ -6495,24 +6501,8 @@ impl Game<'_> { } /// `hasClickedOutside` of the open screen at the cursor. fn clicked_outside(&self, batch: &HudBatch) -> bool { - use horizon_client::container_screen::{Book, Image, clicked_outside}; - let (ox, oy) = self.inventory_origin(batch); - let (shift, width, height) = if self.screen == Screen::Creative { - (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32) - } else { - let (shift, width) = match self.station.as_ref().map(|s| s.kind) { - Some(stations::Kind::Merchant) => (-50.0, 276), - Some(stations::Kind::Beacon) => (beacon::SHIFT, 230), - _ => (0.0, 176), - }; - (shift, width, self.screen_height() as i32) - }; - let image = Image { - left: (ox + shift) as i32, - top: oy as i32, - width, - height, - }; + use horizon_client::container_screen::{Book, clicked_outside}; + let image = self.container_image(batch); let book = self .recipe_book_area(batch) .map(|(visible, tab_hovered)| Book { @@ -6526,6 +6516,26 @@ impl Game<'_> { book, ) } + /// The open container screen's window: its place and size. + fn container_image(&self, batch: &HudBatch) -> horizon_client::container_screen::Image { + let (ox, oy) = self.inventory_origin(batch); + let (shift, width, height) = if self.screen == Screen::Creative { + (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32) + } else { + let (shift, width) = match self.station.as_ref().map(|s| s.kind) { + Some(stations::Kind::Merchant) => (-50.0, 276), + Some(stations::Kind::Beacon) => (beacon::SHIFT, 230), + _ => (0.0, 176), + }; + (shift, width, self.screen_height() as i32) + }; + horizon_client::container_screen::Image { + left: (ox + shift) as i32, + top: oy as i32, + width, + height, + } + } /// A click outside the window (slot id -999): `THROW` does nothing; a /// `PICKUP` drops the carried stack (left) or one of it (right), thrown /// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`). @@ -6686,7 +6696,7 @@ impl Game<'_> { } } fn click_inventory(&mut self, right: bool) { - if self.mount_click(right) { + if self.mod_browser_press(right) || self.mount_click(right) { return; } if self.recipe_book_click(right) { @@ -11645,6 +11655,14 @@ impl ApplicationHandler for Game<'_> { // The recipe book's search box takes every key but Escape. self.recipe_key(&event); } + WindowEvent::KeyboardInput { event, .. } + if self.mod_browser_typing() + && event.state == ElementState::Pressed + && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => + { + // A mod's item panel's search box, as the recipe book's. + self.mod_browser_key(&event); + } WindowEvent::KeyboardInput { event, .. } if self.station_typing() && event.state == ElementState::Pressed diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 3202b23f4..191fa8359 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -628,6 +628,9 @@ impl Game<'_> { // The port, or the game rules' search and number boxes. Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions => self.world_options_text(Some(text)), + Screen::Inventory if self.mod_browser_typing() => { + self.mod_browser_text((text != "\\b").then_some(text), text == "\\b") + } Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } diff --git a/crates/horizon-client/src/game/mod_browser.rs b/crates/horizon-client/src/game/mod_browser.rs new file mode 100644 index 000000000..2f317792f --- /dev/null +++ b/crates/horizon-client/src/game/mod_browser.rs @@ -0,0 +1,440 @@ +//! Capability `ui`'s panel beside container screens (WIT `interface +//! browser`, docs/mods.md): the items a recipe viewer mod lists, drawn as +//! the game's own item slots in pages right of the screen's window, with a +//! search box under them. The mod says what the panel holds; the game pages +//! it and tells the mod what the player clicked, typed, and which of the +//! mod's keys went down over an item. With no mod showing a panel, each +//! hook here returns after one check. +use super::Game; +#[cfg(feature = "mods")] +use { + super::Screen, + horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, + ui::EditBox, + }, + horizon_mods::{BrowserClick, BrowserEvent, BrowserStack}, +}; + +#[cfg(not(feature = "mods"))] +impl Game<'_> { + pub(super) fn draw_mod_browser(&mut self, _batch: &mut horizon_client::hud::HudBatch) {} + pub(super) fn mod_browser_press(&mut self, _right: bool) -> bool { + false + } + pub(super) fn mod_browser_typing(&self) -> bool { + false + } + pub(super) fn mod_browser_key(&mut self, _event: &winit::event::KeyEvent) {} + pub(super) fn mod_browser_text(&mut self, _text: Option<&str>, _backspace: bool) {} + pub(super) fn mod_browser_closed(&mut self) {} +} + +/// One slot of the panel, in GUI pixels. +#[cfg(feature = "mods")] +const SLOT: f32 = 18.0; +/// The most columns the panel takes, and the fewest it shows with. +#[cfg(feature = "mods")] +const COLUMNS: (usize, usize) = (12, 2); +/// The gap between the window and the panel, and the screen's edges. +#[cfg(feature = "mods")] +const MARGIN: f32 = 8.0; + +/// The panel's state in the game. +#[cfg(feature = "mods")] +#[derive(Default)] +pub(super) struct Browser { + /// The items' owner and version they were made from. + of: Option<(usize, u64)>, + /// The mod's items as stacks; `None` for an item the game doesn't have. + stacks: Vec>, + page: usize, + search: Option, + /// The search text the mod last heard. + sent: String, +} + +/// Where the panel's parts are this frame. +#[cfg(feature = "mods")] +struct Layout { + /// The panel's whole area, for clicks that hit none of its parts. + area: [f32; 4], + /// The grid's top left corner, its columns and rows. + grid: (f32, f32), + columns: usize, + rows: usize, + /// The page arrows' row. + arrows_y: f32, + search: [f32; 4], +} +#[cfg(feature = "mods")] +impl Layout { + fn per_page(&self) -> usize { + self.columns * self.rows + } + fn width(&self) -> f32 { + self.columns as f32 * SLOT + } + fn slot(&self, n: usize) -> (f32, f32) { + ( + self.grid.0 + (n % self.columns) as f32 * SLOT, + self.grid.1 + (n / self.columns) as f32 * SLOT, + ) + } + /// The page arrows: backward, then forward. + fn arrows(&self) -> [(f32, f32); 2] { + [ + (self.grid.0, self.arrows_y), + (self.grid.0 + self.width() - 12.0, self.arrows_y), + ] + } +} + +#[cfg(feature = "mods")] +fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool { + p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h +} + +#[cfg(feature = "mods")] +impl Game<'_> { + fn browser_batch(&self) -> Option { + let r = self.renderer.as_ref()?; + Some(HudBatch::new([r.config.width, r.config.height])) + } + /// The mod showing a panel, with its items made into stacks once per + /// `set-items`; none while no mod shows one or no container screen is up. + fn browser_sync(&mut self) -> Option { + if self.screen != Screen::Inventory || self.title.is_some() { + return None; + } + let Some((owner, version)) = self.mods.mods.browser_items().map(|(o, v, _)| (o, v)) else { + self.mods.browser.of = None; + self.mods.browser.stacks.clear(); + return None; + }; + if self.mods.browser.of != Some((owner, version)) { + let items = self.res.items(); + let stacks = self + .mods + .mods + .browser_items() + .map_or_else(Vec::new, |(_, _, list)| { + list.iter().map(|s| browser_stack(items, s)).collect() + }); + self.mods.browser.stacks = stacks; + self.mods.browser.of = Some((owner, version)); + } + Some(owner) + } + /// The panel's parts: right of the window, from the top of the screen to + /// the search box at its foot. None when the screen has no room for it. + fn browser_layout(&self, batch: &HudBatch) -> Option { + let image = self.container_image(batch); + let left = (image.left + image.width) as f32 + MARGIN; + let right = batch.width - MARGIN; + let columns = (((right - left) / SLOT).floor().max(0.0) as usize).min(COLUMNS.0); + if columns < COLUMNS.1 { + return None; + } + let x = (left + (right - left - columns as f32 * SLOT) / 2.0).floor(); + let arrows_y = MARGIN; + let top = arrows_y + 17.0 + 4.0; + let search = [x, batch.height - MARGIN - 16.0, columns as f32 * SLOT, 16.0]; + let rows = ((search[1] - 4.0 - top) / SLOT).floor().max(0.0) as usize; + (rows > 0).then_some(Layout { + area: [left, 0.0, right - left, batch.height], + grid: (x, top), + columns, + rows, + arrows_y, + search, + }) + } + fn browser_pages(&self, layout: &Layout) -> usize { + self.mods + .browser + .stacks + .len() + .div_ceil(layout.per_page()) + .max(1) + } + /// The panel's item under the pointer: its index and stack. + fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> { + let first = self.mods.browser.page * layout.per_page(); + (0..layout.per_page()).find_map(|n| { + let (x, y) = layout.slot(n); + if !inside(self.cursor, [x, y, SLOT, SLOT]) { + return None; + } + let stack = self.mods.browser.stacks.get(first + n)?.clone()?; + Some((first + n, stack)) + }) + } + fn browser_search(&mut self, layout: &Layout) -> &mut EditBox { + let search = self.mods.browser.search.get_or_insert_with(|| { + let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0); + edit.max_length = 50; + edit.focused = false; + edit + }); + [search.x, search.y, search.width, search.height] = layout.search; + search + } + + /// Draws the panel over the open container screen, then the carried + /// stack or the tooltip again so they stay on top of it. + pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) { + if self.browser_sync().is_none() { + return; + } + let Some(layout) = self.browser_layout(batch) else { + return; + }; + let pages = self.browser_pages(&layout); + self.mods.browser.page = self.mods.browser.page.min(pages - 1); + let page = self.mods.browser.page; + let cursor = self.cursor; + if pages > 1 { + let labels = [ + self.translate("gui.recipebook.previous_page", "Previous Page"), + self.translate("gui.recipebook.next_page", "Next Page"), + ]; + let shown = [page > 0, page + 1 < pages]; + let atlas = &self.gui.atlas; + for (((x, y), name), (label, shown)) in layout + .arrows() + .into_iter() + .zip(["page_backward", "page_forward"]) + .zip(labels.iter().zip(shown)) + { + if !shown { + continue; + } + let hover = inside(cursor, [x, y, 12.0, 17.0]); + let suffix = if hover { "_highlighted" } else { "" }; + batch.sprite( + atlas, + &format!("gui/sprites/recipe_book/{name}{suffix}"), + x, + y, + ); + horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true); + } + let text = format!("{}/{pages}", page + 1); + let w = HudBatch::text_width(atlas, &text); + let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor(); + batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true); + } + let first = page * layout.per_page(); + for n in 0..layout.per_page() { + let Some(stack) = self.mods.browser.stacks.get(first + n) else { + break; + }; + let Some(stack) = stack.clone() else { + continue; + }; + let (x, y) = layout.slot(n); + self.draw_item(batch, &stack, x + 1.0, y + 1.0); + let rect = [x + 1.0, y + 1.0, 16.0, 16.0]; + if inside(cursor, [x, y, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + 1.0, + y + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &name, + rect, + true, + horizon_client::widgets::Kind::Button, + ); + } + let hint = self.translate("gui.recipebook.search_hint", "Search..."); + let search = self.browser_search(&layout); + // The hint shows in an empty box without focus, as the recipe book's. + search.suggestion = (search.value.is_empty() && !search.focused).then_some(hint); + let mut search = search.clone(); + search.draw(batch, &self.gui.atlas, None); + self.mods.browser.search = Some(search); + if self.carried.is_some() { + self.draw_carried(batch); + } else if let Some((_, stack)) = self.browser_hovered(&layout) { + let lines = self.stack_tooltip(&stack); + self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1); + } else { + self.draw_slot_tooltip(batch); + } + } + + /// A mouse press on a container screen: true when the panel took it + /// (its search box, page arrows, items or empty space; a click there + /// never throws the carried stack). + pub(super) fn mod_browser_press(&mut self, right: bool) -> bool { + let Some(owner) = self.browser_sync() else { + return false; + }; + let Some(batch) = self.browser_batch() else { + return false; + }; + let Some(layout) = self.browser_layout(&batch) else { + return false; + }; + let cursor = self.cursor; + let shift = self.has_shift_down(); + let atlas = &self.gui.atlas; + let search = self.mods.browser.search.get_or_insert_with(|| { + let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0); + edit.max_length = 50; + edit + }); + [search.x, search.y, search.width, search.height] = layout.search; + if inside(cursor, layout.search) { + search.focused = true; + search.click(atlas, cursor.0, shift, false); + search.reset_blink(); + return true; + } + search.focused = false; + let pages = self.browser_pages(&layout); + let page = self.mods.browser.page; + let [back, forward] = layout.arrows(); + let step = if pages > 1 && page > 0 && inside(cursor, [back.0, back.1, 12.0, 17.0]) { + Some(page - 1) + } else if pages > 1 + && page + 1 < pages + && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) + { + Some(page + 1) + } else { + None + }; + if let Some(to) = step { + self.mods.browser.page = to; + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + return true; + } + if let Some((index, _)) = self.browser_hovered(&layout) { + let event = BrowserEvent::Clicked(BrowserClick { + index: index as u32, + right, + }); + self.mods.mods.browser_event(owner, event); + return true; + } + inside(cursor, layout.area) + } + + /// Whether keys go to the panel's search box. + pub(super) fn mod_browser_typing(&self) -> bool { + self.screen == Screen::Inventory + && self.mods.browser.of.is_some() + && self.mods.browser.search.as_ref().is_some_and(|s| s.focused) + } + /// A key press while the search box has focus. + pub(super) fn mod_browser_key(&mut self, event: &winit::event::KeyEvent) { + use winit::keyboard::PhysicalKey; + let shortcut = self.edit_shortcut(event); + let ctrl = self.has_control_down(); + let shift = self.has_shift_down(); + let Some(search) = self.mods.browser.search.as_mut() else { + return; + }; + if let Some(shortcut) = shortcut { + search.shortcut(shortcut, &mut self.clipboard); + } else { + let handled = match event.physical_key { + PhysicalKey::Code(code) => search.key(code, ctrl, shift), + _ => false, + }; + if !handled + && !ctrl + && let Some(text) = &event.text + { + let text: String = text.chars().filter(|c| !c.is_control()).collect(); + search.insert_text(&text); + } + } + search.reset_blink(); + self.browser_searched(); + } + /// Text typed (or one backspace) into the search box (`horizon-ctl type`). + pub(super) fn mod_browser_text(&mut self, text: Option<&str>, backspace: bool) { + let Some(search) = self.mods.browser.search.as_mut() else { + return; + }; + if backspace { + search.delete_chars(-1); + } else if let Some(text) = text { + search.insert_text(text); + } + self.browser_searched(); + } + /// The mod hears the search text when it changed. + fn browser_searched(&mut self) { + let (Some((owner, _)), Some(search)) = (self.mods.browser.of, &self.mods.browser.search) + else { + return; + }; + if search.value != self.mods.browser.sent { + let value = search.value.clone(); + self.mods.browser.sent.clone_from(&value); + self.mods.browser.page = 0; + self.mods + .mods + .browser_event(owner, BrowserEvent::Search(value)); + } + } + /// The container screen closed: the search box lets go of the keys. + pub(super) fn mod_browser_closed(&mut self) { + if let Some(search) = self.mods.browser.search.as_mut() { + search.focused = false; + } + } + /// The item under the pointer on a container screen, for the mods' keys + /// (`browser`'s `key` event): the panel's, else a slot's. + pub(super) fn mod_browser_pointed(&mut self) -> Option { + let batch = self.browser_batch()?; + let stack = match self + .browser_sync() + .and_then(|_| self.browser_layout(&batch)) + { + Some(layout) if inside(self.cursor, layout.area) => self.browser_hovered(&layout)?.1, + _ => { + let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?; + self.slot_view(slot)? + } + }; + Some(BrowserStack { + item: stack.item.to_string(), + count: stack.count, + components: super::mod_recipes::components(&stack), + }) + } +} + +/// A mod's item as a stack: an item the game has, its components read as +/// `/give` reads them (ones it can't read are left out). +#[cfg(feature = "mods")] +fn browser_stack(items: &horizon_client::items::Items, s: &BrowserStack) -> Option { + items.get(&s.item)?; + let (damage, extra) = if s.components.is_empty() { + (0, None) + } else { + horizon_client::item_data::command_components(&s.components).map_or((0, None), |tag| { + horizon_client::item_data::decode_components(Some(&tag)) + }) + }; + Some(ItemStack { + item: s.item.as_str().into(), + count: s.count.clamp(1, 99), + damage, + extra, + }) +} diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 10faf6a81..3df62c3d4 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -111,6 +111,18 @@ impl Game<'_> { if repeat || !self.mods.mods.has_keys() { return; } + // Over an item on a container screen, the mods' keys are `browser` + // events (a recipe viewer's R and U). + if pressed + && self.screen == Screen::Inventory + && self.title.is_none() + && !self.mod_browser_typing() + && let Some(name) = horizon_client::keybinds::key_name(key) + && let Some(stack) = self.mod_browser_pointed() + { + self.mods.mods.browser_key(name, &stack); + return; + } if pressed && (self.screen != Screen::Playing || self.title.is_some()) { return; } diff --git a/crates/horizon-client/src/game/mod_recipes.rs b/crates/horizon-client/src/game/mod_recipes.rs index 0d57e1f94..f02eb6424 100644 --- a/crates/horizon-client/src/game/mod_recipes.rs +++ b/crates/horizon-client/src/game/mod_recipes.rs @@ -35,7 +35,7 @@ impl Index { /// 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 { +pub(super) 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(); diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 156467e7a..40298a922 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -76,6 +76,9 @@ pub(super) struct ModsState { /// 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]>), + /// Capability `ui`'s item panel beside container screens. + #[cfg(feature = "mods")] + pub(super) browser: super::mod_browser::Browser, /// Extras that are official mods now, being installed. #[cfg(feature = "mods")] pub(super) moved: super::moved_extras::MovedState, From b8da45f5ef2d4b1b1584b0255b36ef389ac18a10 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:51:32 +0100 Subject: [PATCH 022/132] mods: browser's page event names the first recipe shown, set-recipes' indexes are its list's Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mod-sdk/wit/horizon.wit | 14 ++++++++------ crates/horizon-mods/tests/ui_guest/src/lib.rs | 2 +- docs/api/mods-reference.md | 8 ++++---- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index ab20648d8..38a0e5879 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -533,10 +533,10 @@ interface browser { key: string, stack: stack, } - /// A click on a slot of the recipe the panel shows (`set-recipes`). + /// A click on a slot of a recipe the panel shows (`set-recipes`). record slot-click { - /// The recipe's index on the page and the slot's in it; the - /// results come after the slots. + /// The recipe's index in `set-recipes`'s list and the slot's in + /// it; the results come after the slots. recipe: u32, slot: u32, /// The stack the slot showed at that moment. @@ -549,10 +549,12 @@ interface browser { search(string), key(item-key), slot-clicked(slot-click), - /// The action button of the recipe at this index on the page. + /// The action button of the recipe at this index in + /// `set-recipes`'s list. action(u32), - /// The page arrows of `set-recipes`: -1 or 1. - page(s32), + /// The player turned the recipes' page (`set-recipes`): the index + /// of the first recipe now shown. + page(u32), /// The back button of `set-recipes`. back, } diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 4fc2ee2c4..43aa207e0 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -330,7 +330,7 @@ impl Mod for Guest { format!("slot {} {} {}", c.recipe, c.slot, stack(&c.stack)) } browser::Event::Action(i) => format!("action {i}"), - browser::Event::Page(step) => format!("page {step}"), + browser::Event::Page(first) => format!("page {first}"), browser::Event::Back => "back".into(), }); } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 111fefd5c..298db26ba 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -567,11 +567,11 @@ A key the mod registered (`input.register-key`) went down while the pointer was ### record `slot-click` -A click on a slot of the recipe the panel shows (`set-recipes`). +A click on a slot of a recipe the panel shows (`set-recipes`). | Field | Type | | | --- | --- | --- | -| `recipe` | `u32` | The recipe's index on the page and the slot's in it; the results come after the slots. | +| `recipe` | `u32` | The recipe's index in `set-recipes`'s list and the slot's in it; the results come after the slots. | | `slot` | `u32` | | | `stack` | `stack` | The stack the slot showed at that moment. | | `right` | `bool` | | @@ -584,8 +584,8 @@ A click on a slot of the recipe the panel shows (`set-recipes`). | `search` | `string` | The search box's text, each time the player changes it. | | `key` | `item-key` | | | `slot-clicked` | `slot-click` | | -| `action` | `u32` | The action button of the recipe at this index on the page. | -| `page` | `s32` | The page arrows of `set-recipes`: -1 or 1. | +| `action` | `u32` | The action button of the recipe at this index in `set-recipes`'s list. | +| `page` | `u32` | The player turned the recipes' page (`set-recipes`): the index of the first recipe now shown. | | `back` | | The back button of `set-recipes`. | | Function | Signature | What it does | From fc9305bb155c090b35daa3534bcdf4d4daacb92f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:03:42 +0100 Subject: [PATCH 023/132] mods: browser.set-recipes, recipes in the item panel's place A mod gives the recipes to show (a layout: crafting grid, cooking, single input, smithing or brewing; the slots, each cycling through its stacks; the results; a note; and an optional action button, enabled or greyed) under a title; an empty list shows the items again. The game pages them and sends the slot-clicked, action, page and back events. At most 256 recipes, 9 slots each and 64 stacks a slot. Same level as the rest of browser (5): none of it has shipped yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mod-sdk/wit/horizon.wit | 33 +++++++++++ crates/horizon-mods/src/api_level.rs | 3 +- crates/horizon-mods/src/runtime.rs | 56 ++++++++++++++++-- crates/horizon-mods/tests/sandbox.rs | 52 ++++++++++++++++ crates/horizon-mods/tests/ui_guest/src/lib.rs | 59 ++++++++++++++++++- docs/api/mods-reference.md | 27 +++++++++ docs/api/stability.md | 2 +- docs/mods.md | 2 +- 8 files changed, 225 insertions(+), 9 deletions(-) diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 38a0e5879..4896c3e21 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -558,8 +558,41 @@ interface browser { /// The back button of `set-recipes`. back, } + /// How the game lays out a recipe of `set-recipes`. + enum layout { + /// A crafting grid of `width` x `height` slots, an arrow and the + /// result. + grid, + /// One input over a flame, an arrow and the result (furnaces, + /// smokers, campfires). + cooking, + /// One input, an arrow and the result (the stonecutter). + single, + /// Template, base and addition, an arrow and the result. + smithing, + /// A potion and an ingredient, an arrow and the result. + brewing, + } + /// A recipe to show. Each slot, and the result, cycles through its + /// stacks, one a second; an empty slot shows nothing. + record recipe-view { + layout: layout, + /// The grid's size (`grid` only), at most 3 x 3. + width: u32, + height: u32, + slots: list>, + results: list, + /// A short line under the recipe (a cooking time), or "". + note: string, + /// The action button beside it: none, enabled, or shown greyed. + action: option, + } /// The panel's items, at most 8192 (an empty list hides the panel). set-items: func(items: list); + /// Shows these recipes in the panel instead of its items, as many as + /// fit a page, under `title` and a back button; an empty list shows the + /// items again. At most 256 recipes. + set-recipes: func(title: string, recipes: list); /// What the player did on the panel since the last poll, at most 256 /// kept. poll: func() -> list; diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 2474dfddd..7bb87b674 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -13,7 +13,7 @@ pub const LEVEL: u32 = 5; /// 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); 39] = [ +pub const FUNCTIONS: [(&str, u32); 40] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -53,6 +53,7 @@ pub const FUNCTIONS: [(&str, u32); 39] = [ ("recipes.known", 4), ("browser.set-items", 5), ("browser.poll", 5), + ("browser.set-recipes", 5), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 0f2de0246..43c9e3fac 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -88,7 +88,8 @@ mod recipes_bindings { /// Capability `ui`'s recipe viewer panel (WIT `interface browser`). pub use recipes_bindings::horizon::mods::browser::{ Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey, - SlotClick as BrowserSlotClick, Stack as BrowserStack, + Layout as BrowserLayout, RecipeView as BrowserRecipe, SlotClick as BrowserSlotClick, + Stack as BrowserStack, }; /// What capability `recipes` reads (WIT `interface recipes`). pub use recipes_bindings::horizon::mods::recipes::{ @@ -318,14 +319,20 @@ struct UiState { #[derive(Default)] struct BrowserState { items: Vec, - /// Which `set-items` call the items are from, unique across mods and - /// reloads, so the game converts them once. + /// Which `set-items` or `set-recipes` call the panel is from, unique + /// across mods and reloads, so the game converts them once. version: u64, + /// `set-recipes`' title and recipes, shown instead of the items. + recipes: Option<(String, Vec)>, events: std::collections::VecDeque, } static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); /// Items a panel may hold, and events kept for `browser.poll`. const BROWSER_ITEMS: usize = 8192; +/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles. +const BROWSER_RECIPES: usize = 256; +const RECIPE_SLOTS: usize = 9; +const SLOT_STACKS: usize = 64; const BROWSER_EVENTS: usize = 256; impl BrowserState { fn push(&mut self, event: BrowserEvent) { @@ -829,13 +836,26 @@ impl Mods { .any(|e| e.run.as_ref().is_some_and(|r| r.raycasts)) } /// The panel beside container screens (`browser.set-items`): the first - /// running mod with items, its index, the items' version and the items. + /// running mod with items or recipes, its index, the panel's version and + /// the items. pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> { self.entries.iter().enumerate().find_map(|(i, e)| { let b = &e.run.as_ref()?.store.data().browser; - (!b.items.is_empty()).then_some((i, b.version, b.items.as_slice())) + (!b.items.is_empty() || b.recipes.is_some()).then_some(( + i, + b.version, + b.items.as_slice(), + )) }) } + /// The recipes mod `owner`'s panel shows instead of its items + /// (`browser.set-recipes`): the title and the recipes. + pub fn browser_recipes(&self, owner: usize) -> Option<(&str, &[BrowserRecipe])> { + let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser; + b.recipes + .as_ref() + .map(|(title, list)| (title.as_str(), list.as_slice())) + } /// The player did `event` on mod `owner`'s panel. pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) { if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) { @@ -1241,6 +1261,32 @@ impl browser::Host for State { .collect(); self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } + fn set_recipes(&mut self, title: String, recipes: Vec) { + let stack = |s: BrowserStack| BrowserStack { + item: clip(s.item), + components: clip_to(s.components, 4096), + ..s + }; + let cycle = |list: Vec| -> Vec { + list.into_iter().take(SLOT_STACKS).map(stack).collect() + }; + self.browser.recipes = (!recipes.is_empty()).then(|| { + let recipes = recipes + .into_iter() + .take(BROWSER_RECIPES) + .map(|r| BrowserRecipe { + width: r.width.clamp(1, 3), + height: r.height.clamp(1, 3), + slots: r.slots.into_iter().take(RECIPE_SLOTS).map(cycle).collect(), + results: cycle(r.results), + note: clip(r.note), + ..r + }) + .collect(); + (clip(title), recipes) + }); + self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } fn poll(&mut self) -> Vec { self.browser.events.drain(..).collect() } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 576dc5942..081884dc2 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1157,6 +1157,58 @@ fn browser_lists_items_and_hears_the_player() { assert_ne!(mods.browser_items().unwrap().1, version); assert_eq!(said(&mut mods, "browser"), ["panel of 0"]); assert!(mods.browser_items().is_none()); + // Recipes in the panel's place: the guest shows those making planks. + use horizon_mods::{BrowserLayout, Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; + let item = |id: &str| RecipeItem { + id: id.into(), + name: id.into(), + tags: Vec::new(), + }; + let stack = |item| RecipeStack { + item, + count: 1, + components: String::new(), + }; + mods.set_snapshot(Snapshot { + recipes: Some(std::sync::Arc::new(Recipes { + items: vec![item("minecraft:oak_log"), item("minecraft:oak_planks")], + recipes: vec![Recipe { + id: "minecraft:oak_planks".into(), + kind: RecipeKind::CraftingShapeless, + category: "building".into(), + group: "planks".into(), + width: 0, + height: 0, + slots: vec![vec![stack(0)]], + results: vec![RecipeStack { + count: 4, + ..stack(1) + }], + cooking_time: 0, + experience: 0.0, + book_id: 1, + }], + })), + ..Snapshot::default() + }); + said(&mut mods, "browser minecraft:dirt"); + assert_eq!( + said(&mut mods, "browser_recipes minecraft:oak_planks"), + ["recipes shown: 1"] + ); + let (title, recipes) = mods.browser_recipes(owner).unwrap(); + assert_eq!(title, "Recipes for minecraft:oak_planks"); + let r = &recipes[0]; + assert_eq!( + (r.layout, r.width, r.height, r.action), + (BrowserLayout::Grid, 1, 1, Some(false)) + ); + assert_eq!( + (r.slots[0][0].item.as_str(), r.results[0].count), + ("minecraft:oak_log", 4) + ); + assert_eq!(said(&mut mods, "browser_recipes"), ["recipes shown: 0"]); + assert!(mods.browser_recipes(owner).is_none()); // At most 256 events wait for a poll: the oldest go. for _ in 0..300 { mods.browser_event(owner, BrowserEvent::Page(1)); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 43aa207e0..751169565 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -10,7 +10,9 @@ //! counts what `recipes` reads; `/recipes ID` describes that recipe. //! `/browser ID...` fills `browser`'s panel (`/browser N`: the first N //! items, `/browser` alone empties it) and registers the keys `recipe` (R) -//! and `uses` (U); `/browser_poll` says what the player did on it. +//! and `uses` (U); `/browser_poll` says what the player did on it; +//! `/browser_recipes ID` shows the recipes making ID (`/browser_recipes` +//! alone: the items again). use horizon_mod_sdk::{ Mod, Registration, browser, chat, command, game, input::{self, Event}, @@ -110,6 +112,7 @@ impl Mod for Guest { "recipes", "browser", "browser_poll", + "browser_recipes", "corner", "readings", ] @@ -310,6 +313,60 @@ impl Mod for Guest { input::register_key("uses", "Show uses", "key.keyboard.u")?; chat::show(&format!("panel of {}", items.len())); } + "browser_recipes" => { + let items = recipes::items(); + let id = |i: u32| { + items + .get(i as usize) + .map_or(String::new(), |x| x.id.clone()) + }; + let stack = |s: &recipes::Stack| browser::Stack { + item: id(s.item), + count: s.count, + components: s.components.clone(), + }; + let views: Vec = recipes::all() + .iter() + .filter(|r| !args.is_empty() && r.results.iter().any(|s| id(s.item) == args)) + .map(|r| { + use recipes::Kind; + let crafting = + matches!(r.kind, Kind::CraftingShaped | Kind::CraftingShapeless); + let shapeless = (r.slots.len() as u32).clamp(1, 3); + browser::RecipeView { + layout: match r.kind { + Kind::CraftingShaped | Kind::CraftingShapeless => { + browser::Layout::Grid + } + Kind::Stonecutting => browser::Layout::Single, + Kind::Smithing => browser::Layout::Smithing, + Kind::Brewing => browser::Layout::Brewing, + _ => browser::Layout::Cooking, + }, + width: if r.width == 0 { shapeless } else { r.width }, + height: if r.height == 0 { + (r.slots.len() as u32).div_ceil(3).max(1) + } else { + r.height + }, + slots: r + .slots + .iter() + .map(|s| s.iter().map(stack).collect()) + .collect(), + results: r.results.iter().map(stack).collect(), + note: if r.cooking_time > 0 { + format!("{} ticks", r.cooking_time) + } else { + String::new() + }, + action: crafting.then_some(r.kind == Kind::CraftingShaped), + } + }) + .collect(); + browser::set_recipes(&format!("Recipes for {args}"), &views); + chat::show(&format!("recipes shown: {}", views.len())); + } "browser_poll" => { let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components); // A hook shows at most 8 chat lines: the count, then the first 7. diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 298db26ba..6af12fa5b 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -588,9 +588,36 @@ A click on a slot of a recipe the panel shows (`set-recipes`). | `page` | `u32` | The player turned the recipes' page (`set-recipes`): the index of the first recipe now shown. | | `back` | | The back button of `set-recipes`. | +### enum `layout` + +How the game lays out a recipe of `set-recipes`. + +| Case | | +| --- | --- | +| `grid` | A crafting grid of `width` x `height` slots, an arrow and the result. | +| `cooking` | One input over a flame, an arrow and the result (furnaces, smokers, campfires). | +| `single` | One input, an arrow and the result (the stonecutter). | +| `smithing` | Template, base and addition, an arrow and the result. | +| `brewing` | A potion and an ingredient, an arrow and the result. | + +### record `recipe-view` + +A recipe to show. Each slot, and the result, cycles through its stacks, one a second; an empty slot shows nothing. + +| Field | Type | | +| --- | --- | --- | +| `layout` | `layout` | | +| `width` | `u32` | The grid's size (`grid` only), at most 3 x 3. | +| `height` | `u32` | | +| `slots` | `list>` | | +| `results` | `list` | | +| `note` | `string` | A short line under the recipe (a cooking time), or "". | +| `action` | `option` | The action button beside it: none, enabled, or shown greyed. | + | Function | Signature | What it does | | --- | --- | --- | | `set-items` | `func(items: list)` | The panel's items, at most 8192 (an empty list hides the panel). | +| `set-recipes` | `func(title: string, recipes: list)` | Shows these recipes in the panel instead of its items, as many as fit a page, under `title` and a back button; an empty list shows the items again. At most 256 recipes. | | `poll` | `func() -> list` | What the player did on the panel since the last poll, at most 256 kept. | ## `players` diff --git a/docs/api/stability.md b/docs/api/stability.md index bb0ddf501..1314d9813 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`, level 4 `recipes` (`items`, `all`, `known`), level 5 `browser` (`set-items`, `poll`). 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`), level 5 `browser` (`set-items`, `poll`, `set-recipes`). 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 9aed4897b..bbd14dc84 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -88,7 +88,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code; `browser.set-items`, `browser.poll`: a recipe viewer's panel of items right of the inventory and container screens (not the creative one), which the game pages and draws with its own slots and search box, and the mod hears its clicks, its searches and the mod's own keys (`input.register-key`) pressed over any item on the screen. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code; `browser.set-items`, `browser.poll`: a recipe viewer's panel of items right of the inventory and container screens (not the creative one), which the game pages and draws with its own slots and search box, and the mod hears its clicks, its searches and the mod's own keys (`input.register-key`) pressed over any item on the screen; `browser.set-recipes`: recipes in the panel's place (crafting grids, cooking, stonecutting, smithing and brewing layouts, their slots cycling through their stacks, a note and an action button each), paged by the game, with clicks on their slots, action buttons, page turns and a back button. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..: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"]` | From ad557fef4708767d3e60ab24f173192af04716e6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:03:42 +0100 Subject: [PATCH 024/132] game: a mod's recipe pages in the item panel browser.set-recipes replaces the panel's items with the mod's recipes, laid out with the game's slot, furnace arrow and flame sprites and small buttons: a crafting grid, one input over a flame, one input, three inputs or two, then an arrow and the result, a note under it and the action button beside the result (under it when the panel is narrow). Slots cycle through their stacks once a second. As many recipes as fit the panel's height make a page, with the recipe book's arrows; a title row holds a Back button and the title. The same title sent again keeps the page. Clicks on the slots, the action button, the arrows and Back reach the mod; tooltips and the mods' keys work on the recipes' stacks as on the items. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/mod_browser.rs | 89 +++- .../src/game/mod_browser_recipes.rs | 419 ++++++++++++++++++ 3 files changed, 486 insertions(+), 24 deletions(-) create mode 100644 crates/horizon-client/src/game/mod_browser_recipes.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6779d367a..ec21bdbb9 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_browser; +#[cfg(feature = "mods")] +mod mod_browser_recipes; mod mod_input; #[cfg(feature = "mods")] mod mod_recipes; diff --git a/crates/horizon-client/src/game/mod_browser.rs b/crates/horizon-client/src/game/mod_browser.rs index 2f317792f..3121eb05b 100644 --- a/crates/horizon-client/src/game/mod_browser.rs +++ b/crates/horizon-client/src/game/mod_browser.rs @@ -53,27 +53,29 @@ pub(super) struct Browser { search: Option, /// The search text the mod last heard. sent: String, + /// `set-recipes`' recipes, shown instead of the items. + pub(super) recipes: Option, } /// Where the panel's parts are this frame. #[cfg(feature = "mods")] -struct Layout { +pub(super) struct Layout { /// The panel's whole area, for clicks that hit none of its parts. - area: [f32; 4], + pub(super) area: [f32; 4], /// The grid's top left corner, its columns and rows. - grid: (f32, f32), - columns: usize, - rows: usize, + pub(super) grid: (f32, f32), + pub(super) columns: usize, + pub(super) rows: usize, /// The page arrows' row. - arrows_y: f32, - search: [f32; 4], + pub(super) arrows_y: f32, + pub(super) search: [f32; 4], } #[cfg(feature = "mods")] impl Layout { fn per_page(&self) -> usize { self.columns * self.rows } - fn width(&self) -> f32 { + pub(super) fn width(&self) -> f32 { self.columns as f32 * SLOT } fn slot(&self, n: usize) -> (f32, f32) { @@ -83,7 +85,7 @@ impl Layout { ) } /// The page arrows: backward, then forward. - fn arrows(&self) -> [(f32, f32); 2] { + pub(super) fn arrows(&self) -> [(f32, f32); 2] { [ (self.grid.0, self.arrows_y), (self.grid.0 + self.width() - 12.0, self.arrows_y), @@ -92,7 +94,7 @@ impl Layout { } #[cfg(feature = "mods")] -fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool { +pub(super) fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool { p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h } @@ -123,6 +125,12 @@ impl Game<'_> { list.iter().map(|s| browser_stack(items, s)).collect() }); self.mods.browser.stacks = stacks; + // The same title again (the mod updating its buttons) keeps the page. + let old = self.mods.browser.recipes.take(); + self.mods.browser.recipes = + self.mods.mods.browser_recipes(owner).map(|(title, list)| { + super::mod_browser_recipes::Pages::new(items, title, list, old) + }); self.mods.browser.of = Some((owner, version)); } Some(owner) @@ -159,8 +167,22 @@ impl Game<'_> { .div_ceil(layout.per_page()) .max(1) } + /// The stack under the pointer on the panel, an item's or a recipe's, + /// as the mod sent it and as a stack. + fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> { + if self.mods.browser.recipes.is_some() { + let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?; + return Some((sent, stack)); + } + let (index, stack) = self.browser_hovered(layout)?; + let (_, _, items) = self.mods.mods.browser_items()?; + Some((items.get(index)?.clone(), stack)) + } /// The panel's item under the pointer: its index and stack. fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> { + if self.mods.browser.recipes.is_some() { + return None; + } let first = self.mods.browser.page * layout.per_page(); (0..layout.per_page()).find_map(|n| { let (x, y) = layout.slot(n); @@ -182,16 +204,9 @@ impl Game<'_> { search } - /// Draws the panel over the open container screen, then the carried - /// stack or the tooltip again so they stay on top of it. - pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) { - if self.browser_sync().is_none() { - return; - } - let Some(layout) = self.browser_layout(batch) else { - return; - }; - let pages = self.browser_pages(&layout); + /// The items' page arrows and grid. + fn draw_browser_items(&mut self, batch: &mut HudBatch, layout: &Layout) { + let pages = self.browser_pages(layout); self.mods.browser.page = self.mods.browser.page.min(pages - 1); let page = self.mods.browser.page; let cursor = self.cursor; @@ -255,6 +270,22 @@ impl Game<'_> { horizon_client::widgets::Kind::Button, ); } + } + /// Draws the panel over the open container screen, then the carried + /// stack or the tooltip again so they stay on top of it. + pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) { + if self.browser_sync().is_none() { + return; + } + let Some(layout) = self.browser_layout(batch) else { + return; + }; + let cursor = self.cursor; + if self.mods.browser.recipes.is_some() { + self.draw_browser_recipes(batch, &layout); + } else { + self.draw_browser_items(batch, &layout); + } let hint = self.translate("gui.recipebook.search_hint", "Search..."); let search = self.browser_search(&layout); // The hint shows in an empty box without focus, as the recipe book's. @@ -264,8 +295,8 @@ impl Game<'_> { self.mods.browser.search = Some(search); if self.carried.is_some() { self.draw_carried(batch); - } else if let Some((_, stack)) = self.browser_hovered(&layout) { - let lines = self.stack_tooltip(&stack); + } else if let Some(stack) = self.browser_pointed_stack(&layout) { + let lines = self.stack_tooltip(&stack.1); self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1); } else { self.draw_slot_tooltip(batch); @@ -301,6 +332,10 @@ impl Game<'_> { return true; } search.focused = false; + if self.mods.browser.recipes.is_some() { + return self.browser_recipes_press(&layout, owner, right) + || inside(cursor, layout.area); + } let pages = self.browser_pages(&layout); let page = self.mods.browser.page; let [back, forward] = layout.arrows(); @@ -405,7 +440,10 @@ impl Game<'_> { .browser_sync() .and_then(|_| self.browser_layout(&batch)) { - Some(layout) if inside(self.cursor, layout.area) => self.browser_hovered(&layout)?.1, + // The panel's stacks as the mod sent them. + Some(layout) if inside(self.cursor, layout.area) => { + return Some(self.browser_pointed_stack(&layout)?.0); + } _ => { let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?; self.slot_view(slot)? @@ -422,7 +460,10 @@ impl Game<'_> { /// A mod's item as a stack: an item the game has, its components read as /// `/give` reads them (ones it can't read are left out). #[cfg(feature = "mods")] -fn browser_stack(items: &horizon_client::items::Items, s: &BrowserStack) -> Option { +pub(super) fn browser_stack( + items: &horizon_client::items::Items, + s: &BrowserStack, +) -> Option { items.get(&s.item)?; let (damage, extra) = if s.components.is_empty() { (0, None) diff --git a/crates/horizon-client/src/game/mod_browser_recipes.rs b/crates/horizon-client/src/game/mod_browser_recipes.rs new file mode 100644 index 000000000..14848de90 --- /dev/null +++ b/crates/horizon-client/src/game/mod_browser_recipes.rs @@ -0,0 +1,419 @@ +//! `browser.set-recipes` (docs/mods.md): a mod's recipes shown in its item +//! panel's place, laid out by the game with its own slots, arrows and +//! buttons, paged to the panel's height, under a title and a back button. +//! The mod hears clicks on their slots, their action buttons, the back +//! button and page turns. +use super::{ + Game, + mod_browser::{Layout, browser_stack, inside}, +}; +use horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, +}; +use horizon_mods::{BrowserEvent, BrowserLayout, BrowserRecipe, BrowserSlotClick, BrowserStack}; +use std::time::Instant; + +const SLOT: f32 = 18.0; +/// The title row's height, and the gap under each recipe. +const TITLE: f32 = 18.0; +const GAP: f32 = 6.0; + +/// One recipe as the game draws it. +pub(super) struct Shown { + layout: BrowserLayout, + width: usize, + height: usize, + /// Each slot's stacks (the result last), as the mod sent them and as + /// stacks; a stack the game doesn't have is left out of the cycle. + slots: Vec>, + note: String, + action: Option, +} + +/// The recipes a panel shows, and its page. +pub(super) struct Pages { + title: String, + recipes: Vec, + page: usize, + since: Instant, +} + +impl Pages { + pub(super) fn new( + items: &horizon_client::items::Items, + title: &str, + list: &[BrowserRecipe], + old: Option, + ) -> Self { + let kept = old.filter(|o| o.title == title); + let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> { + stacks + .iter() + .filter_map(|s| Some((s.clone(), browser_stack(items, s)?))) + .collect() + }; + let recipes = list + .iter() + .map(|r| { + let mut slots: Vec<_> = r.slots.iter().map(|s| cycle(s)).collect(); + slots.push(cycle(&r.results)); + Shown { + layout: r.layout, + width: r.width as usize, + height: r.height as usize, + slots, + note: r.note.clone(), + action: r.action, + } + }) + .collect(); + Self { + title: title.to_owned(), + recipes, + page: kept.as_ref().map_or(0, |o| o.page), + since: kept.map_or_else(Instant::now, |o| o.since), + } + } +} + +impl Shown { + /// The inputs' block: its size and each input slot's place in it. + fn inputs(&self) -> ((f32, f32), Vec<(f32, f32)>) { + let row = |n: usize| (0..n).map(|i| (i as f32 * SLOT, 0.0)).collect(); + match self.layout { + BrowserLayout::Grid => { + let (w, h) = (self.width.max(1), self.height.max(1)); + let at = (0..w * h) + .map(|i| ((i % w) as f32 * SLOT, (i / w) as f32 * SLOT)) + .collect(); + ((w as f32 * SLOT, h as f32 * SLOT), at) + } + // The input over the flame. + BrowserLayout::Cooking => ((SLOT, 2.0 * SLOT), vec![(0.0, 0.0)]), + BrowserLayout::Single => ((SLOT, SLOT), row(1)), + BrowserLayout::Smithing => ((3.0 * SLOT, SLOT), row(3)), + BrowserLayout::Brewing => ((2.0 * SLOT, SLOT), row(2)), + } + } + /// The height of its slots, arrow and button, `room` wide. + fn block(&self, room: f32) -> f32 { + let h = self.inputs().0.1; + let (_, _, action) = self.places(room); + match self.action { + Some(_) => h.max(action.1 + 12.0), + None => h, + } + } + fn height(&self, room: f32) -> f32 { + let note = if self.note.is_empty() { 0.0 } else { 11.0 }; + self.block(room) + note + GAP + } + /// Every slot's place from the recipe's corner (the result last), the + /// arrow's and the action button's: beside the result, or under it + /// when the panel is `room` wide and that doesn't fit. + fn places(&self, room: f32) -> (Vec<(f32, f32)>, (f32, f32), (f32, f32)) { + let ((w, h), mut at) = self.inputs(); + // The mod's slots beyond the layout's are not shown. + at.truncate(self.slots.len() - 1); + let arrow = (w + 4.0, ((h - 16.0) / 2.0).floor()); + let result = (w + 32.0, ((h - SLOT) / 2.0).floor()); + let action = if result.0 + SLOT + 16.0 <= room { + (result.0 + SLOT + 4.0, ((h - 12.0) / 2.0).floor()) + } else { + (result.0 + 3.0, result.1 + SLOT + 2.0) + }; + while at.len() < self.slots.len() - 1 { + at.push((f32::NAN, f32::NAN)); + } + at.push(result); + (at, arrow, action) + } +} + +impl Game<'_> { + /// The first recipe of each page, filling the panel from the title row + /// to the search box. + fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec { + let room = layout.search[1] - 4.0 - (layout.grid.1 + TITLE); + let mut starts = vec![0]; + let mut used = 0.0; + for (i, r) in pages.recipes.iter().enumerate() { + let h = r.height(layout.width()); + if used > 0.0 && used + h > room { + starts.push(i); + used = 0.0; + } + used += h; + } + starts + } + /// The recipes on the open page, each with its corner. + fn recipes_shown(&self, layout: &Layout) -> Vec<(usize, (f32, f32))> { + let Some(pages) = &self.mods.browser.recipes else { + return Vec::new(); + }; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len()); + let mut y = layout.grid.1 + TITLE; + (starts[page]..end) + .map(|i| { + let at = (layout.grid.0, y); + y += pages.recipes[i].height(layout.width()); + (i, at) + }) + .collect() + } + fn back_button(&self, layout: &Layout) -> ([f32; 4], String) { + let label = self.translate("gui.back", "Back"); + let w = HudBatch::text_width(&self.gui.atlas, &label) + 8.0; + ([layout.grid.0, layout.grid.1, w, 14.0], label) + } + /// What a slot of a shown recipe holds now: its stacks cycle once a second. + fn recipe_slot_now(&self, recipe: usize, slot: usize) -> Option<&(BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + let stacks = pages.recipes.get(recipe)?.slots.get(slot)?; + let n = pages.since.elapsed().as_secs() as usize; + stacks.get(n % stacks.len().max(1)) + } + /// The recipe slot under the pointer: recipe, slot, and its stack now. + pub(super) fn recipe_slot_hovered( + &self, + layout: &Layout, + ) -> Option<(usize, usize, BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + self.recipes_shown(layout) + .into_iter() + .find_map(|(i, (x, y))| { + let (at, _, _) = pages.recipes[i].places(layout.width()); + at.iter().enumerate().find_map(|(k, &(sx, sy))| { + if !inside(self.cursor, [x + sx, y + sy, SLOT, SLOT]) { + return None; + } + let (mod_stack, stack) = self.recipe_slot_now(i, k)?.clone(); + Some((i, k, mod_stack, stack)) + }) + }) + } + + /// Draws the title row, the page's recipes and the page arrows. + pub(super) fn draw_browser_recipes(&mut self, batch: &mut HudBatch, layout: &Layout) { + let Some(pages) = &self.mods.browser.recipes else { + return; + }; + let cursor = self.cursor; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let (title, pages_n) = (pages.title.clone(), starts.len()); + let (back, label) = self.back_button(layout); + let atlas = &self.gui.atlas; + let hover = inside(cursor, back); + let sprite = if hover { + "gui/sprites/widget/button_highlighted" + } else { + "gui/sprites/widget/button" + }; + horizon_client::ui::nine_slice( + batch, + atlas, + sprite, + back[0], + back[1], + back[2], + back[3], + u32::MAX, + ); + batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true); + horizon_client::widgets::record(&label, back, true); + let room = layout.width() - back[2] - 4.0; + let fit = atlas.font.fit(&title, room); + let shown: String = title.chars().take(fit).collect(); + batch.text( + atlas, + &shown, + back[0] + back[2] + 4.0, + back[1] + 3.0, + u32::MAX, + true, + ); + if pages_n > 1 { + let labels = [ + self.translate("gui.recipebook.previous_page", "Previous Page"), + self.translate("gui.recipebook.next_page", "Next Page"), + ]; + let visible = [page > 0, page + 1 < pages_n]; + let atlas = &self.gui.atlas; + for (((x, y), name), (label, visible)) in layout + .arrows() + .into_iter() + .zip(["page_backward", "page_forward"]) + .zip(labels.iter().zip(visible)) + { + if !visible { + continue; + } + let suffix = if inside(cursor, [x, y, 12.0, 17.0]) { + "_highlighted" + } else { + "" + }; + batch.sprite( + atlas, + &format!("gui/sprites/recipe_book/{name}{suffix}"), + x, + y, + ); + horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true); + } + let text = format!("{}/{pages_n}", page + 1); + let w = HudBatch::text_width(atlas, &text); + let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor(); + batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true); + } + for (i, (x, y)) in self.recipes_shown(layout) { + let Some(r) = self.mods.browser.recipes.as_ref().map(|p| &p.recipes[i]) else { + break; + }; + let (at, arrow, action) = r.places(layout.width()); + let h = r.block(layout.width()); + let (cooking, note, button) = + (r.layout == BrowserLayout::Cooking, r.note.clone(), r.action); + let atlas = &self.gui.atlas; + for &(sx, sy) in at.iter().filter(|p| p.0.is_finite()) { + batch.sprite(atlas, "gui/sprites/container/slot", x + sx, y + sy); + } + if cooking { + batch.sprite( + atlas, + "gui/sprites/container/furnace/lit_progress", + x + 2.0, + y + SLOT + 2.0, + ); + } + batch.sprite( + atlas, + "gui/sprites/container/furnace/burn_progress", + x + arrow.0, + y + arrow.1, + ); + if let Some(enabled) = button { + let rect = [x + action.0, y + action.1, 12.0, 12.0]; + let sprite = match (enabled, inside(cursor, rect)) { + (false, _) => "gui/sprites/widget/button_disabled", + (true, true) => "gui/sprites/widget/button_highlighted", + (true, false) => "gui/sprites/widget/button", + }; + horizon_client::ui::nine_slice( + batch, + atlas, + sprite, + rect[0], + rect[1], + 12.0, + 12.0, + u32::MAX, + ); + let color = if enabled { + u32::MAX + } else { + rgba(160, 160, 160, 255) + }; + batch.text(atlas, "+", rect[0] + 3.0, rect[1] + 2.0, color, true); + horizon_client::widgets::record(&format!("+ {i}"), rect, enabled); + } + if !note.is_empty() { + batch.text(atlas, ¬e, x, y + h + 2.0, rgba(224, 224, 224, 255), true); + } + for (k, &(sx, sy)) in at.iter().enumerate().filter(|(_, p)| p.0.is_finite()) { + let Some((_, stack)) = self.recipe_slot_now(i, k).cloned() else { + continue; + }; + self.draw_item(batch, &stack, x + sx + 1.0, y + sy + 1.0); + if inside(cursor, [x + sx, y + sy, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + sx + 1.0, + y + sy + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &format!("{name} {i}:{k}"), + [x + sx + 1.0, y + sy + 1.0, 16.0, 16.0], + true, + horizon_client::widgets::Kind::Button, + ); + } + } + } + + /// A press on the recipes: true when it hit one of their parts. + pub(super) fn browser_recipes_press( + &mut self, + layout: &Layout, + owner: usize, + right: bool, + ) -> bool { + let Some(pages) = &self.mods.browser.recipes else { + return false; + }; + let cursor = self.cursor; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let [back_arrow, forward] = layout.arrows(); + let turn = if page > 0 && inside(cursor, [back_arrow.0, back_arrow.1, 12.0, 17.0]) { + Some(page - 1) + } else if page + 1 < starts.len() && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) { + Some(page + 1) + } else { + None + }; + if let Some(to) = turn { + if let Some(p) = self.mods.browser.recipes.as_mut() { + p.page = to; + } + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Page(starts[to] as u32)); + return true; + } + if inside(cursor, self.back_button(layout).0) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods.mods.browser_event(owner, BrowserEvent::Back); + return true; + } + if let Some((recipe, slot, stack, _)) = self.recipe_slot_hovered(layout) { + let event = BrowserEvent::SlotClicked(BrowserSlotClick { + recipe: recipe as u32, + slot: slot as u32, + stack, + right, + }); + self.mods.mods.browser_event(owner, event); + return true; + } + let action = self.recipes_shown(layout).into_iter().find(|&(i, (x, y))| { + let r = &pages.recipes[i]; + let (_, _, (ax, ay)) = r.places(layout.width()); + r.action.is_some() && inside(cursor, [x + ax, y + ay, 12.0, 12.0]) + }); + if let Some((i, _)) = action { + if pages.recipes[i].action == Some(true) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Action(i as u32)); + } + return true; + } + false + } +} From 61ff050927187a07dc52c5083ac46e24d58ef230 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:11:56 +0100 Subject: [PATCH 025/132] mods: drop the sandbox test's unused LEVEL import Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mods/tests/sandbox.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index a5e95ddfa..96842e439 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -205,7 +205,7 @@ fn undeclared_capabilities_are_refused() { /// from the functions they import. #[test] fn a_mod_for_a_newer_horizon_is_refused() { - use horizon_mods::api_level::{LEVEL, imports, needed}; + use horizon_mods::api_level::{imports, needed}; use wit_parser::{ManglingAndAbi, Resolve}; let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit")) From db13c68585d2f491e0329f6897279176bf18d8ec Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:28:26 +0100 Subject: [PATCH 026/132] mods: recipes.place and recipes.give, a recipe viewer's actions recipes.place(book-id, all) is the recipe book's click: in the open inventory's or crafting table's grid it sends ServerboundPlaceRecipePacket on a server, or places it in this world, refused as handlePlaceRecipe refuses it (no crafting screen, a recipe the player's book doesn't hold, an impossible one); a recipe missing items shows as a ghost. recipes.give(stack) gives a creative player the stack as the creative inventory does; a server hears it as SetCreativeModeSlot through the inventory's sync. Both answer at once from the tick's snapshot (placing, creative, known) and take at most 36 calls a hook call. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 4 ++ crates/horizon-client/src/game/mod_recipes.rs | 18 ++++++ crates/horizon-client/src/game/mods.rs | 14 ++++ crates/horizon-client/src/game/recipe_book.rs | 28 ++++++++ crates/horizon-mod-sdk/wit/horizon.wit | 11 ++++ crates/horizon-mods/src/api_level.rs | 4 +- crates/horizon-mods/src/manifest.rs | 4 +- crates/horizon-mods/src/runtime.rs | 63 ++++++++++++++++++ crates/horizon-mods/tests/sandbox.rs | 43 ++++++++++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 64 +++++++++++++++++-- docs/api/mods-reference.md | 4 +- docs/api/stability.md | 2 +- docs/mods.md | 2 +- 13 files changed, 251 insertions(+), 10 deletions(-) diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 33095a115..cb3981955 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -268,6 +268,10 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), + Output::PlaceRecipe { book_id, all } => { + format!("placed recipe {book_id}{}", if all { " (all)" } else { "" }) + } + Output::Give { item, count, .. } => format!("gave {count} {item}"), Output::Shake { strength, seconds } => { format!("shook the camera: {strength:.2} for {seconds:.1} s") } diff --git a/crates/horizon-client/src/game/mod_recipes.rs b/crates/horizon-client/src/game/mod_recipes.rs index f02eb6424..0f65b0b42 100644 --- a/crates/horizon-client/src/game/mod_recipes.rs +++ b/crates/horizon-client/src/game/mod_recipes.rs @@ -70,6 +70,24 @@ fn recipe(id: String, kind: RecipeKind) -> Recipe { } impl Game<'_> { + /// `recipes.give`: a creative player takes the stack as from the + /// creative inventory; a server hears it as `SetCreativeModeSlot` + /// through the inventory's sync, and refuses it unless creative. + pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) { + if !self.creative || self.res.items().get(item).is_none() { + return; + } + let (damage, extra) = horizon_client::item_data::command_components(components) + .map_or((0, None), |tag| { + horizon_client::item_data::decode_components(Some(&tag)) + }); + let _ = self.give(ItemStack { + item: item.into(), + count, + damage, + extra, + }); + } /// Capability `recipes`'s tables and known displays for this tick's /// snapshot; nothing while no running mod reads them. pub(super) fn mod_recipes(&mut self) -> (Option>, Arc<[i32]>) { diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 40298a922..147a01df3 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -434,6 +434,8 @@ impl Game<'_> { view_hit: self.mod_view_hit(), recipes, known_recipes, + placing: self.mod_recipe_screen(), + creative: self.creative, } } /// The first block along the player's view within @@ -646,6 +648,18 @@ impl Game<'_> { self.mods.shake.add(strength, seconds); continue; } + Output::PlaceRecipe { book_id, all } => { + self.mod_place_recipe(book_id, all); + continue; + } + Output::Give { + item, + count, + components, + } => { + self.mod_give(&item, count, &components); + continue; + } Output::CloseScreen { owner } => { if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { self.close_mod_screen(false); diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 045abeb6f..024d45734 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -845,6 +845,34 @@ impl Game<'_> { self.recipe_ui.ghost.clear(); self.place_recipe(book_type, entry_index, use_max); } + /// Whether the open screen takes `recipes.place`: a crafting grid's + /// book (the inventory's or a crafting table's). + #[cfg(feature = "mods")] + pub(super) fn mod_recipe_screen(&self) -> bool { + self.screen == Screen::Inventory + && self.active_book() == Some(BookType::Crafting) + && !self.spectator() + } + /// `recipes.place`: the book's click on the recipe with this display + /// id, refused as `handlePlaceRecipe` refuses it (no crafting screen, + /// not in the player's book; an impossible one in `place_recipe`). + #[cfg(feature = "mods")] + pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) { + if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) { + return; + } + self.ensure_book(); + let Some(index) = self + .recipe_ui + .book + .as_ref() + .and_then(|b| b.entries.iter().position(|e| e.display_id == display_id)) + else { + return; + }; + self.recipe_ui.ghost.clear(); + self.place_recipe(BookType::Crafting, index, all); + } /// `ServerboundPlaceRecipePacket`: the server places the recipe /// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost /// recipe when the items are missing. diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 4896c3e21..897f669e5 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -507,6 +507,17 @@ interface recipes { all: func() -> list; /// The `book-id`s of the recipes the player's recipe book holds now. known: func() -> list; + /// Places a recipe in the open screen's grid as a click in the recipe + /// book does (`ServerboundPlaceRecipePacket`): the inventory's grid or + /// a crafting table. `all` places as many as the items allow, as with + /// Shift. Refused while no such screen is open, for a recipe the + /// player's book doesn't hold and for one that can't be placed; one + /// missing items shows as a ghost in the grid, as in the book. + place: func(book-id: s32, all: bool) -> result<_, string>; + /// Creative mode only: gives the player the stack, as taking it from + /// the creative inventory does (`ServerboundSetCreativeModeSlot`): the + /// selected slot first, then the hotbar, then the inventory. + give: func(stack: stack) -> result<_, string>; } /// Capability `ui` (experimental): a recipe viewer's panel beside the diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 7bb87b674..87984da02 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -13,7 +13,7 @@ pub const LEVEL: u32 = 5; /// 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); 40] = [ +pub const FUNCTIONS: [(&str, u32); 42] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -51,6 +51,8 @@ pub const FUNCTIONS: [(&str, u32); 40] = [ ("recipes.items", 4), ("recipes.all", 4), ("recipes.known", 4), + ("recipes.place", 5), + ("recipes.give", 5), ("browser.set-items", 5), ("browser.poll", 5), ("browser.set-recipes", 5), diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 4c12fd805..6b2cfdf03 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -158,7 +158,9 @@ 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", + Capability::Recipes => { + "read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items" + } } } /// The capability a component import needs, `Ok(None)` for one every diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 43c9e3fac..fed4e5c4f 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -156,6 +156,10 @@ pub struct Snapshot { pub recipes: Option>, /// The `book-id`s of the recipes the player's book holds. pub known_recipes: Arc<[i32]>, + /// The open screen takes recipes (`recipes.place`). + pub placing: bool, + /// The player is in creative mode (`recipes.give`). + pub creative: bool, } /// Capability `recipes`'s tables: `items` in the registry's order, which @@ -220,6 +224,15 @@ pub enum Output { CloseScreen { owner: usize }, /// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10). Shake { strength: f32, seconds: f32 }, + /// `recipes.place`: the recipe book's click on this display id, all of + /// it when `all`. + PlaceRecipe { book_id: i32, all: bool }, + /// `recipes.give`: a stack for a creative player. + Give { + item: String, + count: u32, + components: String, + }, } /// A mod's text panel, drawn every frame until it changes. @@ -329,6 +342,8 @@ struct BrowserState { static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); /// Items a panel may hold, and events kept for `browser.poll`. const BROWSER_ITEMS: usize = 8192; +/// `recipes.place` and `give` calls a hook call may make. +const RECIPE_ACTIONS: usize = 36; /// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles. const BROWSER_RECIPES: usize = 256; const RECIPE_SLOTS: usize = 9; @@ -1307,6 +1322,54 @@ impl recipes::Host for State { fn known(&mut self) -> Vec { self.snapshot.known_recipes.to_vec() } + fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> { + self.recipe_action()?; + if !self.snapshot.placing { + return Err("no screen that takes recipes is open".into()); + } + if !self.snapshot.known_recipes.contains(&book_id) { + return Err(format!( + "recipe {book_id} is not in the player's recipe book" + )); + } + self.out.push(Output::PlaceRecipe { book_id, all }); + Ok(()) + } + fn give(&mut self, stack: RecipeStack) -> Result<(), String> { + self.recipe_action()?; + if !self.snapshot.creative { + return Err("only in creative mode".into()); + } + let item = self + .snapshot + .recipes + .as_ref() + .and_then(|r| r.items.get(stack.item as usize)) + .ok_or_else(|| format!("no item {}", stack.item))? + .id + .clone(); + self.out.push(Output::Give { + item, + count: stack.count.clamp(1, 99), + components: clip_to(stack.components, 4096), + }); + Ok(()) + } +} +impl State { + /// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call. + fn recipe_action(&self) -> Result<(), String> { + let done = self + .out + .iter() + .filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. })) + .count(); + if done < RECIPE_ACTIONS { + Ok(()) + } else { + Err(format!("at most {RECIPE_ACTIONS} places and gives a call")) + } + } } impl State { /// Queues a chat line unless the call already sent [`CHAT_PER_CALL`]. diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 081884dc2..ea8cc0536 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1059,8 +1059,9 @@ fn recipes_reads_the_tables() { recipes[1].kind = RecipeKind::Brewing; recipes[1].results[0].components = "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into(); + let mods_recipes = Some(std::sync::Arc::new(Recipes { items, recipes })); mods.set_snapshot(Snapshot { - recipes: Some(std::sync::Arc::new(Recipes { items, recipes })), + recipes: mods_recipes.clone(), known_recipes: vec![1, 5, 9].into(), ..Snapshot::default() }); @@ -1091,6 +1092,46 @@ fn recipes_reads_the_tables() { .all(|e| e.status == horizon_mods::Status::Running), "it ran out of fuel" ); + // Actions: refused without a crafting screen, for an unknown recipe, + // and outside creative mode. + assert_eq!( + said(&mut mods, "recipe_place minecraft:recipe_5"), + ["place minecraft:recipe_5: no screen that takes recipes is open"] + ); + let mut snap = Snapshot { + recipes: mods_recipes.clone(), + known_recipes: vec![1, 5, 9].into(), + placing: true, + ..Snapshot::default() + }; + mods.set_snapshot(snap.clone()); + assert_eq!( + said(&mut mods, "recipe_place minecraft:recipe_6"), + ["place minecraft:recipe_6: recipe 6 is not in the player's recipe book"] + ); + assert!(mods.command("recipe_place minecraft:recipe_5 all")); + assert_eq!( + mods.drain()[0], + Output::PlaceRecipe { + book_id: 5, + all: true + } + ); + assert_eq!( + said(&mut mods, "recipe_give minecraft:item_7 3"), + ["give minecraft:item_7: only in creative mode"] + ); + snap.creative = true; + mods.set_snapshot(snap); + assert!(mods.command("recipe_give minecraft:item_7 3")); + assert_eq!( + mods.drain()[0], + Output::Give { + item: "minecraft:item_7".into(), + count: 3, + components: String::new() + } + ); // Without the game's tables (no mod read them yet): empty, not a trap. mods.set_snapshot(Snapshot::default()); assert_eq!( diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 751169565..2b1646614 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -12,7 +12,9 @@ //! items, `/browser` alone empties it) and registers the keys `recipe` (R) //! and `uses` (U); `/browser_poll` says what the player did on it; //! `/browser_recipes ID` shows the recipes making ID (`/browser_recipes` -//! alone: the items again). +//! alone: the items again). `/recipe_place ID [all]` places that recipe +//! with `recipes.place`; `/recipe_give ITEM [COUNT]` gives with +//! `recipes.give`. use horizon_mod_sdk::{ Mod, Registration, browser, chat, command, game, input::{self, Event}, @@ -69,7 +71,11 @@ fn shapes() -> Vec { ] } -struct Guest; +struct Guest { + /// `/recipe_place ID [all] later`: placed on the first tick a crafting + /// screen is open. + pending: Option<(i32, bool, String)>, +} fn widgets() -> Vec { vec![ @@ -113,12 +119,15 @@ impl Mod for Guest { "browser", "browser_poll", "browser_recipes", + "recipe_place", + "recipe_give", "corner", "readings", ] .into_iter() - .fold(Registration::new(), Registration::command); - Ok((Guest, hooks)) + .fold(Registration::new(), Registration::command) + .on_tick(); + Ok((Guest { pending: None }, hooks)) } fn command(&mut self, name: &str, args: &str) -> Result, String> { match name { @@ -367,6 +376,44 @@ impl Mod for Guest { browser::set_recipes(&format!("Recipes for {args}"), &views); chat::show(&format!("recipes shown: {}", views.len())); } + "recipe_place" => { + let mut words = args.split_whitespace(); + let id = words.next().unwrap_or_default(); + let rest: Vec<&str> = words.collect(); + let all = rest.contains(&"all"); + let book = recipes::all() + .iter() + .find(|r| r.id == id) + .map(|r| r.book_id); + if let Some(b) = book.filter(|_| rest.contains(&"later")) { + self.pending = Some((b, all, id.to_owned())); + chat::show(&format!("place {id}: waiting")); + return Ok(None); + } + chat::show(&match book.map(|b| recipes::place(b, all)) { + Some(Ok(())) => format!("place {id}: ok"), + Some(Err(e)) => format!("place {id}: {e}"), + None => format!("place {id}: no such recipe"), + }); + } + "recipe_give" => { + let mut words = args.split_whitespace(); + let id = words.next().unwrap_or_default(); + let count = words.next().and_then(|c| c.parse().ok()).unwrap_or(1); + let item = recipes::items().iter().position(|i| i.id == id); + let result = item.map(|i| { + recipes::give(&recipes::Stack { + item: i as u32, + count, + components: String::new(), + }) + }); + chat::show(&match result { + Some(Ok(())) => format!("give {id}: ok"), + Some(Err(e)) => format!("give {id}: {e}"), + None => format!("give {id}: no such item"), + }); + } "browser_poll" => { let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components); // A hook shows at most 8 chat lines: the count, then the first 7. @@ -402,6 +449,15 @@ impl Mod for Guest { } Ok(None) } + fn tick(&mut self, _tick: u64) { + if let Some((book, all, id)) = self.pending.take() { + match recipes::place(book, all) { + Err(e) if e.starts_with("no screen") => self.pending = Some((book, all, id)), + Ok(()) => chat::show(&format!("place {id}: ok")), + Err(e) => chat::show(&format!("place {id}: {e}")), + } + } + } fn ui_select(&mut self, id: u32, row: u32) { chat::show(&format!("selected {id}:{row}")); } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 6af12fa5b..b79ea5247 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -17,7 +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 | +| `recipes` | [`recipes`](#recipes) | read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items | ## World `horizon-mod` @@ -530,6 +530,8 @@ The station a recipe is made at. | `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. | +| `place` | `func(book-id: s32, all: bool) -> result<_, string>` | Places a recipe in the open screen's grid as a click in the recipe book does (`ServerboundPlaceRecipePacket`): the inventory's grid or a crafting table. `all` places as many as the items allow, as with Shift. Refused while no such screen is open, for a recipe the player's book doesn't hold and for one that can't be placed; one missing items shows as a ghost in the grid, as in the book. | +| `give` | `func(stack: stack) -> result<_, string>` | Creative mode only: gives the player the stack, as taking it from the creative inventory does (`ServerboundSetCreativeModeSlot`): the selected slot first, then the hotbar, then the inventory. | ## `browser` diff --git a/docs/api/stability.md b/docs/api/stability.md index 1314d9813..616767689 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`, level 4 `recipes` (`items`, `all`, `known`), level 5 `browser` (`set-items`, `poll`, `set-recipes`). A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 `recipes` (`items`, `all`, `known`), level 5 `browser` (`set-items`, `poll`, `set-recipes`) and `recipes.place` and `recipes.give`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: diff --git a/docs/mods.md b/docs/mods.md index bbd14dc84..706e48bd6 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -91,7 +91,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code; `browser.set-items`, `browser.poll`: a recipe viewer's panel of items right of the inventory and container screens (not the creative one), which the game pages and draws with its own slots and search box, and the mod hears its clicks, its searches and the mod's own keys (`input.register-key`) pressed over any item on the screen; `browser.set-recipes`: recipes in the panel's place (crafting grids, cooking, stonecutting, smithing and brewing layouts, their slots cycling through their stacks, a note and an action button each), paged by the game, with clicks on their slots, action buttons, page turns and a back button. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | -| `recipes` | `recipes` | `items()`: every item in the registry's order, with its name in the player's language and its tags; `all()`: every recipe (crafting, smelting, blasting, smoking, campfire, stonecutting, smithing, brewing), its slots as the stacks that fit each, its results, cooking time and experience, and the recipe book's id for it; `known()`: the book ids the player's recipe book holds. The recipes are the world's in single player and on Horizon's servers, vanilla 26.3's on any other server (a client is sent no others), while `known` follows that server's book. The game makes the tables once, when a mod first reads them. **Experimental:** `experimental = ["recipes"]` | +| `recipes` | `recipes` | `items()`: every item in the registry's order, with its name in the player's language and its tags; `all()`: every recipe (crafting, smelting, blasting, smoking, campfire, stonecutting, smithing, brewing), its slots as the stacks that fit each, its results, cooking time and experience, and the recipe book's id for it; `known()`: the book ids the player's recipe book holds; `place(book-id, all)`: the recipe book's click on a recipe, in the open inventory's or crafting table's grid (refused for a recipe the player's book doesn't hold, as vanilla's server refuses it); `give(stack)`: in creative mode, the stack into the player's inventory, as from the creative inventory. The recipes are the world's in single player and on Horizon's servers, vanilla 26.3's on any other server (a client is sent no others), while `known` follows that server's book. The game makes the tables once, when a mod first reads them. **Experimental:** `experimental = ["recipes"]` | | Hook (export) | When | |---|---| From 6a62ad67cce8fd23254f285ef6ba7881809216c7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:39:46 +0100 Subject: [PATCH 027/132] mods: set-recipes takes a row of tabs, and the tab event says which one the player picked Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mod-sdk/wit/horizon.wit | 10 +++-- crates/horizon-mods/src/runtime.rs | 37 ++++++++++++++----- crates/horizon-mods/tests/sandbox.rs | 10 +++-- crates/horizon-mods/tests/ui_guest/src/lib.rs | 21 ++++++++++- docs/api/mods-reference.md | 3 +- 5 files changed, 64 insertions(+), 17 deletions(-) diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 4896c3e21..5f8677df0 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -557,6 +557,8 @@ interface browser { page(u32), /// The back button of `set-recipes`. back, + /// The player picked the tab at this index of `set-recipes`' tabs. + tab(u32), } /// How the game lays out a recipe of `set-recipes`. enum layout { @@ -590,9 +592,11 @@ interface browser { /// The panel's items, at most 8192 (an empty list hides the panel). set-items: func(items: list); /// Shows these recipes in the panel instead of its items, as many as - /// fit a page, under `title` and a back button; an empty list shows the - /// items again. At most 256 recipes. - set-recipes: func(title: string, recipes: list); + /// fit a page, under `title` and a back button, with a row of `tabs` + /// (each an icon; `tab` is the selected one) between them; an empty + /// list of recipes shows the items again. At most 256 recipes and 16 + /// tabs. + set-recipes: func(title: string, tabs: list, tab: u32, recipes: list); /// What the player did on the panel since the last poll, at most 256 /// kept. poll: func() -> list; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 43c9e3fac..3b3acf5db 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -323,15 +323,25 @@ struct BrowserState { /// across mods and reloads, so the game converts them once. version: u64, /// `set-recipes`' title and recipes, shown instead of the items. - recipes: Option<(String, Vec)>, + recipes: Option, events: std::collections::VecDeque, } +/// What `browser.set-recipes` shows: a title, tabs (`tab` the selected +/// one) and the recipes. +#[derive(Clone, Debug)] +pub struct RecipePage { + pub title: String, + pub tabs: Vec, + pub tab: u32, + pub recipes: Vec, +} static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); /// Items a panel may hold, and events kept for `browser.poll`. const BROWSER_ITEMS: usize = 8192; /// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles. const BROWSER_RECIPES: usize = 256; const RECIPE_SLOTS: usize = 9; +const RECIPE_TABS: usize = 16; const SLOT_STACKS: usize = 64; const BROWSER_EVENTS: usize = 256; impl BrowserState { @@ -848,13 +858,11 @@ impl Mods { )) }) } - /// The recipes mod `owner`'s panel shows instead of its items - /// (`browser.set-recipes`): the title and the recipes. - pub fn browser_recipes(&self, owner: usize) -> Option<(&str, &[BrowserRecipe])> { + /// What mod `owner`'s panel shows instead of its items + /// (`browser.set-recipes`). + pub fn browser_recipes(&self, owner: usize) -> Option<&RecipePage> { let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser; - b.recipes - .as_ref() - .map(|(title, list)| (title.as_str(), list.as_slice())) + b.recipes.as_ref() } /// The player did `event` on mod `owner`'s panel. pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) { @@ -1261,7 +1269,13 @@ impl browser::Host for State { .collect(); self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - fn set_recipes(&mut self, title: String, recipes: Vec) { + fn set_recipes( + &mut self, + title: String, + tabs: Vec, + tab: u32, + recipes: Vec, + ) { let stack = |s: BrowserStack| BrowserStack { item: clip(s.item), components: clip_to(s.components, 4096), @@ -1283,7 +1297,12 @@ impl browser::Host for State { ..r }) .collect(); - (clip(title), recipes) + RecipePage { + title: clip(title), + tabs: tabs.into_iter().take(RECIPE_TABS).map(stack).collect(), + tab, + recipes, + } }); self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 081884dc2..28fd73ec6 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1196,9 +1196,13 @@ fn browser_lists_items_and_hears_the_player() { said(&mut mods, "browser_recipes minecraft:oak_planks"), ["recipes shown: 1"] ); - let (title, recipes) = mods.browser_recipes(owner).unwrap(); - assert_eq!(title, "Recipes for minecraft:oak_planks"); - let r = &recipes[0]; + let page = mods.browser_recipes(owner).unwrap(); + assert_eq!(page.title, "Recipes for minecraft:oak_planks"); + assert_eq!( + (page.tabs[0].item.as_str(), page.tab), + ("minecraft:crafting_table", 0) + ); + let r = &page.recipes[0]; assert_eq!( (r.layout, r.width, r.height, r.action), (BrowserLayout::Grid, 1, 1, Some(false)) diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 751169565..f879f4302 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -364,7 +364,25 @@ impl Mod for Guest { } }) .collect(); - browser::set_recipes(&format!("Recipes for {args}"), &views); + // A tab per layout shown, the first selected. + let mut tabs: Vec = Vec::new(); + for v in &views { + let icon = match v.layout { + browser::Layout::Grid => "minecraft:crafting_table", + browser::Layout::Cooking => "minecraft:furnace", + browser::Layout::Single => "minecraft:stonecutter", + browser::Layout::Smithing => "minecraft:smithing_table", + browser::Layout::Brewing => "minecraft:brewing_stand", + }; + if !tabs.iter().any(|t| t.item == icon) { + tabs.push(browser::Stack { + item: icon.into(), + count: 1, + components: String::new(), + }); + } + } + browser::set_recipes(&format!("Recipes for {args}"), &tabs, 0, &views); chat::show(&format!("recipes shown: {}", views.len())); } "browser_poll" => { @@ -389,6 +407,7 @@ impl Mod for Guest { browser::Event::Action(i) => format!("action {i}"), browser::Event::Page(first) => format!("page {first}"), browser::Event::Back => "back".into(), + browser::Event::Tab(i) => format!("tab {i}"), }); } } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 6af12fa5b..5e9593525 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -587,6 +587,7 @@ A click on a slot of a recipe the panel shows (`set-recipes`). | `action` | `u32` | The action button of the recipe at this index in `set-recipes`'s list. | | `page` | `u32` | The player turned the recipes' page (`set-recipes`): the index of the first recipe now shown. | | `back` | | The back button of `set-recipes`. | +| `tab` | `u32` | The player picked the tab at this index of `set-recipes`' tabs. | ### enum `layout` @@ -617,7 +618,7 @@ A recipe to show. Each slot, and the result, cycles through its stacks, one a se | Function | Signature | What it does | | --- | --- | --- | | `set-items` | `func(items: list)` | The panel's items, at most 8192 (an empty list hides the panel). | -| `set-recipes` | `func(title: string, recipes: list)` | Shows these recipes in the panel instead of its items, as many as fit a page, under `title` and a back button; an empty list shows the items again. At most 256 recipes. | +| `set-recipes` | `func(title: string, tabs: list, tab: u32, recipes: list)` | Shows these recipes in the panel instead of its items, as many as fit a page, under `title` and a back button, with a row of `tabs` (each an icon; `tab` is the selected one) between them; an empty list of recipes shows the items again. At most 256 recipes and 16 tabs. | | `poll` | `func() -> list` | What the player did on the panel since the last poll, at most 256 kept. | ## `players` From e2b1dc66914a82108611316e978a8aa379463de1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:49:12 +0100 Subject: [PATCH 028/132] Soul Speed: run its effects for each server-side player --- crates/horizon-client/src/game.rs | 15 +++++++- .../src/game/enchant_effects.rs | 34 +++++++++---------- crates/horizon-client/src/game/lan_actions.rs | 8 +++++ .../horizon-client/src/game/lan_particles.rs | 29 ++++++++++++++++ crates/horizon-client/src/motion.rs | 9 ++++- 5 files changed, 75 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 515a69cc8..6f856d1cb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4342,7 +4342,20 @@ impl Game<'_> { }; self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; - self.tick_soul_speed(); + if let Some((at, velocity)) = self.tick_soul_speed() { + self.particles.send_particles( + &horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Soul, + ), + at, + velocity, + 1.0, + 0, + ); + if let Some(host) = self.lan.as_ref() { + lan_particles::send_soul_particle(host, at, velocity); + } + } self.tick_avatar(before, riding); self.end_spin_attack(spin_hit); self.record_combat(&events); diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 8ae54dba7..ad9894da8 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -9,7 +9,6 @@ use super::Game; use horizon_client::{ enchant::{EffectContext, Enchantments, level_value}, items::ItemStack, - particles::{ParticleOptions, ParticleType}, }; use horizon_core::{position::BlockPos, random::RandomSource}; @@ -474,15 +473,16 @@ impl Game<'_> { /// (`enchantment_active_check`); /// - the boots lose 1 durability with a 4% chance when on such a block. /// - /// Every fifth tick the player walking on one also gets soul particles and - /// sometimes a sound. A remote server applies and syncs all of this itself. - pub(super) fn tick_soul_speed(&mut self) { + /// Every fifth tick the player walking on one also gets a soul particle + /// (returned as its position and velocity, for the caller to show or send + /// to the players around) and sometimes a sound. Runs for the window's own + /// player and for each guest on the server (`guest_server_tick`); a remote + /// client leaves it to its server. + pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> { const ID: &str = "minecraft:soul_speed"; - let Some(player) = self.player.as_mut() else { - return; - }; + let player = self.player.as_mut()?; if player.client_side { - return; + return None; } let level = self.armor[3] .as_ref() @@ -533,22 +533,19 @@ impl Game<'_> { self.wear_boots(1); } if level == 0 { - return; + return None; } let r = &mut self.world.random; - if tick_effects { - // `spawn_particles`: in the bounding box, 0.1 above the feet, thrown - // back against the movement (-0.2) and up (0.1). + // `spawn_particles`: in the bounding box, 0.1 above the feet, thrown + // back against the movement (-0.2) and up (0.1). + let particle = tick_effects.then(|| { let x = position.x + (r.next_double() - 0.5) * f64::from(width); let z = position.z + (r.next_double() - 0.5) * f64::from(width); - self.particles.send_particles( - &ParticleOptions::simple(ParticleType::Soul), + ( [x, position.y + 0.1, z], [moved.x * -0.2, 0.1, moved.z * -0.2], - 1.0, - 0, - ); - } + ) + }); // `play_sound`: its `random_chance` (35%) comes first in its `all_of`, // so the level random is drawn every tick the boots are worn; volume // 0.6, pitch 0.6 to 1.0. @@ -561,6 +558,7 @@ impl Game<'_> { pitch, ); } + particle } /// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`): /// Unbreaking applies, and they break when worn out. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bbb0c37c0..78227b475 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2115,6 +2115,7 @@ impl Game<'_> { let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; let sneaking = g.sneaking; + let mut soul = None; let events = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; @@ -2184,6 +2185,7 @@ impl Game<'_> { w.player.shift_key_down = sneaking; w.player.freeze_immune = freeze_immune; let _ = w.server_block_damage(start); + let _ = w.update_soul_speed_block(); let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); @@ -2211,6 +2213,9 @@ impl Game<'_> { // LivingEntity.baseTick: outside the world border, then tickEffects. game.border_damage(); game.tick_mob_effects(); + // Soul Speed's effects (LivingEntity.baseTick's location_changed + // and tick effects); its particle goes to the players around. + soul = game.tick_soul_speed(); let Some(player) = game.player.as_mut() else { return (Vec::new(), None); }; @@ -2238,6 +2243,9 @@ impl Game<'_> { let Some((events, marked)) = events else { return; }; + if let Some((at, velocity)) = soul { + super::lan_particles::send_soul_particle(host, at, velocity); + } self.as_guest(host, conn, |game| game.tick_player_sculk_events()); for event in events { match event { diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 719fe79ab..a11547759 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -24,6 +24,35 @@ fn rgb(c: [f32; 4]) -> [f32; 3] { [c[0], c[1], c[2]] } +/// `ServerLevel.sendParticles` of one soul particle moving by `velocity` +/// (Soul Speed's `spawn_particles`): sent to the players within 32 blocks. +pub(super) fn send_soul_particle(host: &super::lan::LanHost, at: [f64; 3], velocity: [f64; 3]) { + let Some(id) = host + .hub + .registry_id("minecraft:particle_type", "minecraft:soul") + else { + return; + }; + let packet = C::LevelParticles(play::LevelParticles { + particle: Particle { id, data: None }, + override_limiter: false, + always_show: false, + pos: at, + dist: velocity.map(|v| v as f32), + max_speed: [1.0; 3], + count: 0, + randomization: 0, + }); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } +} + impl Game<'_> { /// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point. /// Keep the local event's rendering; connected players receive one at rest. diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 156fc2549..084793049 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1007,7 +1007,7 @@ impl MotionWorld<'_, '_, '_> { ) }); self.player.try_add_frost(on_air)?; - self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?; + self.update_soul_speed_block()?; if self.player.health.tick_count % 40 == 0 && self.player.is_fully_frozen() && self.player.can_freeze() @@ -1020,6 +1020,13 @@ impl MotionWorld<'_, '_, '_> { } Ok(()) } + /// Refresh whether the player stands on a soul speed block, for the + /// `location_changed` enchantment effects (a server's player too, whose + /// client does the walking). + pub fn update_soul_speed_block(&mut self) -> Result<()> { + self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?; + Ok(()) + } /// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`. fn on_soul_speed_block(&mut self) -> Result { let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?; From 5d7097877bccd89bd0e448b875706ec8006ecdbf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:19:30 +0100 Subject: [PATCH 029/132] game: station tabs on the recipe pages A row of tabs above the recipe pages shows `set-recipes`' stations (their item in a slot, a white frame on the selected one). A click sends `tab(i)` to the mod, R/U over a tab works like over any slot, and horizon-ctl lists them as " tab". Changing tab resets the page. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mod_browser.rs | 12 +- .../src/game/mod_browser_recipes.rs | 116 ++++++++++++++++-- 2 files changed, 115 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/game/mod_browser.rs b/crates/horizon-client/src/game/mod_browser.rs index 3121eb05b..645415ccb 100644 --- a/crates/horizon-client/src/game/mod_browser.rs +++ b/crates/horizon-client/src/game/mod_browser.rs @@ -127,10 +127,11 @@ impl Game<'_> { self.mods.browser.stacks = stacks; // The same title again (the mod updating its buttons) keeps the page. let old = self.mods.browser.recipes.take(); - self.mods.browser.recipes = - self.mods.mods.browser_recipes(owner).map(|(title, list)| { - super::mod_browser_recipes::Pages::new(items, title, list, old) - }); + self.mods.browser.recipes = self + .mods + .mods + .browser_recipes(owner) + .map(|shown| super::mod_browser_recipes::Pages::new(items, shown, old)); self.mods.browser.of = Some((owner, version)); } Some(owner) @@ -171,6 +172,9 @@ impl Game<'_> { /// as the mod sent it and as a stack. fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> { if self.mods.browser.recipes.is_some() { + if let Some((_, sent, stack)) = self.recipe_tab_hovered(layout) { + return Some((sent, stack)); + } let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?; return Some((sent, stack)); } diff --git a/crates/horizon-client/src/game/mod_browser_recipes.rs b/crates/horizon-client/src/game/mod_browser_recipes.rs index 14848de90..13b3b78e1 100644 --- a/crates/horizon-client/src/game/mod_browser_recipes.rs +++ b/crates/horizon-client/src/game/mod_browser_recipes.rs @@ -11,12 +11,14 @@ use horizon_client::{ hud::{HudBatch, rgba}, items::ItemStack, }; -use horizon_mods::{BrowserEvent, BrowserLayout, BrowserRecipe, BrowserSlotClick, BrowserStack}; +use horizon_mods::{BrowserEvent, BrowserLayout, BrowserSlotClick, BrowserStack, RecipePage}; use std::time::Instant; const SLOT: f32 = 18.0; /// The title row's height, and the gap under each recipe. const TITLE: f32 = 18.0; +/// A tab's step: an 18 px slot and a gap. +const TAB: f32 = 20.0; const GAP: f32 = 6.0; /// One recipe as the game draws it. @@ -34,6 +36,9 @@ pub(super) struct Shown { /// The recipes a panel shows, and its page. pub(super) struct Pages { title: String, + /// The tabs' icons and the selected one. + tabs: Vec<(BrowserStack, Option)>, + tab: usize, recipes: Vec, page: usize, since: Instant, @@ -42,11 +47,11 @@ pub(super) struct Pages { impl Pages { pub(super) fn new( items: &horizon_client::items::Items, - title: &str, - list: &[BrowserRecipe], + shown: &RecipePage, old: Option, ) -> Self { - let kept = old.filter(|o| o.title == title); + let (title, list, tab) = (&shown.title, &shown.recipes, shown.tab as usize); + let kept = old.filter(|o| o.title == *title && o.tab == tab); let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> { stacks .iter() @@ -69,7 +74,13 @@ impl Pages { }) .collect(); Self { - title: title.to_owned(), + title: title.clone(), + tabs: shown + .tabs + .iter() + .map(|t| (t.clone(), browser_stack(items, t))) + .collect(), + tab, recipes, page: kept.as_ref().map_or(0, |o| o.page), since: kept.map_or_else(Instant::now, |o| o.since), @@ -131,11 +142,30 @@ impl Shown { } } +/// The tabs' places, in rows under the title row. +fn tab_places(pages: &Pages, layout: &Layout) -> Vec<(f32, f32)> { + let per_row = ((layout.width() / TAB).floor() as usize).max(1); + (0..pages.tabs.len()) + .map(|i| { + ( + layout.grid.0 + (i % per_row) as f32 * TAB, + layout.grid.1 + TITLE + 3.0 + (i / per_row) as f32 * TAB, + ) + }) + .collect() +} +/// Where the recipes start: under the title row and the tabs. +fn recipes_top(pages: &Pages, layout: &Layout) -> f32 { + let tabs = tab_places(pages, layout); + tabs.last() + .map_or(layout.grid.1 + TITLE, |&(_, y)| y + TAB + 3.0) +} + impl Game<'_> { - /// The first recipe of each page, filling the panel from the title row - /// to the search box. + /// The first recipe of each page, filling the panel from the tabs to + /// the search box. fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec { - let room = layout.search[1] - 4.0 - (layout.grid.1 + TITLE); + let room = layout.search[1] - 4.0 - recipes_top(pages, layout); let mut starts = vec![0]; let mut used = 0.0; for (i, r) in pages.recipes.iter().enumerate() { @@ -156,7 +186,7 @@ impl Game<'_> { let starts = Self::recipe_pages(pages, layout); let page = pages.page.min(starts.len() - 1); let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len()); - let mut y = layout.grid.1 + TITLE; + let mut y = recipes_top(pages, layout); (starts[page]..end) .map(|i| { let at = (layout.grid.0, y); @@ -177,6 +207,21 @@ impl Game<'_> { let n = pages.since.elapsed().as_secs() as usize; stacks.get(n % stacks.len().max(1)) } + /// The tab under the pointer: its index and icon. + pub(super) fn recipe_tab_hovered( + &self, + layout: &Layout, + ) -> Option<(usize, BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + let places = tab_places(pages, layout); + places.iter().enumerate().find_map(|(i, &(x, y))| { + if !inside(self.cursor, [x, y, SLOT, SLOT]) { + return None; + } + let (sent, stack) = pages.tabs.get(i)?; + Some((i, sent.clone(), stack.clone()?)) + }) + } /// The recipe slot under the pointer: recipe, slot, and its stack now. pub(super) fn recipe_slot_hovered( &self, @@ -237,6 +282,7 @@ impl Game<'_> { u32::MAX, true, ); + self.draw_recipe_tabs(batch, layout); if pages_n > 1 { let labels = [ self.translate("gui.recipebook.previous_page", "Previous Page"), @@ -351,6 +397,50 @@ impl Game<'_> { } } + /// The tabs, on slots; the selected one framed. + fn draw_recipe_tabs(&mut self, batch: &mut HudBatch, layout: &Layout) { + let Some(pages) = &self.mods.browser.recipes else { + return; + }; + let places = tab_places(pages, layout); + let tabs: Vec> = pages.tabs.iter().map(|t| t.1.clone()).collect(); + let selected = pages.tab; + for (i, (&(x, y), stack)) in places.iter().zip(tabs).enumerate() { + let atlas = &self.gui.atlas; + batch.sprite(atlas, "gui/sprites/container/slot", x, y); + let Some(stack) = stack else { + continue; + }; + self.draw_item(batch, &stack, x + 1.0, y + 1.0); + // The selected tab: a white frame around its slot. + if i == selected { + let white = rgba(255, 255, 255, 255); + let atlas = &self.gui.atlas; + batch.fill(atlas, x - 1.0, y - 1.0, SLOT + 2.0, 1.0, white); + batch.fill(atlas, x - 1.0, y + SLOT, SLOT + 2.0, 1.0, white); + batch.fill(atlas, x - 1.0, y, 1.0, SLOT, white); + batch.fill(atlas, x + SLOT, y, 1.0, SLOT, white); + } + if inside(self.cursor, [x, y, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + 1.0, + y + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &format!("{name} tab"), + [x + 1.0, y + 1.0, 16.0, 16.0], + true, + horizon_client::widgets::Kind::Tab(i == selected), + ); + } + } + /// A press on the recipes: true when it hit one of their parts. pub(super) fn browser_recipes_press( &mut self, @@ -383,6 +473,14 @@ impl Game<'_> { .browser_event(owner, BrowserEvent::Page(starts[to] as u32)); return true; } + if let Some((tab, _, _)) = self.recipe_tab_hovered(layout) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Tab(tab as u32)); + return true; + } if inside(cursor, self.back_button(layout).0) { self.audio .play("minecraft:ui.button.click", None, 0.25, 1.0); From 705e3d10cf00e1fd4e504c6a974432531f5f983a Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 14:11:07 +0100 Subject: [PATCH 030/132] Force-loaded chunks decorate in vanilla's order Chunks no player ticket reached were decorated nearest the centre first. Vanilla's ForceLoadCommand adds a FORCED ticket per chunk, x-outer and z-inner, and the FULL tasks run in that order, so a chunk decorates before its neighbour at higher x or z. Both orders agree only in the +x, +z quarter of the map. Elsewhere features crossing chunk borders overwrote each other the other way round: a geode next door ate a trial chamber's dispensers, sculk or a clay pool closed a dungeon so it was never placed, and ore, stone and tree blobs swapped. The forceload command now ranks the chunks it adds in vanilla's order (decoration_order::forced_order, which shares its scheduler with vanilla_order); chunks without a rank still go last, nearest first. Co-Authored-By: Claude Opus 5.5 --- .../src/game/commands/pregen.rs | 6 +- .../src/game/commands/terrain_cmds.rs | 3 + crates/horizon-client/src/game/levels.rs | 3 +- crates/horizon-client/src/streaming.rs | 8 +++ .../src/worldgen/decoration_order.rs | 67 +++++++++++++++---- 5 files changed, 71 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game/commands/pregen.rs b/crates/horizon-client/src/game/commands/pregen.rs index d497e2734..eb3c37688 100644 --- a/crates/horizon-client/src/game/commands/pregen.rs +++ b/crates/horizon-client/src/game/commands/pregen.rs @@ -244,7 +244,11 @@ impl Game<'_> { /// hand them the next jobs as soon as each one is done, rather than once /// a tick. pub(in crate::game) fn pump_pregen(&mut self, until: Instant) { - while self.pregen_runs_here() { + // Force-loaded chunks too: decorating in vanilla's order, a chunk + // waits for its neighbours far more often than once a tick allows. + while self.pregen_runs_here() + || (!self.streaming.forced.is_empty() && self.streaming.busy()) + { let now = Instant::now(); if now >= until { break; diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index d4b1c125c..824ca4d60 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -120,6 +120,9 @@ impl Game<'_> { tracker.track(&holder(chunk_text(x, z)), i32::from(changed)); } } + if add { + self.streaming.rank_forced(cx0, cz0, cx1, cz1); + } let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1)); let verb = if add { "added" } else { "removed" }; let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 8d2e0a4a2..8ba18ac22 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -383,7 +383,8 @@ impl Game<'_> { } *next += self.clock.tick_duration(); if *next > now { - // A `/pregen` task keeps the workers fed until the next tick. + // A `/pregen` task or force-loaded chunks keep the workers fed + // until the next tick. self.pump_pregen(*next); let now = Instant::now(); if *next > now { diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 643a604bc..bc43d1c94 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -1381,6 +1381,14 @@ impl Streaming { pub fn band(&self) -> Option { self.band } + /// Rank the chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` + /// decorates in vanilla's order (`forced_order`), after every chunk + /// ranked before. + pub fn rank_forced(&mut self, x0: i32, z0: i32, x1: i32, z1: i32) { + for (x, z) in horizon_world::worldgen::decoration_order::forced_order(x0, z0, x1, z1) { + self.decoration_order.rank_or_append(x, z); + } + } /// Generate, light and keep the chunks of `band` (none: stop), and let /// go of what earlier bands held as it falls out of range. The chunks a /// band reaches are ranked for decoration row by row, as they first come diff --git a/crates/horizon-world/src/worldgen/decoration_order.rs b/crates/horizon-world/src/worldgen/decoration_order.rs index 6b0fb2252..0e53e7d09 100644 --- a/crates/horizon-world/src/worldgen/decoration_order.rs +++ b/crates/horizon-world/src/worldgen/decoration_order.rs @@ -29,7 +29,7 @@ //! overlap), so a chunk may be decorated as soon as no lower-ranked chunk //! within two of it is still waiting: [`DecorationOrder::blocked`]. Chunks //! further apart still decorate in parallel. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; #[derive(Default)] pub struct DecorationOrder { @@ -121,7 +121,6 @@ fn ticket_hash(x: i32, z: i32) -> u64 { /// The chunks decorated around a player at `center`, in vanilla's order. pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; - use std::collections::{BinaryHeap, VecDeque}; let mut tickets: Vec<(i32, i32)> = (-radius..=radius) .flat_map(|dx| (-radius..=radius).map(move |dz| (center.0 + dx, center.1 + dz))) .collect(); @@ -132,16 +131,31 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { Reverse(ticket_hash(x, z) & (TICKET_SET_CAPACITY - 1)), ) }); - let mut tickets: VecDeque<_> = tickets.into(); // Every chunk this touches lies within `half` of the centre: tickets // reach `LIGHT_LEVEL - TICKET_LEVEL` further, and FULL tasks decorate - // one more ring. Dense grids over that square replace hash maps. + // one more ring. + let half = radius.max(0) + LIGHT_LEVEL - TICKET_LEVEL + 1; + ticket_order( + tickets.into(), + TICKETS_IN_FLIGHT, + (center.0 - half, center.1 - half), + (2 * half + 1) as usize, + ) +} + +/// The decoration order of `tickets` (level 31) added in turn, at most +/// `in_flight` at a time. Dense grids of `side` chunks from `origin` hold +/// every chunk this touches, in place of hash maps. +fn ticket_order( + mut tickets: VecDeque<(i32, i32)>, + in_flight: usize, + origin: (i32, i32), + side: usize, +) -> Vec<(i32, i32)> { + use std::cmp::Reverse; + use std::collections::BinaryHeap; let reach = LIGHT_LEVEL - TICKET_LEVEL; - let half = radius.max(0) + reach + 1; - let side = (2 * half + 1) as usize; - let cell = |(x, z): (i32, i32)| { - ((x - center.0 + half) as usize) * side + (z - center.1 + half) as usize - }; + let cell = |(x, z): (i32, i32)| ((x - origin.0) as usize) * side + (z - origin.1) as usize; let mut active: Vec<(i32, i32)> = Vec::new(); // Queued task per chunk (level, sequence), `NONE` when there is none; // stale heap entries are skipped. @@ -177,10 +191,9 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { } } }; - for _ in 0..TICKETS_IN_FLIGHT { - if let Some(t) = tickets.pop_front() { - add(t, &mut active, &mut queued, &mut heap, &full); - } + while active.len() < in_flight { + let Some(t) = tickets.pop_front() else { break }; + add(t, &mut active, &mut queued, &mut heap, &full); } while let Some(Reverse((l, s, chunk))) = heap.pop() { let i = cell(chunk); @@ -202,7 +215,7 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { full[i] = true; } active.retain(|t| !(-2..=2).all(|dx| (-2..=2).all(|dz| full[cell((t.0 + dx, t.1 + dz))]))); - while active.len() < TICKETS_IN_FLIGHT { + while active.len() < in_flight { let Some(t) = tickets.pop_front() else { break }; add(t, &mut active, &mut queued, &mut heap, &full); } @@ -210,10 +223,36 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { order } +/// The chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` decorates, +/// in vanilla's order: ForceLoadCommand adds a FORCED ticket (level 31) per +/// chunk, x-outer, z-inner, all at once. +pub fn forced_order(x0: i32, z0: i32, x1: i32, z1: i32) -> Vec<(i32, i32)> { + let tickets = (x0..=x1) + .flat_map(|x| (z0..=z1).map(move |z| (x, z))) + .collect(); + let pad = LIGHT_LEVEL - TICKET_LEVEL + 1; + let side = ((x1 - x0).max(z1 - z0) + 2 * pad + 1) as usize; + ticket_order(tickets, usize::MAX, (x0 - pad, z0 - pad), side) +} + #[cfg(test)] mod tests { use super::*; + /// Seed 8675309's geodes in chunks (-26, -1) and (14, -20) run into the + /// trial chambers of (-26, 0) and (14, -19); vanilla decorates the lower + /// z first, wherever the batch lies, so the chambers are drawn over them. + #[test] + fn forced_chunks_decorate_x_outer_z_inner() { + let rank = |order: &[(i32, i32)], c| order.iter().position(|&o| o == c).unwrap(); + let west = forced_order(-32, -16, -17, -1); + assert!(rank(&west, (-26, -1)) < rank(&west, (-26, 0))); + let east = forced_order(0, -32, 15, -17); + assert!(rank(&east, (14, -20)) < rank(&east, (14, -19))); + assert_eq!(west[0], (-33, -17)); + assert_eq!(west.len(), 22 * 22); + } + /// The hash map version this module had before its dense grids. fn hashed_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; From 8c2ef15171d2bdfd31a07c83f5ea80df315068e1 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 13:58:26 +0100 Subject: [PATCH 031/132] Falling suspicious sand and gravel break where they land BrushableBlock.tick makes the falling block entity with disableDrop, so vanilla breaks it on landing (onBrokenAfterFall: level event 2001 and the block_destroy game event) and places nothing. Horizon landed it as a plain block without its archaeology block entity. Seen in pre-generated worlds: suspicious gravel of cold ocean ruins that sits over water fell during the first ticks and landed one block lower without its block entity, so with no loot. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/falling_block.rs | 20 +++++++++++++++++++ crates/horizon-client/src/game.rs | 8 +++----- .../horizon-client/src/game/falling_damage.rs | 19 ++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs index 79ca28f7a..4faf105b9 100644 --- a/crates/horizon-client/src/falling_block.rs +++ b/crates/horizon-client/src/falling_block.rs @@ -35,6 +35,18 @@ impl Damage { ..Self::default() } } + /// A block that starts to fall: anvils hurt, and a brushable block + /// breaks where it lands (BrushableBlock.tick: disableDrop). + pub fn falling(block: &str) -> Self { + if block.ends_with("anvil") { + Self::anvil() + } else { + Self { + cancel_drop: block.starts_with("minecraft:suspicious_"), + ..Self::default() + } + } + } pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { Self { hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), @@ -181,6 +193,14 @@ pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { #[cfg(test)] mod tests { use super::*; + #[test] + fn only_brushable_blocks_break_where_they_land() { + assert!(Damage::falling("minecraft:suspicious_gravel").cancel_drop); + assert!(Damage::falling("minecraft:suspicious_sand").cancel_drop); + assert!(!Damage::falling("minecraft:gravel").cancel_drop); + assert!(Damage::falling("minecraft:chipped_anvil").hurt_entities); + } + #[test] fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { let damage = Damage::anvil(); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..b961b6d16 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2971,11 +2971,9 @@ impl Game<'_> { drop_item: true, fall_distance: 0.0, stuck: Vec3::ZERO, - damage: if self.res.facts().get(state).name.ends_with("anvil") { - horizon_client::falling_block::Damage::anvil() - } else { - Default::default() - }, + damage: horizon_client::falling_block::Damage::falling( + &self.res.facts().get(state).name, + ), saved: None, }); } diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index 8eec28d1d..08d96d7d1 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -64,6 +64,25 @@ impl Game<'_> { pos: BlockPos::new(pos[0], pos[1], pos[2]), data: 0, }); + } else if self + .res + .facts() + .get(block.state) + .name + .starts_with("minecraft:suspicious_") + { + // BrushableBlock.onBrokenAfterFall. + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.level_events.push(LevelEvent::LevelEvent { + id: 2001, + pos: at, + data: block.state.0 as i32, + }); + self.level_events.push(LevelEvent::GameEvent { + pos: at, + event: "minecraft:block_destroy", + state: None, + }); } return; } From 55a066e88a7b0739903a6ef6f46d33ed4f19b7c3 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 16:20:45 +0100 Subject: [PATCH 032/132] End: spike crystals are saved with the chunk that generates them SpikeFeature.placeSpike adds each crystal to the WorldGenRegion, so a pre-generated End holds its ten crystals before anyone ticks it. Horizon's decoration dropped spawn_end_crystal and the game placed the crystals later, once the arena was loaded and ticking. An End generated with ticks frozen, as a seed generator does, had none. The decoration region now writes the crystal like any placed entity; the game's own placement still skips a spike that has its crystal. Co-Authored-By: Claude Opus 5.5 --- .../src/worldgen/generator_decoration.rs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc1cd8bcf..426cd98a4 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -851,6 +851,33 @@ impl PlacementContext for World<'_> { self.entities.push(nbt); Ok(()) } + /// SpikeFeature.placeSpike: the crystal is a fresh entity of the region, + /// saved with the chunk. + fn spawn_end_crystal( + &mut self, + position: [f64; 3], + yaw: f32, + beam_target: Option<[i32; 3]>, + invulnerable: bool, + ) -> Result<(), PlacementQueryError> { + use crate::nbt::Tag; + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String("minecraft:end_crystal".into())); + nbt.insert( + "Pos".into(), + Tag::List(position.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ); + nbt.insert( + "Rotation".into(), + Tag::List(vec![Tag::Float(yaw.to_bits()), Tag::Float(0)]), + ); + nbt.insert("Invulnerable".into(), Tag::Byte(i8::from(invulnerable))); + nbt.insert("ShowBottom".into(), Tag::Byte(1)); + if let Some(b) = beam_target { + nbt.insert("beam_target".into(), Tag::IntArray(b.to_vec())); + } + self.add_entity(nbt) + } fn set_block_entity( &mut self, position: [i32; 3], From 1eb7a04a4e17cfd56cf2b6f530c123c1c8ec83cb Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 13:41:57 +0100 Subject: [PATCH 033/132] End: no exit portal while nobody is in the fight With force-loaded levels ticking without players (#1525), Horizon placed the exit portal as soon as the End's main island was loaded. Vanilla only places it from scanState and the dragon's death, both with players in the fight, so a pre-generated End has no portal until someone arrives. test_forced_end_parity force-loads the End's arena on vanilla's and Horizon's dedicated servers with nobody online and compares what is around 0, 0. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 4 +- docs/architecture.md | 2 +- tools/test_forced_end_parity.py | 91 ++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 2 deletions(-) create mode 100755 tools/test_forced_end_parity.py diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..a2602fb96 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2598,7 +2598,9 @@ impl Game<'_> { } pub(super) fn fight_ready(&mut self) -> bool { self.load_fight(); - self.fight.loaded + // spawnExitPortal runs from scanState and the dragon's death, both + // only with players in the fight. + self.fight.loaded && self.fight.players } pub(super) fn exit_portal(&self) -> Option<[i32; 3]> { self.fight.exit_portal diff --git a/docs/architecture.md b/docs/architecture.md index 0350bd1ea..8e19046f8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -46,7 +46,7 @@ file selects ~103. | 29 | Title, worlds, startup (49) | `L/title.rs` + `L/title/`, `G/startup_menu.rs`, `L/title_edition.rs` | world_options; `cargo test -p horizon-client --lib title` | | 30 | Dedicated server, horizon-server (48) | `G/dedicated.rs`, `G/dedicated/status.rs`, `crates/horizon-server/`, `crates/horizon-server-files/` | dedicated_server, server_files, user_cache, online_mode, server_ops_feedback | | 31 | Particles and client effects (46) | `L/particles.rs`, `G/render_tick.rs`, `G/level_particles.rs`, `L/animate_tick.rs` | particle_providers, block_particles, entity_particles, emitter_particles, marker_particles | -| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, end_podium, end_gateway | +| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, forced_end, end_podium, end_gateway | | 33 | Protocol and packets (44) | `crates/horizon-protocol/src/` (`packets/play.rs`, `entity_data.rs`, `connection.rs`) | dedicated_server, online_mode, secure_chat; `cargo test -p horizon-protocol` | | 34 | Multiplayer and LAN screens, friends (44) | `L/multiplayer.rs`, `G/lan_screen.rs`, `G/friends.rs`, `L/friends_screen.rs`, `crates/horizon-friends/`, `crates/horizon-relay/` | lan, world_options; `python3 tools/test_friends.py` | | 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser | diff --git a/tools/test_forced_end_parity.py b/tools/test_forced_end_parity.py new file mode 100755 index 000000000..81a92e4ed --- /dev/null +++ b/tools/test_forced_end_parity.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""The End of a dedicated server nobody has entered, force-loaded from the console, against vanilla's. + +A vanilla dedicated server and Horizon's each open a copy of one world vanilla generated (its End not made yet). +With no player online, the console force-loads the End's main island and its arena. A FORCED ticket keeps its level active +(`ServerChunkCache.hasActiveTickets`, `TicketType.FORCED`), so the chunks are generated, loaded and ticked +without a player in the dimension. With nobody in the fight, `EnderDragonFight.tick` neither scans the state nor +places the exit portal: no bedrock and no torches around 0, 0. Both servers must answer the same. +""" +import os +import re +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server, wait_ticks + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server, wait_ticks + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'forced-end-parity' +END = 'execute in minecraft:the_end' +QUERIES = [ + f'{END} run fill -3 0 -3 3 255 3 minecraft:air replace minecraft:bedrock', + f'{END} run fill -3 0 -3 3 255 3 minecraft:air replace minecraft:wall_torch', +] + + +def answer(server, command, n): + start = len(server.lines) + server.console(command) + server.console(f'say done {n}') + server.wait_for(rf'\[Server\] done {n}$', timeout=120) + replies = [l.split(']: ', 1)[-1] for l in server.lines[start:] if 'done ' not in l] + return ' / '.join(r for r in replies if r) or '(no reply)' + + +def run_side(label, command, build, world): + directory = build / label + server_dir(directory, world) + server = Server(command, directory, label) + try: + server.wait_for(r'Done \(') + # The main island's arena (EnderDragonFight.isArenaLoaded: chunks -8..8), in pieces of at most 256 chunks. + for area in ('-128 -128 143 -1', '-128 0 143 143'): + server.console(f'{END} run forceload add {area}') + deadline = time.time() + 600 + for poll in range(1_000_000): + reply = answer(server, f'{END} if loaded 0 0 0', f'loaded {poll}') + if 'passed' in reply: + break + if time.time() > deadline: + raise AssertionError(f'{label}: the End centre never loaded') + time.sleep(2) + wait_ticks(server, 200) + return {q: answer(server, q, i) for i, q in enumerate(QUERIES)} + finally: + server.stop() + + +def main(): + _, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + binary = lab.cargo_target() / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + world = generate_world(vanilla_server, build) + vanilla = run_side('vanilla', vanilla_server, build, world) + horizon = run_side('horizon', horizon_server, build, world) + normal = lambda s: re.sub(r'\s+', ' ', s).strip() + problems = [f'{q}\n vanilla: {vanilla[q]}\n horizon: {horizon[q]}' + for q in QUERIES if normal(vanilla[q]) != normal(horizon[q])] + if problems: + raise AssertionError('the forced End differs:\n' + '\n'.join(problems)) + print(f'forced End: loaded and ticked with nobody in it, no exit portal, as vanilla ({vanilla[QUERIES[0]]})') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From ec81bea5bfc0270e4b597eff4d0dc2f320258874 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 16:32:02 +0100 Subject: [PATCH 034/132] Worldgen: blocks with a block entity get vanilla's default one WorldGenRegion.setBlock gives every block that has a block entity a new one, so vanilla saves the sculk sensors, catalysts and shriekers of the deep dark and potent sulfur with their block entities. Horizon only saved block entities that a structure or feature placed data for, and these kinds have none, so a Horizon-made world had none of them (3,035 sculk sensors, 753 catalysts, 329 shriekers and 21 potent sulfur over three 1,024-block seeds). A finished column now adds vanilla's defaults (block_entity_nbt::canonical) for every such block: as the modelled block entity where Horizon has one (sculk), as raw NBT otherwise. Potent sulfur gets its block entity type. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/chunks.rs | 1 + crates/horizon-client/src/vanillagen.rs | 85 ++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 122d37bcd..9ca20b894 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -66,6 +66,7 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { "sculk_catalyst" => "minecraft:sculk_catalyst", "sculk_shrieker" => "minecraft:sculk_shrieker", "crafter" => "minecraft:crafter", + "potent_sulfur" => "minecraft:potent_sulfur", "chiseled_bookshelf" => "minecraft:chiseled_bookshelf", "trial_spawner" => "minecraft:trial_spawner", "vault" => "minecraft:vault", diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 923818a08..a634d5e28 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -39,6 +39,8 @@ pub struct VanillaTerrain { tick_blocks: Vec, /// Block index -> default state id: `tick_blocks` the other way. tick_states: Vec, + /// Block state id -> the block entity type of its block, if it has one. + block_entity_types: Vec>, seed: i64, dimension: String, /// When the last proto chunk was generated, in milliseconds since @@ -51,6 +53,51 @@ enum VanillaProto { Ready(Box), Failed(i32, i32), } +/// WorldGenRegion.setBlock gives every block with a block entity a new +/// one: the blocks nothing placed data for (a sculk patch's sensors) get +/// vanilla's defaults. +fn add_default_block_entities(kinds: &[Option<&str>], out: &mut Chunk, raw: &mut Vec) { + let kind = |v: u32| kinds.get(v as usize).copied().flatten(); + let mut states = [0u32; 4096]; + for (si, section) in out.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| kind(v).is_some()) { + continue; + } + section.unpack(&mut states); + for (i, &v) in states.iter().enumerate() { + let Some(id) = kind(v) else { + continue; + }; + let i = i as i32; + let pos = [ + out.x * 16 + (i & 15), + MIN_Y + si as i32 * 16 + (i >> 8), + out.z * 16 + ((i >> 4) & 15), + ]; + let at = |t: &Tag| { + ["x", "y", "z"] + .iter() + .zip(pos) + .all(|(k, p)| t.get(k) == Some(&Tag::Int(p))) + }; + if raw.iter().any(at) || out.block_entities.iter().any(|(p, _)| *p == pos.into()) { + continue; + } + let tag = Tag::compound([ + ("id", Tag::String(id.into())), + ("x", Tag::Int(pos[0])), + ("y", Tag::Int(pos[1])), + ("z", Tag::Int(pos[2])), + ]); + let tag = crate::block_entity_nbt::canonical(&tag).unwrap_or(tag); + match crate::save::decode_block_entity(&tag) { + Some(modelled) => out.block_entities.push(modelled), + None => raw.push(tag), + } + } + } +} + impl VanillaTerrain { fn client_surface(&self, surface: SurfaceSample) -> crate::lod::Surface { crate::lod::Surface { @@ -119,6 +166,7 @@ impl VanillaTerrain { } let mut tick_blocks = Vec::with_capacity(registry.len()); let mut tick_states = Vec::new(); + let mut block_entity_types = Vec::with_capacity(registry.len()); let mut last: Option<&str> = None; let mut index = 0u32; for id in 0..registry.len() { @@ -133,6 +181,7 @@ impl VanillaTerrain { } last = Some(name); tick_blocks.push(index); + block_entity_types.push(crate::lan::chunks::block_entity_type(name)); } Ok(Self { generator, @@ -141,6 +190,7 @@ impl VanillaTerrain { query: std::sync::Mutex::new(None), tick_blocks, tick_states, + block_entity_types, seed, dimension: dimension.to_owned(), last_proto: std::sync::atomic::AtomicU64::new(0), @@ -553,7 +603,7 @@ impl ChunkGenerator for VanillaTerrain { // The block entities Horizon does not model (decorated pots with their // sherds and loot table, brushable blocks) stay as placed, like a // loaded chunk's. - let unmodelled: Vec = chunk + let mut unmodelled: Vec = chunk .block_entities .iter() .filter(|(pos, _)| { @@ -573,6 +623,7 @@ impl ChunkGenerator for VanillaTerrain { Some(Tag::Compound(nbt)) }) .collect(); + add_default_block_entities(&self.block_entity_types, &mut out, &mut unmodelled); if !unmodelled.is_empty() || !rolled_loot.is_empty() { let mut extras = out .saved @@ -596,3 +647,35 @@ impl ChunkGenerator for VanillaTerrain { out } } + +#[cfg(test)] +mod default_block_entity_tests { + use super::*; + + #[test] + fn generated_blocks_get_their_block_entities() { + let mut out = Chunk::empty(-2, 3); + out.set(4, -40, 9, 7); + out.set(5, -40, 9, 6); + let mut kinds = vec![None; 8]; + kinds[6] = Some("minecraft:potent_sulfur"); + kinds[7] = Some("minecraft:sculk_sensor"); + let mut raw = vec![]; + add_default_block_entities(&kinds, &mut out, &mut raw); + assert!(matches!( + out.block_entities[..], + [((-28, -40, 57), crate::containers::BlockEntity::Sculk(_))] + )); + assert_eq!(raw.len(), 1); + assert_eq!( + raw[0].get("id"), + Some(&Tag::String("minecraft:potent_sulfur".into())) + ); + add_default_block_entities(&kinds, &mut out, &mut raw); + assert_eq!( + (out.block_entities.len(), raw.len()), + (1, 1), + "a placed block entity is kept, not doubled" + ); + } +} From 61df807b33290aa01e0bebb928ea7449252213df Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 13:41:57 +0100 Subject: [PATCH 035/132] Structures: a chunk saves its starts also when no piece reaches it A chunk's STRUCTURE_STARTS are the starts made in it (StructureManager.getAllStarts), whether or not one of their pieces reaches it. own_starts filtered the chunk's references, which only hold starts with a piece in the chunk, so a start whose pieces all lie next door (seed 8675309's giant ruined portal in chunk -26, 23) was not saved. The proto chunk now keeps the starts made at its position. Co-Authored-By: Claude Opus 5.5 --- .../horizon-world/src/worldgen/generator.rs | 49 ++++++++++++++----- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7a38608be..8630a4ef8 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -23,6 +23,7 @@ use super::{ climate::{ClimateSampler, decode_parameter, quantize}, decode_noise, density::DensityRegistry, + generator_structures::Starts, material_condition::{ MaterialConditionRegistry, MaterialConditions, MaterialDensitySources, MaterialRule, MaterialRuleError, MaterialRuleLibrary, MaterialSurfaceQueries, @@ -567,6 +568,9 @@ pub struct ProtoChunk { pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, /// Structure starts referencing this chunk (STRUCTURE_REFERENCES). pub(super) structure_starts: Vec>, + /// The starts made in this chunk (STRUCTURE_STARTS), also those none of + /// whose pieces reach it (a giant ruined portal next door). + own_starts: Starts, /// Entities placed by structures (`ProtoChunk.addEntity`), as NBT with /// absolute `Pos`. pub entities: Vec, @@ -620,12 +624,7 @@ impl ProtoChunk { } /// The structure starts this chunk holds itself (`structures.starts`). pub fn own_starts(&self) -> Vec> { - let pos = self.position(); - self.structure_starts - .iter() - .filter(|s| s.chunk == pos) - .cloned() - .collect() + self.own_starts.to_vec() } /// Also restores a saved proto chunk that was decorated before it was saved. pub fn set_decorated(&mut self) { @@ -1114,16 +1113,19 @@ where ) .map_err(stage("noise"))?; chunk.set_generation_stage(PreLightChunkStage::Biomes); - let references = match &self.structures { - Some(structures) => structures.references( - &mut StructureQueries { + let (references, own_starts) = match &self.structures { + Some(structures) => { + let mut queries = StructureQueries { pipeline: self, worker, valid: BTreeSet::new(), - }, - pos, - ), - None => Vec::new(), + }; + ( + structures.references(&mut queries, pos), + structures.starts_at(&mut queries, pos), + ) + } + None => (Vec::new(), Starts::default()), }; if let Some(beard) = self .structures @@ -1259,6 +1261,7 @@ where decorated: false, block_entities: Vec::new(), structure_starts: references, + own_starts, entities: Vec::new(), }) } @@ -2975,6 +2978,26 @@ mod tests { } } + /// Seed 8675309's giant ruined portal starts in chunk (-26, 23) and lies + /// wholly in (-26, 24): its own chunk still holds the start, as vanilla's + /// getAllStarts does, though no piece reaches it. + #[test] + fn a_chunk_holds_its_starts_whose_pieces_lie_elsewhere() { + let Some(data) = prepared_data() else { + return; + }; + let generator = OverworldGenerator::new(data, 8675309).expect("generator"); + let mut worker = generator.worker(); + let proto = worker + .generate_proto(ChunkPos::new(-26, 23)) + .expect("proto"); + let own: Vec<_> = proto.own_starts().iter().map(|s| s.name.clone()).collect(); + assert!( + own.iter().any(|n| n == "minecraft:ruined_portal_mountain"), + "{own:?}" + ); + } + /// Chunks no ring search can end near are decided without the rings, /// which stay unsearched, and get the starts they get with them. #[test] From b28b4991359b3111ac2249d0c3b9b6276684cc66 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:41:35 +0100 Subject: [PATCH 036/132] mods: recipes.give hands out one stack at most As the creative inventory does: a count over the item's stack size (64, 16 or 1) is cut to it, so a mod can ask for a full stack without knowing it. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mod_recipes.rs | 8 ++++++-- crates/horizon-mod-sdk/wit/horizon.wit | 3 ++- docs/api/mods-reference.md | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/mod_recipes.rs b/crates/horizon-client/src/game/mod_recipes.rs index 0f65b0b42..b97944e39 100644 --- a/crates/horizon-client/src/game/mod_recipes.rs +++ b/crates/horizon-client/src/game/mod_recipes.rs @@ -74,7 +74,10 @@ impl Game<'_> { /// creative inventory; a server hears it as `SetCreativeModeSlot` /// through the inventory's sync, and refuses it unless creative. pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) { - if !self.creative || self.res.items().get(item).is_none() { + let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else { + return; + }; + if !self.creative { return; } let (damage, extra) = horizon_client::item_data::command_components(components) @@ -83,7 +86,8 @@ impl Game<'_> { }); let _ = self.give(ItemStack { item: item.into(), - count, + // One stack at most, as the creative inventory hands out. + count: count.min(max), damage, extra, }); diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 3edc44872..1c1431273 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -516,7 +516,8 @@ interface recipes { place: func(book-id: s32, all: bool) -> result<_, string>; /// Creative mode only: gives the player the stack, as taking it from /// the creative inventory does (`ServerboundSetCreativeModeSlot`): the - /// selected slot first, then the hotbar, then the inventory. + /// selected slot first, then the hotbar, then the inventory. The count + /// is cut to one stack of the item (64, 16 or 1). give: func(stack: stack) -> result<_, string>; } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index ed8d8d4ad..6416245ad 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -531,7 +531,7 @@ The station a recipe is made at. | `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. | | `place` | `func(book-id: s32, all: bool) -> result<_, string>` | Places a recipe in the open screen's grid as a click in the recipe book does (`ServerboundPlaceRecipePacket`): the inventory's grid or a crafting table. `all` places as many as the items allow, as with Shift. Refused while no such screen is open, for a recipe the player's book doesn't hold and for one that can't be placed; one missing items shows as a ghost in the grid, as in the book. | -| `give` | `func(stack: stack) -> result<_, string>` | Creative mode only: gives the player the stack, as taking it from the creative inventory does (`ServerboundSetCreativeModeSlot`): the selected slot first, then the hotbar, then the inventory. | +| `give` | `func(stack: stack) -> result<_, string>` | Creative mode only: gives the player the stack, as taking it from the creative inventory does (`ServerboundSetCreativeModeSlot`): the selected slot first, then the hotbar, then the inventory. The count is cut to one stack of the item (64, 16 or 1). | ## `browser` From 818b377c02105e8662225a8ec7072867834ed9ef Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:54:32 +0100 Subject: [PATCH 037/132] Add honey drips, poplar and azalea leaves, falling dust and campfire food smoke --- crates/horizon-client/src/animate_tick.rs | 148 ++++++++++++++++-- crates/horizon-client/src/game/render_tick.rs | 5 + 2 files changed, 142 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 28b28544b..0e0a3319b 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -35,8 +35,9 @@ enum Animate { Campfire { spawn_particles: bool, }, - /// Leaves: optional falling-leaf particle and chance, tinted by foliage. - Leaves(Option<(T, f32)>), + /// Leaves: optional falling-leaf particle and chance; a tinted leaf takes + /// the biome foliage colour unless a fixed colour is given (azalea). + Leaves(Option<(T, f32)>, Option), NetherPortal, EnchantingTable, EndRod([i32; 3]), @@ -49,6 +50,8 @@ enum Animate { EnderChest, /// FallingBlock with its dust colour. Falling(u32), + /// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`). + Beehive, RedstoneOre, RedstoneWire { power: u8, @@ -104,10 +107,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { spawn_particles: false, }, "oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" - | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))), - "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))), - "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))), - "spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None), + | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None), + "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None), + "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None), + "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None), + "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None), + "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None), + // The azalea blocks drop tinted leaves of the fixed colour -9399763. + "azalea_leaves" | "flowering_azalea_leaves" => { + Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D)) + } + "spruce_leaves" => Animate::Leaves(None, None), "nether_portal" => Animate::NetherPortal, "enchanting_table" => Animate::EnchantingTable, "end_rod" => Animate::EndRod(facing()), @@ -119,6 +129,14 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "sand" => Animate::Falling(0xDBD3A0), "red_sand" => Animate::Falling(0xA95821), "gravel" => Animate::Falling(0x807C7B), + // AnvilBlock/ConcretePowderBlock.getDustColor is the map colour; + // DragonEggBlock's is black. + "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7), + "dragon_egg" => Animate::Falling(0x000000), + _ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color( + name.trim_end_matches("_concrete_powder"), + )), + "beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive, "redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre, "redstone_wire" => { let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0); @@ -161,6 +179,27 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { _ => Animate::None, } } +/// `DyeColor.getMapColor` of a concrete powder colour. +fn concrete_powder_color(dye: &str) -> u32 { + match dye { + "white" => 0xFFFFFF, + "orange" => 0xD87F33, + "magenta" => 0xB24CD8, + "light_blue" => 0x6699D8, + "yellow" => 0xE5E533, + "lime" => 0x7FCC19, + "pink" => 0xF27FA5, + "gray" => 0x4C4C4C, + "light_gray" => 0x999999, + "cyan" => 0x4C7F99, + "purple" => 0x7F3FB2, + "blue" => 0x334CB2, + "brown" => 0x664C33, + "green" => 0x667F33, + "red" => 0x993333, + _ => 0x191919, + } +} /// `RedstoneWireBlock.COLORS`. fn redstone_color(power: u8) -> [f32; 3] { let f = f32::from(power) / 15.0; @@ -504,6 +543,53 @@ fn try_spawn_drip( } } } +/// `BeehiveBlock.trySpawnDripParticles`. +fn beehive_drip( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + if ctx.facts.get(state).fluid != Fluid::None || engine.random().next_float() < 0.3 { + return; + } + let Some((bottom, top, bounds)) = ctx.shape_y(pos) else { + return; + }; + if top < 1.0 + || tables + .impermeable + .get(state.0 as usize) + .copied() + .unwrap_or(false) + { + return; + } + let y = if bottom > 0.0 { + f64::from(pos[1]) + bottom - 0.05 + } else { + let below = [pos[0], pos[1] - 1, pos[2]]; + let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1); + // `belowTop < 1 || !isCollisionShapeFullBlock` and no fluid below. + if (below_top < 1.0 || !ctx.sturdy(below)) + && ctx.facts.get(ctx.state(below)).fluid == Fluid::None + { + f64::from(pos[1]) - 0.05 + } else { + return; + } + }; + let r = engine.random(); + let (a, b) = (r.next_double(), r.next_double()); + let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2])); + let p = [ + fx + bounds[0] + (bounds[1] - bounds[0]) * a, + y, + fz + bounds[2] + (bounds[3] - bounds[2]) * b, + ]; + add(engine, T::DrippingHoney, p, [0.0; 3]); +} /// `WaterFluid.animateTick` / `LavaFluid.animateTick`. fn fluid_animate_tick( engine: &mut ParticleEngine, @@ -685,7 +771,7 @@ fn block_animate_tick( } } } - Animate::Leaves(falling) => { + Animate::Leaves(falling, fixed_tint) => { let below = [pos[0], pos[1] - 1, pos[2]]; // LeavesBlock.makeDrippingWaterParticles. if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1 @@ -705,7 +791,7 @@ fn block_animate_tick( let r = engine.random(); let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()]; let options = if ty == T::TintedLeaves { - let c = ctx.foliage(pos); + let c = fixed_tint.unwrap_or_else(|| ctx.foliage(pos)); let f = |s: u32| ((c >> s) & 255) as f32 / 255.0; ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0]) } else { @@ -977,6 +1063,13 @@ fn block_animate_tick( } } } + Animate::Beehive => { + // BeehiveBlock.animateTick: nextInt(1) + 1 attempts. + let attempts = next_int(engine.random(), 1) + 1; + for _ in 0..attempts { + beehive_drip(tables, engine, ctx, state, pos); + } + } Animate::RedstoneOre => { for d in [ [0, -1, 0], @@ -1209,21 +1302,32 @@ fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { } add(engine, T::SmallFlame, p, [0.0; 3]); } -/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items). +/// `CampfireBlockEntity.particleTick` for every lit campfire; `cooking` says +/// which of a campfire's four slots hold an item. pub fn campfire_particles<'a>( tables: &AnimateTables, engine: &mut ParticleEngine, ctx: &AnimateContext, blocks: impl Iterator, + cooking: &dyn Fn([i32; 3]) -> [bool; 4], ) { for &(pos, state) in blocks { if !tables.is_lit_campfire(state) { continue; } - let signal = ctx + let properties = ctx .registry .state(BlockStateId(state)) - .is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true")); + .map(|s| &s.properties); + let prop = |k: &str| properties.and_then(|p| p.get(k)).map(String::as_str); + let signal = prop("signal_fire") == Some("true"); + // Direction.get2DDataValue: south, west, north, east. + let rotation = match prop("facing") { + Some("west") => 1, + Some("north") => 2, + Some("east") => 3, + _ => 0, + }; let r = engine.random(); if r.next_float() < 0.11 { let count = next_int(r, 2) + 2; @@ -1231,6 +1335,28 @@ pub fn campfire_particles<'a>( make_campfire_smoke(engine, pos, signal, false); } } + // The smoke over each cooking item, at the slot's corner of the fire. + let occupied = cooking(pos); + for (slot, _) in occupied.iter().enumerate().filter(|(_, held)| **held) { + if engine.random().next_float() >= 0.2 { + continue; + } + // Direction.from2DDataValue((slot + rotation) % 4) and its clockwise side. + let (step, clockwise) = match (slot + rotation) % 4 { + 0 => ([0.0, 1.0], [-1.0, 0.0]), + 1 => ([-1.0, 0.0], [0.0, -1.0]), + 2 => ([0.0, -1.0], [1.0, 0.0]), + _ => ([1.0, 0.0], [0.0, 1.0]), + }; + let at = [ + f64::from(pos[0]) + 0.5 - step[0] * 0.3125 + clockwise[0] * 0.3125, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5 - step[1] * 0.3125 + clockwise[1] * 0.3125, + ]; + for _ in 0..4 { + add(engine, T::Smoke, at, [0.0, 5.0e-4, 0.0]); + } + } } } /// `CampfireBlock.makeParticles` (always visible, overriding the limiter); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..3f5862f49 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -7,6 +7,7 @@ use horizon_client::{ biome::Biomes, blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, + containers::BlockEntity, particles::{ParticleLevel, ParticleOptions, ParticleType}, world::World, }; @@ -344,6 +345,10 @@ impl Game<'_> { &mut self.particles, &ctx, r.block_entities(), + &|pos| match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { + Some(BlockEntity::Campfire(c)) => c.items.each_ref().map(Option::is_some), + _ => [false; 4], + }, ); } let level = ParticleLevel { From 7112d0cd6498c6e16020230a2868e8f0d0ba4e3f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:55:27 +0100 Subject: [PATCH 038/132] Mobs standing in a wither rose get wither, bees in an open eyeblossom get poison --- crates/horizon-client/src/mobs/ai.rs | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..189625541 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -413,6 +413,7 @@ pub fn tick( super::axolotl::tick_animation(m); m.anim.end_tick(m.ai.swinging); tick_swing(m); + flower_contact_effects(m, w); if m.species() == Species::CopperGolem { // CopperGolem.tick: updateWeathering after the living tick. super::copper_golem::update_weathering(m, w, level_random, events); @@ -1464,6 +1465,56 @@ pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec = Vec::new(); + for at in [m.previous, m.position] { + let cells = |lo: f64, hi: f64| lo.floor() as i32..=hi.floor() as i32; + for x in cells(at.x - half, at.x + half) { + for y in cells(at.y + 1.0e-5, at.y + height) { + for z in cells(at.z - half, at.z + half) { + let p = [x, y, z]; + if visited.contains(&p) { + continue; + } + match w.block_name(x, y, z) { + "minecraft:wither_rose" => { + // isInvulnerableTo(wither): the invulnerable time + // after a hit; WitherBoss and WitherSkeleton + // refuse the effect (`canBeAffected`). + if m.invulnerable <= 0 + && !m.invulnerable_flag + && !matches!(m.species(), Species::Wither | Species::WitherSkeleton) + { + m.add_effect("minecraft:wither", 40, 0); + } + } + "minecraft:open_eyeblossom" + if m.species() == Species::Bee + && super::bee::attracts_bees(w, p) + && !m.has_effect("minecraft:poison") => + { + m.add_effect("minecraft:poison", 25, 0); + } + _ => continue, + } + visited.push(p); + } + } + } + } +} + /// MobEffect ticking for the effects mobs receive (poison, wither, regeneration). fn tick_effects(m: &mut Mob) { let mut effects = std::mem::take(&mut m.extra.effects); From 4ebfaef0d3976c2e003acddeded25c891028d1d4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:56:07 +0100 Subject: [PATCH 039/132] Slide slowly down the sides of honey blocks --- crates/horizon-client/src/game.rs | 26 +++++++++++++++ crates/horizon-client/src/motion.rs | 51 +++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index de7eb448b..ab63124d6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4544,6 +4544,32 @@ impl Game<'_> { MotionEvent::Fall(event) => self.landing_block_updates(&event), MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), + MotionEvent::HoneySlide { + pos, + sound, + particles, + } => { + if sound { + self.audio + .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); + } + // HoneyBlock.showSlideParticles: five block particles. + if particles + && let Some((sprite, tint)) = self.particle_sprite( + self.world.block(pos.x, pos.y, pos.z), + [pos.x, pos.y, pos.z], + ) + { + use horizon_client::particles::{ParticleOptions, ParticleType}; + for _ in 0..5 { + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite.clone(), tint), + feet, + [0.0; 3], + ); + } + } + } MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos), MotionEvent::CauldronExtinguish { pos } => self.cauldron_extinguish(pos), MotionEvent::InsideWitherRose => self.wither_rose_contact(), diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index fcdd32cbd..04341b66f 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -203,6 +203,14 @@ pub enum MotionEvent { bubble: bool, position: Vec3, }, + /// `HoneyBlock.maybeDoSlideEffects` for a player sliding down the side of + /// the honey block at `pos`: its slide sound, and the client's five + /// block particles (entity event 53) at the player. + HoneySlide { + pos: BlockPos, + sound: bool, + particles: bool, + }, /// Entity event 67 (`LivingEntity.makeDrownParticles`): eight bubbles /// around a drowning player. Drown, @@ -1386,6 +1394,7 @@ impl MotionWorld<'_, '_, '_> { entered.push((step, p)); } "minecraft:cobweb" => self.web_inside(), + "minecraft:honey_block" => self.honey_block_inside(p)?, "minecraft:sweet_berry_bush" => self.sweet_berry_bush_inside(state)?, "minecraft:bubble_column" => { let precise = moved_far || deflated.intersects(Aabb::block(p)); @@ -1403,6 +1412,48 @@ impl MotionWorld<'_, '_, '_> { } Ok(iterations + 1) } + /// `HoneyBlock.entityInside`: a falling player touching a side of the block + /// slides down it (`isSlidingDown`, `doSlideMovement`, `maybeDoSlideEffects`). + fn honey_block_inside(&mut self, pos: BlockPos) -> Result<()> { + let old_delta_y = |dy: f64| dy / f64::from(0.98_f32) + 0.08; + let new_delta_y = |dy: f64| (dy - 0.08) * f64::from(0.98_f32); + let position = self.player.position; + let velocity = self.player.velocity; + if self.player.ground.on_ground + || position.y > f64::from(pos.y) + 0.9375 - 1.0e-7 + || old_delta_y(velocity.y) >= -0.08 + { + return Ok(()); + } + let dx = (f64::from(pos.x) + 0.5 - position.x).abs(); + let dz = (f64::from(pos.z) + 0.5 - position.z).abs(); + let overlap = 0.4375 + f64::from(self.player.dimensions.width / 2.0); + if !(dx + 1.0e-7 > overlap || dz + 1.0e-7 > overlap) { + return Ok(()); + } + // doSlideMovement + let old = old_delta_y(velocity.y); + if old < -0.13 { + let factor = -0.05 / old; + self.player.velocity = + Vec3::new(velocity.x * factor, new_delta_y(-0.05), velocity.z * factor); + } else { + self.player.velocity = Vec3::new(velocity.x, new_delta_y(-0.05), velocity.z); + } + self.player.fall_distance = 0.0; + // maybeDoSlideEffects: the sound, then the server's event 53. + let random = &mut self.scene.random; + let sound = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + let particles = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + if sound || particles { + self.player.events.push(MotionEvent::HoneySlide { + pos, + sound, + particles, + }); + } + Ok(()) + } /// `Player.makeStuckInBlock`: the next move is scaled by `multiplier` /// (and the fall forgotten) unless flying; the impulse context resets /// either way. From e7e6e5bc07556c8c4e15fcda5768517007001e59 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:56:22 +0100 Subject: [PATCH 040/132] Scale entity tracking range by entity-broadcast-range-percentage The property was parsed and ignored. The tracking range of each entity type is now scaled by it on a dedicated server, like DedicatedServer.getScaledTrackingDistance. --- crates/horizon-client/src/game/dedicated.rs | 3 +++ crates/horizon-client/src/lan/entity.rs | 14 ++++++++++---- crates/horizon-client/src/lan/hub.rs | 4 ++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..49b653ae1 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -654,6 +654,9 @@ impl Game<'_> { // DedicatedServer.initServer ends with saveEverything(false, true, true). self.save_game()?; self.log_saved_levels(); + if let Some(host) = self.lan.as_mut() { + host.hub.entity_range_percent = props.entity_broadcast_range_percentage; + } let mut state = ServerState { lists, console, diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index ae3089006..920052b5a 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -611,8 +611,9 @@ pub struct Viewer<'a> { } /// One entity as this tick's range checks read it: where it is -/// horizontally, its id, its type's tracking range in chunks and the chunk -/// it is in (an index into the tick's chunks). +/// horizontally, its id, its tracking range in blocks (scaled by +/// `entity-broadcast-range-percentage`) and the chunk it is in (an index +/// into the tick's chunks). #[derive(Clone, Copy)] struct Probe { x: f64, @@ -627,7 +628,7 @@ struct Probe { /// each of the tick's chunks whether the client has it (0: not looked up /// yet, 1: no, 2: yes), so each chunk is looked up once per client. fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { - let range = f64::from(p.range.min(v.view_distance) * 16); + let range = f64::from(p.range.min(v.view_distance * 16)); let (dx, dz) = (v.position[0] - p.x, v.position[2] - p.z); dx * dx + dz * dz <= range * range && { let held = &mut held[p.chunk as usize]; @@ -641,6 +642,9 @@ fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { /// One level's tracked entities (ChunkMap.entityMap). #[derive(Default)] pub struct Entities { + /// `entity-broadcast-range-percentage` (None: 100), which scales every + /// type's tracking range (MinecraftServer.getScaledTrackingDistance). + pub range_percent: Option, states: crate::fast_hash::FxHashMap, /// The level tick, stamped on every entity still in the level. tick: u32, @@ -732,7 +736,9 @@ impl Entities { x: e.position[0], z: e.position[2], id: e.id, - range: s.range, + range: self + .range_percent + .map_or(s.range * 16, |p| p * (s.range * 16) / 100), chunk, }); } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..ac0530d86 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -168,6 +168,8 @@ pub struct Hub { level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, + /// `entity-broadcast-range-percentage` (dedicated servers). + pub entity_range_percent: i32, chat_type: i32, dimension_type: i32, clock_ids: Vec, @@ -332,6 +334,7 @@ impl Hub { ticking: (20.0, false), stepping: 0, ops: Default::default(), + entity_range_percent: 100, weather: (false, 0.0, 0.0), level_sync: Default::default(), chat_type, @@ -1678,6 +1681,7 @@ impl Hub { out, }) .collect(); + level.range_percent = Some(self.entity_range_percent); let (types, sync) = (&mut self.entity_types, &self.sync); level.tick(&entities, &self.riding, &mut viewers, |kind| { entity_type(types, sync, kind) From 5a70691d63980600cd6de1fc03b6ad0c03c02e60 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:56:39 +0100 Subject: [PATCH 041/132] Show the note particle above a note block when it plays --- crates/horizon-client/src/game.rs | 25 ++++++++++++++++++++++ crates/horizon-world/src/level/redstone.rs | 9 +++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index de7eb448b..118256915 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3085,6 +3085,31 @@ impl Game<'_> { LevelEvent::BlockEntityEvent { pos, a, b, .. } => { self.block_entity_event([pos.x, pos.y, pos.z], a, b) } + // NoteBlock.triggerEvent: a NOTE particle above, coloured by + // the note (`note / 24.0` in the x speed). + LevelEvent::BlockEvent { + pos, + state, + kind: "note_particle", + } => { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let note = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("note")?.parse::().ok()) + .unwrap_or(0.0); + self.particles.add( + &ParticleOptions::simple(ParticleType::Note), + [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.2, + f64::from(pos.z) + 0.5, + ], + [note / 24.0, 0.0, 0.0], + ); + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } => {} diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index a2a02081f..3965a57a2 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -1108,7 +1108,8 @@ impl Sim<'_, L> { self.game_event(pos, "minecraft:note_block_play"); } } - /// `NoteBlock.triggerEvent`: the note's sound. + /// `NoteBlock.triggerEvent`: the note's particle (tunable instruments) + /// and sound. pub(crate) fn note_trigger_event(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let instrument = b.table.text(state, b.props.instrument).to_owned(); @@ -1120,6 +1121,12 @@ impl Sim<'_, L> { let pitch = if mob_head { 1.0 } else { + // `isTunable`: the client adds the NOTE particle above the block. + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "note_particle", + }); horizon_core::jmath::pow(2.0, f64::from(note - 12) / 12.0) as f32 }; let sound = match instrument.as_str() { From dbd24e2e16534cbdadb9cd56118d987d25b0ec07 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:57:02 +0100 Subject: [PATCH 042/132] A creaking heart blown up by an explosion makes its creaking die --- crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/game/creaking.rs | 7 ++++--- crates/horizon-client/src/game/explosion.rs | 5 +++++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a51bdcbcb..0ebf5bfaf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3493,7 +3493,7 @@ impl Game<'_> { } else if let Some(tag) = spill::saved_entity(&self.world, pos) { self.pending.record_saved(pos, &tag); } - self.creaking_heart_broken(pos); + self.creaking_heart_broken(pos, true); let hive = match self.world.block_entities.get(&key) { Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)), _ => None, diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index c75325c2f..19b3442c2 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -218,8 +218,9 @@ impl Game<'_> { ); } /// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to - /// death and a natural heart drops experience. - pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { + /// death and a natural heart drops experience. `onExplosionHit` does the + /// same for the creaking (`by_player` false), without the experience. + pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3], by_player: bool) { let key = (pos[0], pos[1], pos[2]); if !matches!( self.world.block_entities.get(&key), @@ -242,7 +243,7 @@ impl Game<'_> { .state(state) .and_then(|s| s.properties.get("natural").cloned()) .is_some_and(|v| v == "true"); - if natural && !self.creative && !self.spectator() { + if by_player && natural && !self.creative && !self.spectator() { let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; self.spawn_orbs( [ diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 8800e29d8..886310d91 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -599,6 +599,11 @@ impl Game<'_> { } let name = self.res.facts().get(state).name.clone(); let is_tnt = &*name == "minecraft:tnt"; + // CreakingHeartBlock.onExplosionHit: its creaking dies (no + // experience, as Horizon does not track a TNT's owner). + if &*name == "minecraft:creaking_heart" { + self.creaking_heart_broken(pos, false); + } // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. let key = (pos[0], pos[1], pos[2]); From 9e848670dbb543e2e0338b0290804390fd6cd577 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:57:11 +0100 Subject: [PATCH 043/132] Send swimming, gliding, fire, invisible and glowing for LAN players --- crates/horizon-client/src/game/lan.rs | 11 +++- crates/horizon-client/src/lan/hub.rs | 77 ++++++++++++++++++++++---- crates/horizon-client/tests/lan_bot.rs | 1 + 3 files changed, 78 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..4ccbb0ec8 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -11,7 +11,7 @@ use horizon_client::{ chunks::ChunkEncoder, data::SyncData, entity::{EntityState, States}, - hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, + hub::{BodyFlags, HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, mobs::{Mob, Who, leash::Holder}, @@ -835,6 +835,15 @@ impl Game<'_> { living_flags: living_flags(self.using) | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, bed: self.sleeping, + body: BodyFlags { + gliding: p.fall_flying, + swimming: p.swimming, + crawling: p.pose == horizon_client::pose::Pose::Swimming && !p.swimming, + spin_attack: p.auto_spin_attack_ticks > 0, + on_fire: p.fire_ticks > 0, + invisible: self.potions.effects.get("invisibility").is_some(), + glowing: self.potions.effects.get("glowing").is_some(), + }, }) } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..c3a18ee86 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -87,6 +87,27 @@ pub struct HostState { pub living_flags: i8, /// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`). pub bed: Option<[i32; 3]>, + pub body: BodyFlags, +} + +/// What the other players see of a player's body besides sneaking and +/// sprinting: the pose and the rest of `Entity.DATA_SHARED_FLAGS_ID`. +#[derive(Clone, Copy, Debug, Default)] +pub struct BodyFlags { + /// `Entity.isFallFlying`: gliding with elytra. + pub gliding: bool, + /// `Entity.isSwimming` (the swimming flag). + pub swimming: bool, + /// The swimming pose of a player crawling under a block. + pub crawling: bool, + /// `LivingEntity.isAutoSpinAttack`: Riptide's spin. + pub spin_attack: bool, + /// `Entity.isOnFire`. + pub on_fire: bool, + /// `Entity.isInvisible`: the invisibility effect. + pub invisible: bool, + /// The glowing effect. + pub glowing: bool, } /// Everything the hub needs from the game for one tick. @@ -1507,7 +1528,8 @@ impl Hub { position: [f64; 3], rot: (f32, f32, f32), on_ground: bool, - flags: (bool, bool, bool, bool), + flags: (bool, bool, bool), + body: BodyFlags, living_flags: i8, bed: Option<[i32; 3]>, skin: u8, @@ -1515,12 +1537,18 @@ impl Hub { equipment: Vec<(u8, Option)>, attributes: Vec, ) -> EntityState { - let (sneaking, sprinting, gliding, sleeping) = flags; - let shared = shared_flags(sneaking, sprinting, gliding); + let (sneaking, sprinting, sleeping) = flags; + let shared = shared_flags(sneaking, sprinting, &body); + // Player.getDesiredPose (and updatePlayerPose's crawl): sleeping, + // swimming, gliding, Riptide's spin, crouching. let pose = if sleeping { 2 - } else if gliding { + } else if body.swimming || body.crawling { + 3 + } else if body.gliding { 1 + } else if body.spin_attack { + 4 } else if sneaking { 5 } else { @@ -1607,7 +1635,8 @@ impl Hub { h.position, (h.yaw, h.pitch, h.head_yaw), h.on_ground, - (h.sneaking, h.sprinting, false, h.bed.is_some()), + (h.sneaking, h.sprinting, h.bed.is_some()), + h.body, h.living_flags, h.bed, 0x7F, @@ -1639,7 +1668,8 @@ impl Hub { g.position, (g.yaw, g.pitch, g.head_yaw), g.on_ground, - (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), + (g.sneaking, g.sprinting, g.sleeping), + guest_body(g), g.living_flags, g.bed, g.info.model_customisation, @@ -1798,7 +1828,7 @@ impl Hub { // too, so the sprint a hit stops (Player.causeExtraKnockback) stops // on its client. let g = &mut self.guests[i]; - let shared = shared_flags(g.sneaking, g.sprinting, g.fall_flying); + let shared = shared_flags(g.sneaking, g.sprinting, &guest_body(g)); if shared != g.sent_shared { g.sent_shared = shared; g.send(&C::SetEntityData(play::SetEntityData { @@ -2578,16 +2608,43 @@ fn ticking_state(rate: f32, frozen: bool) -> C { raw(ids::TICKING_STATE, w.data) } -/// Entity.DATA_SHARED_FLAGS_ID of a player: crouching, sprinting, gliding. -fn shared_flags(sneaking: bool, sprinting: bool, gliding: bool) -> i8 { +/// What the others see of a guest's body, from its server-side state. +fn guest_body(g: &Guest) -> BodyFlags { + let m = g.motion.as_deref(); + BodyFlags { + gliding: g.fall_flying, + swimming: m.is_some_and(|m| m.swimming), + crawling: m.is_some_and(|m| m.pose == crate::pose::Pose::Swimming && !m.swimming), + spin_attack: m.is_some_and(|m| m.auto_spin_attack_ticks > 0), + on_fire: m.is_some_and(|m| m.fire_ticks > 0), + invisible: g.effects.get("invisibility").is_some(), + glowing: g.effects.get("glowing").is_some(), + } +} + +/// Entity.DATA_SHARED_FLAGS_ID of a player: on fire 0x01, crouching 0x02, +/// sprinting 0x08, swimming 0x10, invisible 0x20, glowing 0x40, gliding 0x80. +fn shared_flags(sneaking: bool, sprinting: bool, body: &BodyFlags) -> i8 { let mut shared = 0i8; + if body.on_fire { + shared |= 0x01; + } if sneaking { shared |= 0x02; } if sprinting { shared |= 0x08; } - if gliding { + if body.swimming { + shared |= 0x10; + } + if body.invisible { + shared |= 0x20; + } + if body.glowing { + shared |= 0x40; + } + if body.gliding { shared |= -128; } shared diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 34e8265a1..c4ed2884b 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -186,6 +186,7 @@ impl Server { attributes: Vec::new(), bed: None, living_flags: 0, + body: Default::default(), }; let mut ctx = TickCtx { world: &mut self.world, From 00cb813dc88ff067912e574ae02c7fcbc6cd10b3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:57:18 +0100 Subject: [PATCH 044/132] Show the missing item tooltip lines in vanilla order Custom names are italic. Unbreakable, dyed, written book author and generation, music disc songs, goat horn instruments, loaded crossbow projectiles, hive bees and honey, the potion "When Applied" block and enchantment attribute modifiers (Efficiency V gives +26 Mining Efficiency) now appear, and advanced tooltips (F3+H) end with the item id and the component count. Attribute lines use the attribute's sentiment colour. --- crates/horizon-client/src/enchant.rs | 26 ++ crates/horizon-client/src/game/stations.rs | 253 +++++++++++++---- crates/horizon-client/src/item_tooltip.rs | 311 ++++++++++++++++++--- crates/horizon-client/src/items.rs | 6 + 4 files changed, 498 insertions(+), 98 deletions(-) diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 2f418ae82..73b9bf090 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -545,6 +545,32 @@ impl Enchantments { } out } + /// `EnchantmentHelper.forEachModifier` as an item's tooltip lists them: the + /// `minecraft:attributes` effects of `stack`'s enchantments as rows of + /// (attribute, id, amount, operation, slot group), one per slot group the + /// enchantment lists. + pub fn modifier_rows(&self, stack: &ItemStack) -> Vec<(String, String, f64, String, String)> { + let mut rows = Vec::new(); + for (id, level) in stack.enchantments() { + let Some(e) = self.get(id) else { continue }; + for a in e.effects["minecraft:attributes"] + .as_array() + .into_iter() + .flatten() + { + for slot in &e.slots { + rows.push(( + a["attribute"].as_str().unwrap_or("").to_owned(), + a["id"].as_str().unwrap_or("").to_owned(), + f64::from(level_value(&a["amount"], *level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + slot.clone(), + )); + } + } + } + rows + } /// Sum of `add_value` amounts of one attribute from enchantments on `stack`. pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 { stack.map_or(0.0, |s| { diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 56b19e393..686ad0c02 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -277,6 +277,10 @@ fn argb(c: i32) -> u32 { ) } +/// A text style's `0xRRGGBB` colour from a HUD colour (`rgba`). +fn rgb_of(rgba: u32) -> u32 { + (rgba & 0xFF) << 16 | (rgba >> 8 & 0xFF) << 8 | (rgba >> 16 & 0xFF) +} impl Game<'_> { /// `Component.translatable`: the selected language (which `lang` layers /// over `en_us`), the caller's English text last. @@ -1689,20 +1693,34 @@ impl Game<'_> { &self, stack: &ItemStack, ) -> Vec<(horizon_client::text::Text, u32)> { - let e: &Enchantments = &self.res.stations().enchantments; - let props = e.props(&stack.item); + self.stack_tooltip_lines(stack, false) + } + /// `ItemStack.getRarity`'s colour for the name line and a `[name]` link. + fn rarity_color(&self, stack: &ItemStack) -> u32 { + let props = self.res.stations().enchantments.props(&stack.item); let rarity = horizon_client::item_tooltip::rarity( stack, props.map_or("common", |p| p.rarity.as_str()), ); - let color = match rarity { + match rarity { "uncommon" => rgba(255, 255, 85, 255), "rare" => rgba(85, 255, 255, 255), "epic" => rgba(255, 85, 255, 255), _ => u32::MAX, - }; - let name = if let Some(n) = stack.custom_name() { + } + } + /// `ItemStack.getHoverName`: the custom name, a written book's title, the + /// item name component, else the item's or potion's name. + fn stack_hover_name(&self, stack: &ItemStack) -> String { + if let Some(n) = stack.custom_name() { n.to_owned() + } else if let Some(title) = stack + .data() + .and_then(|d| d.written.as_ref()) + .map(|w| w.title.as_str()) + .filter(|t| !t.trim().is_empty()) + { + title.to_owned() } else if let Some(n) = stack.item_name() { n } else if stack.data().is_some_and(|d| d.ominous_banner) { @@ -1718,16 +1736,47 @@ impl Game<'_> { .unwrap_or_else(|| self.pack.names.display_item(&stack.item)) } else { self.pack.names.display_item(&stack.item) - }; + } + } + /// `ItemStack.getTooltipLines`. A `nested` stack is a crossbow's + /// projectile: `ChargedProjectiles.addProjectileTooltip` takes its details + /// without the name, the player and the advanced flag. + fn stack_tooltip_lines( + &self, + stack: &ItemStack, + nested: bool, + ) -> Vec<(horizon_client::text::Text, u32)> { + let e: &Enchantments = &self.res.stations().enchantments; + let color = self.rarity_color(stack); + let advanced = !nested && self.options_advanced_tooltips(); let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack); let mut lines = Vec::new(); - if display.name_visible(self.screen == Screen::Creative) { - lines.push((horizon_client::text::Text::legacy(&name), color)); + if !nested && display.name_visible(self.screen == Screen::Creative) { + // `getStyledHoverName`: a custom name is italic. + let name = self.stack_hover_name(stack); + let name = if stack.custom_name().is_some() { + horizon_client::text::Text::literal(name).italic() + } else { + horizon_client::text::Text::legacy(&name) + }; + lines.push((name, color)); } let translate = |k: &str| self.pack.names.display_get(k); let push = |lines: &mut Vec<(horizon_client::text::Text, u32)>, s: String, c: u32| { lines.push((horizon_client::text::Text::legacy(&s), c)); }; + let gray = rgba(170, 170, 170, 255); + let item_info = self.res.items().get(&stack.item); + // InstrumentComponent.addToTooltip. + if let Some(text) = + horizon_client::item_tooltip::instrument_line(stack, &display, &translate) + { + push(&mut lines, text, gray); + } + // Bees.addToTooltip. + if let Some(text) = horizon_client::item_tooltip::bees_line(stack, &display, &translate) { + push(&mut lines, text, gray); + } // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() @@ -1742,6 +1791,70 @@ impl Game<'_> { push(&mut lines, text, u32::MAX); } } + // BannerPatternLayers.addToTooltip: up to six layer names. + if display.shows("minecraft:banner_patterns") { + for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { + let key = self.res.stations().banners.layer_key(layer); + push( + &mut lines, + self.translate(&key, &key), + rgba(170, 170, 170, 255), + ); + } + } + // WrittenBookContent.addToTooltip. + for text in horizon_client::item_tooltip::written_book_lines(stack, &display, &translate) { + push(&mut lines, text, gray); + } + // ChargedProjectiles.addToTooltip: each run of equal projectiles, then + // the projectile's own details indented under it. + if display.shows("minecraft:charged_projectiles") { + let charged = stack.data().map_or(&[][..], |d| &d.charged[..]); + for run in charged.chunk_by(|a, b| a.same_item_same_components(b)) { + let projectile = &run[0]; + let name = self.stack_hover_name(projectile); + let line = if run.len() == 1 { + // `getDisplayName`: `[name]` in the rarity colour. + let mut shown = horizon_client::text::Text::literal(format!("[{name}]")) + .with_color(rgb_of(self.rarity_color(projectile))); + if projectile.custom_name().is_some() { + shown = shown.italic(); + } + horizon_client::text::format_translation( + &self.translate( + "item.minecraft.crossbow.projectile.single", + "Projectile: %s", + ), + &[shown], + ) + } else { + horizon_client::text::format_translation( + &self.translate( + "item.minecraft.crossbow.projectile.multiple", + "Projectile: %s x %s", + ), + &[ + horizon_client::text::Text::literal(run.len().to_string()), + horizon_client::text::Text::literal(name), + ], + ) + }; + lines.push((line, u32::MAX)); + for (text, c) in self.stack_tooltip_lines(projectile, true) { + // `literal(" ").append(line).withStyle(GRAY)`: the line's + // own colours win over the gray. + let rgb = if c == u32::MAX { + horizon_client::text::GRAY + } else { + rgb_of(c) + }; + let indented = horizon_client::text::Text::literal(" ") + .append(text) + .with_color(rgb); + lines.push((indented, u32::MAX)); + } + } + } // Fireworks / FireworkExplosion.addToTooltip. for text in horizon_client::item_tooltip::firework_lines(stack, &translate) { push(&mut lines, text, rgba(170, 170, 170, 255)); @@ -1764,6 +1877,17 @@ impl Game<'_> { }; push(&mut lines, text, c); } + // The attribute modifiers of the effects (`When Applied:`). + for (text, c) in horizon_client::item_tooltip::potion_modifier_lines(stack, &translate) + { + push(&mut lines, text, c); + } + } + // JukeboxPlayable.addToTooltip. + if let Some(text) = + horizon_client::item_tooltip::jukebox_line(stack, item_info, &display, &translate) + { + push(&mut lines, text, gray); } if display.shows("minecraft:trim") && let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) @@ -1811,16 +1935,12 @@ impl Game<'_> { ); } } - // BannerPatternLayers.addToTooltip: up to six layer names. - if display.shows("minecraft:banner_patterns") { - for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { - let key = self.res.stations().banners.layer_key(layer); - push( - &mut lines, - self.translate(&key, &key), - rgba(170, 170, 170, 255), - ); - } + // DyedItemColor.addToTooltip. + if let Some((text, italic)) = + horizon_client::item_tooltip::dyed_line(stack, &display, advanced, &translate) + { + let text = horizon_client::text::Text::legacy(&text); + lines.push((if italic { text.italic() } else { text }, gray)); } // ItemLore.addToTooltip: after the enchantments, before the attributes // (ItemStack.addDetailsToTooltip). @@ -1829,6 +1949,50 @@ impl Game<'_> { lines.push((text, u32::MAX)); } } + if display.shows("minecraft:attribute_modifiers") { + // The item's own modifiers, then its enchantments' for each slot + // group (`ItemStack.forEachModifier`). + let mut modifiers = item_info.map(|i| i.modifiers.clone()).unwrap_or_default(); + modifiers.extend(e.modifier_rows(stack)); + let base = |name: &str, default| { + self.player + .as_ref() + .and_then(|player| { + let key = player.attributes.key(name)?; + let handle = player.attributes.lookup(Some(&key))?; + player + .attributes + .instance(&handle) + .ok() + .map(|value| value.base_value()) + }) + .unwrap_or(default) + }; + let player_base = (!nested).then(|| { + [ + base("minecraft:attack_damage", 1.0), + base( + "minecraft:attack_speed", + horizon_client::attack_strength::BASE_ATTACK_SPEED, + ), + ] + }); + for (text, c) in + horizon_client::item_tooltip::attribute_lines(&modifiers, player_base, &translate) + { + push(&mut lines, text, c); + } + } + // ItemStack.UNBREAKABLE_TOOLTIP. + if let Some(text) = + horizon_client::item_tooltip::unbreakable_line(stack, &display, &translate) + { + push(&mut lines, text, rgba(85, 85, 255, 255)); + } + // BlockItemStateProperties.addToTooltip. + if let Some(text) = horizon_client::item_tooltip::honey_line(stack, &display, &translate) { + push(&mut lines, text, gray); + } // Spawner.appendHoverText: what a spawner or trial spawner item spawns. if display.shows("minecraft:block_entity_data") && matches!( @@ -1852,43 +2016,11 @@ impl Game<'_> { } } } - if display.shows("minecraft:attribute_modifiers") - && let Some(info) = self.res.items().get(&stack.item) - { - let base = |name: &str, default| { - self.player - .as_ref() - .and_then(|player| { - let key = player.attributes.key(name)?; - let handle = player.attributes.lookup(Some(&key))?; - player - .attributes - .instance(&handle) - .ok() - .map(|value| value.base_value()) - }) - .unwrap_or(default) - }; - let player_base = [ - base("minecraft:attack_damage", 1.0), - base( - "minecraft:attack_speed", - horizon_client::attack_strength::BASE_ATTACK_SPEED, - ), - ]; - for (text, c) in horizon_client::item_tooltip::attribute_lines( - &info.modifiers, - Some(player_base), - &translate, - ) { - push(&mut lines, text, c); - } - } if display.shows("minecraft:damage") - && let Some(info) = self.res.items().get(&stack.item) + && let Some(info) = item_info && info.max_damage > 0 && stack.damage > 0 - && self.options_advanced_tooltips() + && advanced { push( &mut lines, @@ -1900,8 +2032,23 @@ impl Game<'_> { u32::MAX, ); } + // ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id + // and how many components the stack has. + if advanced { + let dark_gray = rgba(85, 85, 85, 255); + push(&mut lines, stack.item.to_string(), dark_gray); + let count = horizon_client::item_tooltip::component_count(stack, item_info); + if count > 0 { + let text = self.translate("item.components", "%s component(s)"); + push( + &mut lines, + text.replacen("%s", &count.to_string(), 1), + dark_gray, + ); + } + } // ItemStack.OP_NBT_WARNING, for a player with game master permission. - if self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { + if !nested && self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { for (key, fallback) in [ ("item.op_warning.line1", "Warning:"), ( diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 88f01439e..63a19b114 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -108,6 +108,32 @@ fn modifier_line( ) } +/// `Attribute.getStyle`: the colour of a line for an attribute whose value +/// rises or falls. Gravity, scale and the waypoint ranges are neutral, burning +/// time and fall damage are negative, every other attribute is positive. +fn attribute_color(attribute: &str, rises: bool) -> u32 { + let (blue, red) = (rgba(85, 85, 255, 255), rgba(255, 85, 85, 255)); + match attribute { + "burning_time" | "fall_damage_multiplier" => { + if rises { + red + } else { + blue + } + } + "gravity" | "scale" | "waypoint_transmit_range" | "waypoint_receive_range" => { + rgba(170, 170, 170, 255) + } + _ => { + if rises { + blue + } else { + red + } + } + } +} + /// `ItemStack.addAttributeTooltips`: slot groups, colors and optional player /// attack damage/speed bases. Recipe search has no player context. pub fn attribute_lines( @@ -150,10 +176,8 @@ pub fn attribute_lines( ) { let (line, color) = if base.is_some() { (format!(" {line}"), rgba(0, 170, 0, 255)) - } else if *amount > 0.0 { - (line, rgba(85, 85, 255, 255)) } else { - (line, rgba(255, 85, 85, 255)) + (line, attribute_color(path, *amount > 0.0)) }; lines.push((line, color)); } @@ -231,6 +255,235 @@ pub fn rarity<'a>(stack: &ItemStack, default: &'a str) -> &'a str { } } +fn is_beehive(path: &str) -> bool { + matches!(path, "beehive" | "bee_nest") +} + +/// `InstrumentComponent.addToTooltip`: the instrument's description. A goat +/// horn without the component has the item's default, the ponder horn. +pub fn instrument_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:instrument") { + return None; + } + let id = match stack.data().and_then(|d| d.other("minecraft:instrument")) { + Some(Tag::String(id)) => id.to_string_lossy(), + // An inline instrument carries its own description. + Some(inline) => { + return inline + .get("description") + .map(|d| crate::entity_nbt::name_text(d).plain()); + } + None if &*stack.item == "minecraft:goat_horn" => "minecraft:ponder_goat_horn".to_owned(), + None => return None, + }; + let key = format!("instrument.{}", id.replacen(':', ".", 1)); + Some(translate(&key).unwrap_or(key)) +} + +/// `Bees.addToTooltip`: how many bees a hive item holds (a hive item without +/// the component has the item's default, none). +pub fn bees_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:bees") { + return None; + } + let bees = match stack.data().and_then(|d| d.other("minecraft:bees")) { + Some(Tag::List(bees)) => bees.len(), + Some(_) => return None, + None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0, + None => return None, + }; + let text = + translate("container.beehive.bees").unwrap_or_else(|| "container.beehive.bees".into()); + Some( + text.replacen("%s", &bees.to_string(), 1) + .replacen("%s", "3", 1), + ) +} + +/// `BlockItemStateProperties.addToTooltip`: a hive item's honey level (a hive +/// item without the component has the item's default, 0). +pub fn honey_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:block_state") { + return None; + } + let level = match stack.data().and_then(|d| d.other("minecraft:block_state")) { + Some(Tag::Compound(state)) => { + match state.get(&horizon_world::nbt::JavaString::from("honey_level")) { + Some(Tag::String(level)) => level.to_string_lossy().parse::().ok()?, + _ => return None, + } + } + Some(_) => return None, + None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0, + None => return None, + }; + let text = + translate("container.beehive.honey").unwrap_or_else(|| "container.beehive.honey".into()); + Some( + text.replacen("%s", &level.to_string(), 1) + .replacen("%s", "5", 1), + ) +} + +/// `WrittenBookContent.addToTooltip`: "by " and the generation. +pub fn written_book_lines( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Vec { + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let Some(book) = stack + .data() + .and_then(|d| d.written.as_ref()) + .filter(|_| display.shows("minecraft:written_book_content")) + else { + return Vec::new(); + }; + let mut lines = Vec::new(); + if !book.author.trim().is_empty() { + lines.push( + crate::text::format_translation( + &text("book.byAuthor"), + &[crate::text::Text::literal(&book.author)], + ) + .plain(), + ); + } + lines.push(text(&format!("book.generation.{}", book.generation))); + lines +} + +/// `JukeboxPlayable.addToTooltip`: the song's description. +pub fn jukebox_line( + stack: &ItemStack, + info: Option<&ItemInfo>, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:jukebox_playable") { + return None; + } + let song = match stack + .data() + .and_then(|d| d.other("minecraft:jukebox_playable")) + { + Some(Tag::String(song)) => song.to_string_lossy(), + // An inline song carries its own description. + Some(inline) => { + return inline + .get("description") + .map(|d| crate::entity_nbt::name_text(d).plain()); + } + None => info?.jukebox_song.clone()?, + }; + let key = format!("jukebox_song.{}", song.replacen(':', ".", 1)); + Some(translate(&key).unwrap_or(key)) +} + +/// `DyedItemColor.addToTooltip`: "Dyed" (italic, the flag), or with advanced +/// tooltips the colour's hex code. +pub fn dyed_line( + stack: &ItemStack, + display: &TooltipDisplay, + advanced: bool, + translate: &dyn Fn(&str) -> Option, +) -> Option<(String, bool)> { + let rgb = stack.data()?.dyed_color?; + if !display.shows("minecraft:dyed_color") { + return None; + } + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + Some(if advanced { + let hex = format!("#{:06X}", rgb & 0xFF_FFFF); + (text("item.color").replacen("%s", &hex, 1), false) + } else { + (text("item.dyed"), true) + }) +} + +/// `ItemStack.UNBREAKABLE_TOOLTIP`. +pub fn unbreakable_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + (stack.data()?.other("minecraft:unbreakable").is_some() + && display.shows("minecraft:unbreakable")) + .then(|| translate("item.unbreakable").unwrap_or_else(|| "item.unbreakable".into())) +} + +/// `PotionContents.addPotionTooltip`'s attribute block: an empty line, "When +/// Applied:" and the modifiers of the potion's effects (blue for a gain, red +/// for a loss); nothing for a potion whose effects add none. +pub fn potion_modifier_lines( + stack: &ItemStack, + translate: &dyn Fn(&str) -> Option, +) -> Vec<(String, u32)> { + if !is_potion_item(&stack.item) { + return Vec::new(); + } + let applied: Vec<(String, u32)> = stack + .potion() + .and_then(crate::brewing::potion) + .into_iter() + .flat_map(|p| p.effects.iter()) + .filter_map(|(effect, _, amplifier)| { + let (attribute, amount, operation) = effect_modifier(effect)?; + let amount = amount * (*amplifier + 1) as f64; + let line = modifier_line(translate, attribute, amount, operation, false)?; + let color = if amount > 0.0 { + rgba(85, 85, 255, 255) + } else { + rgba(255, 85, 85, 255) + }; + Some((line, color)) + }) + .collect(); + if applied.is_empty() { + return applied; + } + let mut lines = vec![ + (String::new(), u32::MAX), + ( + translate("potion.whenDrank").unwrap_or_else(|| "potion.whenDrank".into()), + rgba(170, 0, 170, 255), + ), + ]; + lines.extend(applied); + lines +} + +/// `ItemStack.components.size()`: the item's default components with the +/// stack's own changes applied. +pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize { + let mut keys: std::collections::HashSet = info + .map(|i| i.components.iter().cloned().collect()) + .unwrap_or_default(); + if let Some(Tag::Compound(patch)) = crate::item_data::components_tag(stack.damage, stack.data()) + { + for key in patch.keys() { + let key = key.to_string_lossy(); + match key.strip_prefix('!') { + Some(removed) => keys.remove(removed), + None => keys.insert(key), + }; + } + } + keys.len() +} + /// The lines of `stack` below its name that its components give, in /// `ItemStack.addDetailsToTooltip` order. pub fn detail_lines( @@ -265,19 +518,9 @@ pub fn detail_lines( )) )); } - // BeehiveBlock: the block state components of the item. - if path == "beehive" { - lines.push( - text("container.beehive.bees") - .replacen("%s", "0", 1) - .replacen("%s", "3", 1), - ); - lines.push( - text("container.beehive.honey") - .replacen("%s", "0", 1) - .replacen("%s", "5", 1), - ); - } + let display = TooltipDisplay::for_stack(stack); + lines.extend(bees_line(stack, &display, translate)); + lines.extend(honey_line(stack, &display, translate)); let data = stack.data(); // PotDecorations.addToTooltip. if let Some(sherds) = data @@ -303,32 +546,13 @@ pub fn detail_lines( .into_iter() .map(|l| l.0), ); - let applied: Vec = stack - .potion() - .and_then(crate::brewing::potion) - .into_iter() - .flat_map(|p| p.effects.iter()) - .filter_map(|(effect, _, amplifier)| { - let (attribute, amount, operation) = effect_modifier(effect)?; - modifier_line( - translate, - attribute, - amount * (*amplifier + 1) as f64, - operation, - false, - ) - }) - .collect(); - if !applied.is_empty() { - lines.push(String::new()); - lines.push(text("potion.whenDrank")); - lines.extend(applied); - } - } - // JukeboxPlayable.addToTooltip: the song's description. - if path.starts_with("music_disc_") { - lines.push(text(&format!("item.minecraft.{path}.desc"))); + lines.extend( + potion_modifier_lines(stack, translate) + .into_iter() + .map(|l| l.0), + ); } + lines.extend(jukebox_line(stack, info, &display, translate)); // Trim.addToTooltip. if let Some((material, pattern)) = data.and_then(|d| d.trim.as_ref()) { let short = |s: &str| s.trim_start_matches("minecraft:").to_owned(); @@ -342,10 +566,7 @@ pub fn detail_lines( text(&format!("trim_material.minecraft.{}", short(material))) )); } - // DyedItemColor.addToTooltip (without advanced tooltips). - if data.is_some_and(|d| d.dyed_color.is_some()) { - lines.push(text("item.dyed")); - } + lines.extend(dyed_line(stack, &display, false, translate).map(|l| l.0)); if let Some(info) = info { lines.extend( attribute_lines(&info.modifiers, None, translate) diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index b4092a201..1749f8243 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -128,6 +128,8 @@ pub struct ItemInfo { pub block_transformer: Option, /// Has a default `bundle_contents` (the bundles, `BundleItem`). pub bundle: bool, + /// The ids of the item's default components (its prototype's keys). + pub components: Vec, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -614,6 +616,10 @@ impl Items { cushion_color: c["minecraft:cushion/color"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), bundle: c.get("minecraft:bundle_contents").is_some(), + components: c + .as_object() + .map(|c| c.keys().cloned().collect()) + .unwrap_or_default(), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) From 85db9a23a942a5110d099771535edc7818467753 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:57:54 +0100 Subject: [PATCH 045/132] Use the small explosion particle when an explosion keeps blocks --- crates/horizon-client/src/game/explosion.rs | 18 +++++++++--------- .../horizon-client/src/game/lan_particles.rs | 10 ++++++++-- crates/horizon-client/src/particles.rs | 9 +++++---- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 8800e29d8..5d6b4eb4f 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -573,16 +573,16 @@ impl Game<'_> { let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7; self.audio .play("minecraft:entity.generic.explode", Some(center), 4.0, pitch); - let block_count = if interaction == BlockInteraction::Keep { - 0 - } else { - targets.len() - }; + // ServerLevel.explode sends toBlow.size() whatever the interaction, and + // `ServerExplosion.isSmall` also covers an explosion that keeps blocks. + let block_count = targets.len(); + let small = radius < 2.0 || interaction == BlockInteraction::Keep; let (world, facts) = (&self.world, self.res.facts()); - self.particles.explosion(center, radius, block_count, &|b| { - facts.is_air(world.block(b[0], b[1], b[2])) - }); - self.lan_explode(center, radius, block_count); + self.particles + .explosion(center, small, block_count, radius, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); + self.lan_explode(center, small, radius, block_count); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index c41fdf1ad..0095da624 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -225,8 +225,14 @@ impl Game<'_> { /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. - pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { - let emitter = if radius < 2.0 { + pub(super) fn lan_explode( + &self, + center: [f64; 3], + small: bool, + radius: f32, + block_count: usize, + ) { + let emitter = if small { "minecraft:explosion" } else { "minecraft:explosion_emitter" diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..2e28603c4 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1381,16 +1381,17 @@ impl ParticleEngine { } } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the - /// explosion particle (emitter for radius >= 2) and up to 512 poof/smoke - /// particles thrown from air inside the radius. + /// explosion particle (the emitter unless `ServerExplosion.isSmall`) and up + /// to 512 poof/smoke particles thrown from air inside the radius. pub fn explosion( &mut self, center: [f64; 3], - radius: f32, + small: bool, block_count: usize, + radius: f32, is_air: &dyn Fn([i32; 3]) -> bool, ) { - let ty = if radius < 2.0 { + let ty = if small { ParticleType::Explosion } else { ParticleType::ExplosionEmitter From 4efa49ae820f957164aa5ad05eaaab18e8403f91 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:58:22 +0100 Subject: [PATCH 046/132] Raise sprint dust under running players A sprinting player kicks up dust of the block under their feet every tick (Entity.spawnSprintParticle). Horizon drew none, for the window's player or for the other players it sees. --- .../horizon-client/src/game/client_ambient.rs | 91 +++++++++++++++++++ crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/game/remote.rs | 7 +- crates/horizon-client/src/mobs.rs | 2 + 4 files changed, 98 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index a10c6da49..b655aff3f 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -4,8 +4,12 @@ //! on the game that has the window, in-frame or following a server, never on //! a server: nothing of them goes over the network. use super::Game; +use horizon_client::blocks::RenderShape; use horizon_client::mobs::{MobEvent, ambient}; +use horizon_client::motion::{LAVA, WATER}; use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_client::pose::Pose; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { pub(super) fn tick_client_ambient(&mut self) { @@ -33,5 +37,92 @@ impl Game<'_> { } } self.eye_particles(); + self.sprint_dust(); + } + + /// `Entity.baseTick`'s `spawnSprintParticle` on a client: dust of the + /// block under a sprinting player's feet streams back from them every + /// tick, for the window's own player and for the other players it sees. + fn sprint_dust(&mut self) { + // Each runner's feet, movement and supporting block. + let mut runners: Vec<(Vec3, Vec3, Option<[i32; 3]>)> = Vec::new(); + // Entity.canSpawnSprintParticle. + if let Some(p) = self.player.as_ref() + && p.sprinting + && !p.spectator + && p.pose != Pose::Crouching + && !p.health.dead_or_dying() + && !p.fluids.was_touching_water + && !p.is_in_lava() + && p.fluid_height(WATER) <= 0.0 + && p.fluid_height(LAVA) <= 0.0 + { + let support = p.ground.supporting_block.map(|b| [b.x, b.y, b.z]); + runners.push((p.position, p.velocity, support)); + } + let guests = self.lan.iter().flat_map(|host| host.models.values()); + for m in self.mobs.iter().chain(guests) { + // Another player's fluids aren't known here: none where they stand. + let feet = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if m.extra.sprinting + && !m.extra.crouching + && m.alive() + && &*m.kind.id == "minecraft:player" + && self + .res + .facts() + .get(self.world.block(feet[0], feet[1], feet[2])) + .fluid_level + == 0 + { + runners.push((m.position, m.position.subtract(m.previous), None)); + } + } + for (position, movement, support) in runners { + // Entity.getOnPosLegacy: getOnPos(0.2). + let below = (position.y - f64::from(0.2f32)).floor() as i32; + let tall = |game: &Self, s: [i32; 3]| { + let name = game.block_name(s); + [ + "minecraft:fences", + "minecraft:walls", + "minecraft:fence_gates", + ] + .iter() + .any(|tag| game.block_in_tag(tag, &name)) + }; + let at = match support { + Some(s) if tall(self, s) => s, + Some(s) => [s[0], below, s[2]], + None => [position.x.floor() as i32, below, position.z.floor() as i32], + }; + let state = self.world.block(at[0], at[1], at[2]); + if self.res.facts().get(state).render_shape == RenderShape::Invisible { + continue; + } + let Some((sprite, tint)) = self.particle_sprite(state, at) else { + continue; + }; + let width = f64::from(0.6f32); + let r = self.particles.random(); + let mut x = position.x + (r.next_double() - 0.5) * width; + let mut z = position.z + (r.next_double() - 0.5) * width; + // Clamped into the block when the feet are in another column. + if position.x.floor() as i32 != at[0] { + x = x.clamp(f64::from(at[0]), f64::from(at[0]) + 1.0); + } + if position.z.floor() as i32 != at[2] { + z = z.clamp(f64::from(at[2]), f64::from(at[2]) + 1.0); + } + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite, tint), + [x, position.y + 0.1, z], + [movement.x * -4.0, 1.5, movement.z * -4.0], + ); + } } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..0ee6c961d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1409,6 +1409,7 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + m.extra.sprinting = g.sprinting; // Lying in its bed (LivingEntity.getBedOrientation). m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..23dc6c2f8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1973,9 +1973,9 @@ impl Game<'_> { } } } - // Entity.DATA_SHARED_FLAGS_ID's crouching bit: another - // player's or a mannequin's crouch (their model and - // Entity.isDiscrete's name tag). + // Entity.DATA_SHARED_FLAGS_ID's crouching and sprinting bits: + // another player's or a mannequin's crouch (their model and + // Entity.isDiscrete's name tag), and the dust a runner raises. if (mannequin || self .remote @@ -1986,6 +1986,7 @@ impl Game<'_> { for (index, _, value) in &p.values { if let (0, Value::Byte(flags)) = (index, value) { m.extra.crouching = flags & 2 != 0; + m.extra.sprinting = flags & 8 != 0; } } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..ffeb145eb 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -636,6 +636,8 @@ pub struct Attrs { pub struct Extra { /// Players: crouching and riding (HumanoidModel's poses). pub crouching: bool, + /// Players: sprinting (`Entity.DATA_SHARED_FLAGS_ID`), for the dust they raise. + pub sprinting: bool, pub passenger: bool, /// AgeableMob.age: negative while a baby (a tadpole counts up to 24000). pub age: i32, From d241c54e059bbb9274f8e2c1b2a1db6e3f62e815 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:58:45 +0100 Subject: [PATCH 047/132] Official mod: Recipes, a recipe viewer Every item sits in the item panel beside the inventory and container screens, with a search box (words in the name or id, @namespace, #tag). R or a click shows an item's recipes, U or a right click its uses, with a tab per station; Back returns through the pages. + beside a crafting recipe the player knows fills the grid as the recipe book does. In creative mode, with "Click gives items" on, a click gives one item and a right click a stack. The keys are rebindable in Controls. Written from vanilla 26.3's recipe book and screens and Horizon's design system only. On servers that are not Horizon it shows the game's own 26.3 recipes; known recipes and + follow the server's recipe book. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 7 + Cargo.toml | 2 +- docs/mods.md | 5 +- mods/official/recipes/Cargo.toml | 16 ++ mods/official/recipes/horizon-mod.toml | 9 + mods/official/recipes/src/lib.rs | 364 +++++++++++++++++++++++++ 6 files changed, 400 insertions(+), 3 deletions(-) create mode 100644 mods/official/recipes/Cargo.toml create mode 100644 mods/official/recipes/horizon-mod.toml create mode 100644 mods/official/recipes/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 0e93bba0e..4d48c48cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2962,6 +2962,13 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "recipes" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "redox_syscall" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index e4628f962..f6ff38ad8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/recipes", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/docs/mods.md b/docs/mods.md index 706e48bd6..4c7ba012a 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | -| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap | +| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap; and Recipes, a recipe viewer | | Runtime | `crates/horizon-mods` | wasmtime 48 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / test / check`, and the registry's CI (`registry build / review / list`) | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | @@ -521,7 +521,7 @@ says how). The formats: [api/mod-index.md](api/mod-index.md). ### Horizon's official mods -The Horizon extras that are mods now live in `mods/official//`, one crate each in the game's workspace, so +The Horizon extras that are mods now, and Horizon's own recipe viewer, live in `mods/official//`, one crate each in the game's workspace, so `cargo clippy --workspace` and pr_ready cover them. They use only the public API, like any other mod, with the same options on their settings page as the extra had and the same look. Each is published by a maintainer: build it on `main` with the toolchain CI uses (`cd mods/official/ && cargo horizon-mod build`), then open a pull request in @@ -535,6 +535,7 @@ so the same rustc and `Cargo.lock` give the same file. | Keystrokes | `keystrokes` | Extras > Keystrokes | `corner`: as above, default `top_left`; `cps`: `true` (default), `false` | | Zoom | `zoom` | Extras > Zoom | `level`: `2`, `3`, `4` (default), `6`, `8`, `10`; `smooth`: `true` (default), `false`; `sensitivity` (slower turning): `true` (default), `false`. The key is the game's: `key.zoom.zoom` in `horizon-mods.txt`, default `key.keyboard.z` | | Minimap | `minimap` | Extras > Minimap | `corner`: as above, default `top_right`; `size`: `64`, `96` (default), `128`; `shape`: `square` (default), `round`; `zoom` (blocks per pixel): `0.5`, `1` (default), `2`, `4`; `rotate`: `false` (default), `true`. The game draws the map (`render.set-minimap`) | +| Recipes | `recipes` | nothing (new) | `give` (a click on the item panel gives the item in creative mode: one, a stack with a right click): `false` (default), `true`. The keys are the game's: `key.recipes.recipe` (default `key.keyboard.r`) and `key.recipes.uses` (default `key.keyboard.u`) in `horizon-mods.txt`. Every item sits in the item panel (`browser`) with a search box (words in the name or id, `@namespace`, `#tag`); R or a click shows an item's recipes, U or a right click its uses, a tab per station, and + fills the grid with a recipe the player knows (`recipes.place`). On servers that are not Horizon it shows the game's own 26.3 recipes; known recipes and + follow the server's recipe book | ## Versions and compatibility diff --git a/mods/official/recipes/Cargo.toml b/mods/official/recipes/Cargo.toml new file mode 100644 index 000000000..5bf0f5d9c --- /dev/null +++ b/mods/official/recipes/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "recipes" +version = "1.0.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Horizon's official recipe viewer: every item beside the inventory, its recipes and uses." + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/mods/official/recipes/horizon-mod.toml b/mods/official/recipes/horizon-mod.toml new file mode 100644 index 000000000..f4c04af0d --- /dev/null +++ b/mods/official/recipes/horizon-mod.toml @@ -0,0 +1,9 @@ +id = "recipes" +name = "Recipes" +version = "1.0.0" +description = "Every item beside your inventory, with a search box. R over an item shows its recipes, U its uses (both rebindable in Controls), and + fills the crafting grid with a recipe you know. In creative mode a click can give you the item (Mod settings). On servers that are not Horizon, it shows this game's own 26.3 recipes; what you know and what + can fill follow the server's recipe book." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["recipes", "ui", "input", "game-read", "chat", "storage"] +experimental = ["recipes", "ui", "input"] diff --git a/mods/official/recipes/src/lib.rs b/mods/official/recipes/src/lib.rs new file mode 100644 index 000000000..42f856016 --- /dev/null +++ b/mods/official/recipes/src/lib.rs @@ -0,0 +1,364 @@ +//! Horizon's official recipe viewer. Every item sits in the item panel the +//! game draws beside the inventory and container screens (`browser`), with +//! a search box. R over an item, the panel's or any slot's, shows its +//! recipes, U its uses (`input.register-key`, so both can be rebound in +//! Controls); a click does the same, left for recipes and right for uses. +//! A recipe page has a tab per station, and + beside a crafting recipe the +//! player knows fills the grid as the recipe book does (`recipes.place`). +//! In creative mode, with "Click gives items" on, a click on a panel item +//! gives one, a right click a stack (`recipes.give`). +//! +//! On a server that is not Horizon the recipes are the game's own 26.3 +//! ones; `known` and `place` follow the server's recipe book. +use horizon_mod_sdk::{ + Mod, Registration, browser, chat, game, input, recipes, + recipes::Kind, + storage, + ui::{self, ButtonWidget, Widget}, +}; + +const RECIPE_KEY: &str = "recipe"; +const USES_KEY: &str = "uses"; +const GIVE_BUTTON: u32 = 1; +/// What `set-recipes` takes at most. +const MAX_RECIPES: usize = 256; +const MAX_STACKS: usize = 64; +/// The stations, in the order of their tabs, with each one's icon. +const STATIONS: [&str; 8] = [ + "minecraft:crafting_table", + "minecraft:furnace", + "minecraft:blast_furnace", + "minecraft:smoker", + "minecraft:campfire", + "minecraft:stonecutter", + "minecraft:smithing_table", + "minecraft:brewing_stand", +]; + +fn station(kind: Kind) -> usize { + match kind { + Kind::CraftingShaped | Kind::CraftingShapeless => 0, + Kind::Smelting => 1, + Kind::Blasting => 2, + Kind::Smoking => 3, + Kind::Campfire => 4, + Kind::Stonecutting => 5, + Kind::Smithing => 6, + Kind::Brewing => 7, + } +} + +fn stack(item: &str) -> browser::Stack { + browser::Stack { + item: item.into(), + count: 1, + components: String::new(), + } +} + +/// A recipe page: an item's recipes or its uses, on one station's tab. +#[derive(Clone)] +struct View { + item: browser::Stack, + uses: bool, + tab: usize, +} + +#[derive(Default)] +struct Recipes { + items: Vec, + all: Vec, + /// The panel's items now: indexes into `items`, after the search. + listed: Vec, + search: String, + /// The page shown, then the ones Back returns to. + history: Vec, + /// The book id behind each recipe the page shows (-1: none). + shown: Vec, + give: bool, +} + +impl Recipes { + fn id(&self, s: &recipes::Stack) -> &str { + self.items + .get(s.item as usize) + .map_or("minecraft:air", |i| &i.id) + } + fn convert(&self, s: &recipes::Stack) -> browser::Stack { + browser::Stack { + item: self.id(s).into(), + count: s.count, + components: s.components.clone(), + } + } + /// The same item, and the same components when `want` names some. + fn matches(&self, s: &recipes::Stack, want: &browser::Stack) -> bool { + self.id(s) == want.item && (want.components.is_empty() || s.components == want.components) + } + fn name<'a>(&'a self, item: &'a str) -> &'a str { + self.items + .iter() + .find(|i| i.id == item) + .map_or(item, |i| &i.name) + } + + /// Loads the tables once a world is open, and drops them when it closes. + fn load(&mut self) { + let in_world = game::get_player().is_some(); + if in_world && self.items.is_empty() { + self.items = recipes::items(); + self.all = recipes::all(); + self.list(); + } else if !in_world && !self.items.is_empty() { + browser::set_recipes("", &[], 0, &[]); + browser::set_items(&[]); + *self = Recipes { + give: self.give, + ..Recipes::default() + }; + } + } + + /// Fills the panel with the items the search keeps: every word must be + /// in the name or the id; `@minecraft` keeps a namespace, `#logs` a tag. + fn list(&mut self) { + let words: Vec = self + .search + .to_lowercase() + .split_whitespace() + .map(String::from) + .collect(); + let keeps = |item: &recipes::Item| { + words.iter().all(|w| { + if let Some(ns) = w.strip_prefix('@') { + item.id.split(':').next().is_some_and(|n| n.starts_with(ns)) + } else if let Some(tag) = w.strip_prefix('#') { + item.tags.iter().any(|t| t.contains(tag)) + } else { + item.name.to_lowercase().contains(w.as_str()) || item.id.contains(w.as_str()) + } + }) + }; + self.listed = (self.items.iter().enumerate()) + .filter(|(_, i)| i.id != "minecraft:air" && keeps(i)) + .map(|(n, _)| n) + .collect(); + let stacks: Vec<_> = self + .listed + .iter() + .map(|&n| stack(&self.items[n].id)) + .collect(); + browser::set_items(&stacks); + } + + /// The recipes a view lists, all stations together. + fn found(&self, view: &View) -> Vec<&recipes::Recipe> { + (self.all.iter()) + .filter(|r| { + if view.uses { + r.slots + .iter() + .flatten() + .any(|s| self.matches(s, &view.item)) + } else { + r.results.iter().any(|s| self.matches(s, &view.item)) + } + }) + .collect() + } + + /// Opens a page, pushing it on the history; nothing when it is empty. + fn open(&mut self, item: browser::Stack, uses: bool) { + let view = View { item, uses, tab: 0 }; + if self.found(&view).is_empty() { + return; + } + self.history.push(view); + self.show(); + } + + /// Sends the page on top of the history, or the items when there is none. + fn show(&mut self) { + let Some(mut view) = self.history.last().cloned() else { + self.shown.clear(); + browser::set_recipes("", &[], 0, &[]); + return; + }; + let found = self.found(&view); + let stations: Vec = (0..STATIONS.len()) + .filter(|&s| found.iter().any(|r| station(r.kind) == s)) + .collect(); + view.tab = view.tab.min(stations.len().saturating_sub(1)); + let on: Vec<&recipes::Recipe> = (found.iter().copied()) + .filter(|r| stations.get(view.tab) == Some(&station(r.kind))) + .take(MAX_RECIPES) + .collect(); + let known = recipes::known(); + let views: Vec = on.iter().map(|r| self.view(r, &known)).collect(); + let mut title = format!( + "{}: {}", + if view.uses { "Uses" } else { "Recipes" }, + self.name(&view.item.item) + ); + let total = found + .iter() + .filter(|r| stations.get(view.tab) == Some(&station(r.kind))) + .count(); + if total > on.len() { + title.push_str(&format!(" ({} of {total})", on.len())); + } + let tabs: Vec<_> = stations.iter().map(|&s| stack(STATIONS[s])).collect(); + browser::set_recipes(&title, &tabs, view.tab as u32, &views); + self.shown = on.iter().map(|r| r.book_id).collect(); + if let Some(top) = self.history.last_mut() { + top.tab = view.tab; + } + } + + fn view(&self, r: &recipes::Recipe, known: &[i32]) -> browser::RecipeView { + let mut slots: Vec> = (r.slots.iter()) + .map(|s| s.iter().take(MAX_STACKS).map(|s| self.convert(s)).collect()) + .collect(); + let results = r + .results + .iter() + .take(MAX_STACKS) + .map(|s| self.convert(s)) + .collect(); + let (layout, width, height, note) = match r.kind { + Kind::CraftingShaped => (browser::Layout::Grid, r.width, r.height, String::new()), + Kind::CraftingShapeless => { + let n = slots.len() as u32; + let width = match n { + 0 | 1 => 1, + 2..=4 => 2, + _ => 3, + }; + let height = n.div_ceil(width).max(1); + slots.resize((width * height) as usize, Vec::new()); + (browser::Layout::Grid, width, height, "Shapeless".into()) + } + Kind::Smelting | Kind::Blasting | Kind::Smoking | Kind::Campfire => { + let seconds = r.cooking_time as f32 / 20.0; + let note = format!("{seconds} s, {} XP", (r.experience * 100.0).round() / 100.0); + (browser::Layout::Cooking, 1, 1, note) + } + Kind::Stonecutting => (browser::Layout::Single, 1, 1, String::new()), + Kind::Smithing => (browser::Layout::Smithing, 3, 1, String::new()), + Kind::Brewing => (browser::Layout::Brewing, 2, 1, String::new()), + }; + // + only for what the recipe book shows; greyed until the book has it. + let action = (r.book_id >= 0).then(|| known.contains(&r.book_id)); + browser::RecipeView { + layout, + width, + height, + slots, + results, + note, + action, + } + } + + fn handle(&mut self, event: browser::Event) { + match event { + browser::Event::Search(text) => { + self.search = text; + self.list(); + } + browser::Event::Clicked(c) => { + let Some(&n) = self.listed.get(c.index as usize) else { + return; + }; + let item = self.items[n].id.clone(); + if self.give { + let count = if c.right { 99 } else { 1 }; + let gift = recipes::Stack { + item: n as u32, + count, + components: String::new(), + }; + if recipes::give(&gift).is_ok() { + return; + } + } + self.open(stack(&item), c.right); + } + browser::Event::Key(k) if k.key == RECIPE_KEY || k.key == USES_KEY => { + let item = browser::Stack { + count: 1, + ..k.stack + }; + self.open(item, k.key == USES_KEY); + } + browser::Event::SlotClicked(c) => { + let item = browser::Stack { + count: 1, + ..c.stack + }; + self.open(item, c.right); + } + browser::Event::Tab(i) => { + if let Some(top) = self.history.last_mut() { + top.tab = i as usize; + } + self.show(); + } + browser::Event::Action(i) => { + let book = self.shown.get(i as usize).copied(); + if let Some(Err(e)) = book.map(|b| recipes::place(b, false)) { + chat::show(&e); + } + } + browser::Event::Back => { + self.history.pop(); + self.show(); + } + _ => {} + } + } + + fn page(&self) { + ui::set_settings(&[Widget::Button(ButtonWidget { + id: GIVE_BUTTON, + label: format!( + "Click gives items (creative): {}", + if self.give { "ON" } else { "OFF" } + ), + })]); + } +} + +impl Mod for Recipes { + fn init() -> Result<(Self, Registration), String> { + input::register_key(RECIPE_KEY, "Show recipes", "key.keyboard.r")?; + input::register_key(USES_KEY, "Show uses", "key.keyboard.u")?; + let give = storage::get("give").is_some_and(|v| v == b"true"); + let me = Recipes { + give, + ..Recipes::default() + }; + me.page(); + Ok((me, Registration::new().on_frame())) + } + fn frame(&mut self, _seconds: f32) { + self.load(); + // The keys matter only over an item, which `browser` reports. + let _ = input::poll(); + for event in browser::poll() { + self.handle(event); + } + } + fn ui_select(&mut self, id: u32, _row: u32) { + if id == GIVE_BUTTON { + self.give = !self.give; + let _ = storage::set("give", if self.give { b"true" } else { b"false" }); + self.page(); + } + } + fn ui_settings_opened(&mut self) { + self.page(); + } +} + +horizon_mod_sdk::export_mod!(Recipes); From 29eae3a1afc1f725a69a43cc8da3d44c878c43ff Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:58:51 +0100 Subject: [PATCH 048/132] Throw a burst of spit particles when a llama spits --- crates/horizon-client/src/game/creatures.rs | 5 +++++ crates/horizon-client/src/game/remote_projectiles.rs | 4 ++++ crates/horizon-client/src/particles.rs | 12 ++++++++++++ 3 files changed, 21 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 86a7954e9..7343064e5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1013,6 +1013,11 @@ impl Game<'_> { self.next_entity += 1; p.id = self.next_entity; let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]); + // LlamaSpit.recreateFromPacket: the spit's burst on the client. + if p.kind == ProjectileKind::LlamaSpit { + let v = p.velocity; + self.particles.llama_spit_burst(at, [v.x, v.y, v.z]); + } self.creatures.projectiles.push(p); self.projectile_event("minecraft:projectile_shoot", owner, at); } diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 897999c6b..64f09d72a 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -161,6 +161,10 @@ impl Game<'_> { let Some(k) = projectile_kind(kind) else { return false; }; + if k == ProjectileKind::LlamaSpit { + self.particles + .llama_spit_burst(position, [velocity.x, velocity.y, velocity.z]); + } let mut p = Projectile::new(k, at, None); p.id = id; p.velocity = velocity; diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..fd05a1ac1 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1398,6 +1398,18 @@ impl ParticleEngine { self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); self.explosion_blocks(center, radius, block_count, is_air); } + /// `LlamaSpit.recreateFromPacket`: seven spit particles thrown ahead of a + /// new spit, each faster than the last along x and z. + pub fn llama_spit_burst(&mut self, at: [f64; 3], movement: [f64; 3]) { + for i in 0..7 { + let k = 0.4 + 0.1 * f64::from(i); + self.add( + &ParticleOptions::simple(ParticleType::Spit), + at, + [movement[0] * k, movement[1], movement[2] * k], + ); + } + } /// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`. pub fn explosion_blocks( &mut self, From 96b538d48f6e8e9da03faa04a8f9b8c85f1cf281 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:59:59 +0100 Subject: [PATCH 049/132] Throw up landing dust where a hard fall lands A landing that hurts sends the block's crumbs from the server (LivingEntity.checkFallDamage). Horizon built the event but dropped it, for the window's player and for every server player. --- crates/horizon-client/src/game.rs | 7 ++ crates/horizon-client/src/game/lan_actions.rs | 7 ++ .../horizon-client/src/game/lan_particles.rs | 79 +++++++++++++++++-- 3 files changed, 87 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a51bdcbcb..5b69799fc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4578,6 +4578,13 @@ impl Game<'_> { }; self.audio.play(name, Some(feet), volume, pitch); } + // LivingEntity.checkFallDamage: the block's crumbs where the fall landed. + MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { + state, + position, + count, + speed, + }) => self.landing_dust(None, state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..31bb454cb 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2310,6 +2310,13 @@ impl Game<'_> { for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at), + // LivingEntity.checkFallDamage: the crumbs reach every player. + MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { + state, + position, + count, + speed, + }) => self.landing_dust(Some(host), state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), _ => {} } diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index c41fdf1ad..888264bcc 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -1,7 +1,8 @@ //! Particles a server sends its players and its clients draw: //! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which //! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). -use super::Game; +use super::{Game, lan::LanHost}; +use horizon_client::lan::hub::Hub; use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ @@ -52,6 +53,66 @@ impl Game<'_> { } } + /// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the + /// landing block's crumbs: drawn in this window, when it has one, and + /// sent to each player within 32 blocks. `host` is the hub of a guest's + /// turn, which is out of `self.lan` meanwhile. + pub(super) fn landing_dust( + &mut self, + host: Option<&LanHost>, + state: BlockStateId, + at: Vec3, + count: i32, + speed: f64, + ) { + let at = [at.x, at.y, at.z]; + if self.serving.is_none() && self.options.dedicated.is_none() { + let block = [ + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ]; + if let Some((sprite, tint)) = self.particle_sprite(state, block) { + self.particles.send_particles( + &ParticleOptions::block(ParticleType::Block, sprite, tint), + at, + [0.0; 3], + speed, + count as u32, + ); + } + } + let Some(hub) = host.or(self.lan.as_ref()).map(|h| &h.hub) else { + return; + }; + let Some(particle) = Self::hub_particle( + hub, + &ParticleOptions::simple(ParticleType::Block), + Some(state), + ) else { + return; + }; + let packet = C::LevelParticles(play::LevelParticles { + particle, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.0; 3], + max_speed: [speed as f32; 3], + count, + randomization: 0, + }); + for g in hub.guests.iter().filter(|g| hub.here(g)) { + // ServerLevel compares the player's block centre, strictly within 32. + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } + } + /// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's /// network id and the data it carries (`state` for the block particles). /// None while not serving, or for a particle whose data isn't sent from @@ -60,13 +121,19 @@ impl Game<'_> { &self, options: &ParticleOptions, state: Option, + ) -> Option { + Self::hub_particle(&self.lan.as_ref()?.hub, options, state) + } + + /// `network_particle` for a hub that is out of `self.lan` meanwhile (a + /// guest's turn). + fn hub_particle( + hub: &Hub, + options: &ParticleOptions, + state: Option, ) -> Option { let name = format!("minecraft:{}", options.ty.name()); - let id = self - .lan - .as_ref()? - .hub - .registry_id("minecraft:particle_type", &name)?; + let id = hub.registry_id("minecraft:particle_type", &name)?; use ParticleType as T; let c = options.color; let data = match options.ty { From a08f3eb2fa74ccff9d3565b8c0cab520a55276d8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:02:36 +0100 Subject: [PATCH 050/132] Select a bundle's item with the mouse wheel --- crates/horizon-client/src/bundle.rs | 56 ++++++++-- crates/horizon-client/src/game.rs | 12 ++ crates/horizon-client/src/game/bundles.rs | 103 ++++++++++++++++++ crates/horizon-client/src/game/lan_actions.rs | 6 + crates/horizon-client/src/game/remote.rs | 4 +- crates/horizon-client/src/game/stations.rs | 22 +++- crates/horizon-client/src/item_data.rs | 17 +++ crates/horizon-client/src/item_render.rs | 1 + crates/horizon-client/src/lan/containers.rs | 36 ++++++ crates/horizon-client/src/lan/menu.rs | 5 +- crates/horizon-client/src/menu/bundle.rs | 7 +- crates/horizon-protocol/src/packets/play.rs | 6 + 12 files changed, 260 insertions(+), 15 deletions(-) create mode 100644 crates/horizon-client/src/game/bundles.rs diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs index 42473729f..948e2f4a9 100644 --- a/crates/horizon-client/src/bundle.rs +++ b/crates/horizon-client/src/bundle.rs @@ -1,6 +1,7 @@ //! `BundleContents.Mutable`: what a bundle takes in and gives back, by //! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click //! overrides on it. +use crate::item_data::BundleSelected; use crate::items::{ItemStack, Items}; use horizon_world::nbt::Tag; @@ -97,6 +98,8 @@ pub fn can_be_in_bundle(stack: &ItemStack) -> bool { pub struct Contents { items: Vec, weight: Weight, + /// `selectedItem`: an index into `items`, -1 for none. + selected: i32, } impl Contents { @@ -104,9 +107,11 @@ impl Contents { pub fn of(items: &Items, stack: &ItemStack) -> Option { let inside = contents_of(items, stack)?.to_vec(); let weight = contents_weight(items, &inside); + let selected = stack.data().map_or(-1, |d| d.bundle_selected.0); Some(Self { items: inside, weight, + selected, }) } @@ -154,18 +159,26 @@ impl Contents { amount } - /// `removeOne`: the first stack (Horizon keeps no selected item). + /// `removeOne`: the selected stack, else the first; nothing is selected after. pub fn remove_one(&mut self, items: &Items) -> Option { if self.items.is_empty() { return None; } - let stack = self.items.remove(0); + let at = + usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 }); + let stack = self.items.remove(at); self.weight = self .weight .sub(item_weight(items, &stack).times(stack.count)); + self.selected = -1; Some(stack) } + /// `getSelectedItemIndex`. + pub fn selected(&self) -> i32 { + self.selected + } + /// The stacks inside, in display order (the first is the next out). pub fn items(&self) -> &[ItemStack] { &self.items @@ -200,11 +213,28 @@ impl Contents { /// `toImmutable`, written back into the bundle's component. pub fn store(self, bundle: &mut ItemStack) { - bundle.data_mut().bundle_contents = self.items; + let data = bundle.data_mut(); + data.bundle_contents = self.items; + data.bundle_selected = BundleSelected(self.selected); bundle.tidy(); } } +/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the +/// selected one already or outside the contents. +pub fn toggle_selected(bundle: &mut ItemStack, index: i32) { + let Some(data) = bundle.extra.as_deref_mut() else { + return; + }; + let inside = (0..data.bundle_contents.len() as i32).contains(&index); + let selected = if data.bundle_selected.0 != index && inside { + index + } else { + -1 + }; + data.bundle_selected = BundleSelected(selected); +} + #[cfg(test)] mod tests { use super::Weight; @@ -232,8 +262,10 @@ pub struct TooltipLayout { /// The component's own width (96) and height, the text's excluded. pub width: f32, pub height: f32, - /// Each slot's top-left and the stack in it, in reading order. + /// Each slot's top-left and the stack in it, in drawing order. pub slots: Vec<([f32; 2], ItemStack)>, + /// The position in `slots` of the selected item, which is drawn highlighted. + pub selected: Option, /// The `+N` of the items past the grid: its top-left and the count. pub overflow: Option<([f32; 2], u32)>, /// The progress bar's top-left, its fill's width out of 94, and whether @@ -266,6 +298,7 @@ pub fn tooltip_layout( width: 96.0, height: description_height + 13.0 + 8.0, slots: Vec::new(), + selected: None, overflow: None, bar: [x + offset, y + description_height + 4.0], fill: 0.0, @@ -282,6 +315,7 @@ pub fn tooltip_layout( let x_start = x + offset + 96.0; let y_start = y + grid_height; let mut slots = Vec::with_capacity(shown.len()); + let mut selected = None; let mut overflow = None; // Rows fill bottom-up and columns right-to-left, as vanilla draws them. let mut slot = 0; @@ -290,8 +324,13 @@ pub fn tooltip_layout( let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0]; if hidden > 0 && row == 1 && column == 1 { overflow = Some((at, hidden)); - } else if let Some(stack) = shown.get(slot) { - slots.push((at, stack.clone())); + } else if slot < shown.len() { + // `extractSlot`: the cell of slot number n holds item `size - n`. + let index = shown.len() - 1 - slot; + if usize::try_from(contents.selected()) == Ok(index) { + selected = Some(slots.len()); + } + slots.push((at, shown[index].clone())); slot += 1; } } @@ -301,6 +340,7 @@ pub fn tooltip_layout( width: 96.0, height: grid_height + 13.0 + 8.0, slots, + selected, overflow, bar: [x + offset, y + grid_height + 4.0], // `Mth.mulAndTruncate(weight, 94)`, kept within the bar. @@ -349,8 +389,8 @@ mod tooltip_tests { assert_eq!(layout.slots.len(), 12); assert_eq!(layout.overflow, None); assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0); - // Rows fill bottom-up and columns right-to-left: the first item is in - // the bottom-right cell, the twelfth in the top-left. + // Rows fill bottom-up and columns right-to-left: the twelfth item is in + // the bottom-right cell, the first in the top-left. assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]); assert_eq!(&*layout.slots[0].1.item, "minecraft:stone"); assert_eq!(layout.slots[11].0, [0.0, 0.0]); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index de7eb448b..fc92a6c6f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -18,6 +18,7 @@ mod boats; mod books; mod bossbars; mod breezes; +mod bundles; mod campfire; mod campfire_douse; mod cartography; @@ -1254,6 +1255,8 @@ struct Game<'a> { inv_clicks: horizon_client::container_screen::Clicks, /// The Mouse Tweaks extra's drag and wheel (`tweaks`). tweaks: tweaks::Tweaks, + /// The wheel and hovered slot of `BundleMouseActions`. + bundle_mouse: bundles::BundleMouse, /// The last inventory click, for the double click that gathers a stack. last_inv_click: Option<(std::time::Instant, usize, bool)>, /// `lastQuickMoved`: what the last Shift click moved, which a Shift @@ -4653,6 +4656,7 @@ impl Game<'_> { self.shield_cooldown = self.shield_cooldown.saturating_sub(1); self.cooldowns.tick(); horizon_client::spans::time("tick_using", || self.tick_using()); + self.tick_bundle_hover(); horizon_client::spans::time("tick_hud", || self.tick_hud()); // The player's digging comes in with its packets, before the level // ticks; ServerLevel.tick then runs the scheduled and random block @@ -5847,6 +5851,12 @@ impl Game<'_> { /// Several clicks on one menu instance (a quick craft drag is three). fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::Input; + // BundleMouseActions.onSlotClicked: a Shift click or a swap clears the bundle's selection. + for &(slot, _, input) in ops { + if let (Some(slot), Input::QuickMove | Input::Swap) = (slot, input) { + self.unselect_bundle(slot); + } + } if self.remote.is_some() && self.screen == Screen::Inventory { // On a server the clicks are the server's: predicted and sent. return self.remote_menu_ops(ops); @@ -11660,6 +11670,7 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory && d != 0.0 + && !self.bundle_scroll(scaled(raw_x), scaled(raw_y)) && !self.tweak_scroll(d, self.inventory_target().0) { self.station_scroll(d); @@ -12441,6 +12452,7 @@ impl<'a> Game<'a> { craft_table: None, inv_drag: None, tweaks: Default::default(), + bundle_mouse: Default::default(), inv_clicks: Default::default(), last_inv_click: None, last_quick_moved: None, diff --git a/crates/horizon-client/src/game/bundles.rs b/crates/horizon-client/src/game/bundles.rs new file mode 100644 index 000000000..198964803 --- /dev/null +++ b/crates/horizon-client/src/game/bundles.rs @@ -0,0 +1,103 @@ +//! `BundleMouseActions`: the wheel over a bundle in a container screen selects +//! one of the items it shows, which a click that takes one out of it then takes +//! (`BundleContents.Mutable.removeOne`). Moving off the bundle clears the +//! selection. On a server the selection is sent to it (`ServerboundSelectBundleItemPacket`). +use super::{Game, Screen}; +use horizon_client::{ + bundle::{Contents, toggle_selected}, + mouse::ScrollWheelHandler, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +#[derive(Default)] +pub(super) struct BundleMouse { + wheel: ScrollWheelHandler, + /// The slot under the cursor at the last tick (`AbstractContainerScreen.hoveredSlot`). + hovered: Option, +} + +impl Game<'_> { + /// A slot a bundle can be selected in: the player's inventory, the off hand and a + /// container's own slots. A server only knows these in the inventory and chest-like menus. + fn bundle_slot(&mut self, slot: usize) -> bool { + (slot < 36 || slot == 504 || (300..500).contains(&slot)) + && (self.remote.is_none() || self.remote_storage_open()) + && (slot < 36 || slot == 504 || self.slots().contains(&slot)) + } + + /// `BundleMouseActions.onMouseScrolled`: the wheel over a bundle moves the selection + /// through the items its tooltip shows. True when the bundle took the wheel. + pub(super) fn bundle_scroll(&mut self, x: f64, y: f64) -> bool { + let Some(slot) = self.inventory_target().0 else { + return false; + }; + if !self.bundle_slot(slot) { + return false; + } + let stack = self.slot_mut(slot).clone(); + let items = self.res.items(); + let Some(bundle) = stack.filter(|s| items.get(&s.item).is_some_and(|i| i.bundle)) else { + return false; + }; + let shown = Contents::of(items, &bundle).map_or(0, |c| c.shown_count()); + if shown == 0 { + return false; + } + let (wheel_x, wheel_y) = self.bundle_mouse.wheel.on_mouse_scroll(x, y); + let wheel = if wheel_y == 0 { -wheel_x } else { wheel_y }; + if wheel != 0 { + let selected = bundle.data().map_or(-1, |d| d.bundle_selected.0); + let next = ScrollWheelHandler::next_selection(f64::from(wheel), selected, shown as i32); + if next != selected { + self.select_bundle(slot, next); + } + } + true + } + + /// `BundleMouseActions.toggleSelectedBundleItem`: the stack here and, on a server, there. + fn select_bundle(&mut self, slot: usize, index: i32) { + if let Some(stack) = self.slot_mut(slot) { + toggle_selected(stack, index); + } + if self.remote.is_some() { + let (_, menu) = self.remote_menu(); + if let Some(menu_slot) = Self::menu_slot_index(&menu, slot) { + self.send(S::SelectBundleItem(play::SelectBundleItem { + slot: menu_slot as i32, + index, + })); + } + } + } + + /// `BundleMouseActions.unselectedBundleItem` for the bundle in `slot`, if it has a selection. + pub(super) fn unselect_bundle(&mut self, slot: usize) { + if !self.bundle_slot(slot) { + return; + } + let selected = self + .slot_mut(slot) + .as_ref() + .and_then(|s| s.data()) + .is_some_and(|d| d.bundle_selected.0 >= 0); + if selected { + self.select_bundle(slot, -1); + } + } + + /// `AbstractContainerScreen.onStopHovering` (and `onClose`): leaving a slot, or the + /// screen, clears the bundle's selection. + pub(super) fn tick_bundle_hover(&mut self) { + let now = if self.screen == Screen::Inventory { + self.inventory_target().0 + } else { + None + }; + if let Some(left) = std::mem::replace(&mut self.bundle_mouse.hovered, now) + && Some(left) != now + { + self.unselect_bundle(left); + } + } +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..df651b102 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1216,6 +1216,12 @@ impl Game<'_> { { self.guest_carried_back(host, gi); } + S::SelectBundleItem(p) => { + if !spectator && let Ok(slot) = usize::try_from(p.slot) { + host.hub + .select_bundle_item(conn, slot, p.index, &mut self.world); + } + } S::ContainerClick(p) => { let rules = ItemRules(self.res.items()); let slots = host.hub.guests[gi] diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..32f5f6093 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1558,7 +1558,7 @@ impl Game<'_> { } } /// Find a game slot in the menu's complete, contiguous slot mapping. - fn menu_slot_index(menu: &str, internal: usize) -> Option { + pub(super) fn menu_slot_index(menu: &str, internal: usize) -> Option { (0..) .map_while(|slot| Self::menu_slot(menu, slot)) .position(|slot| slot == internal) @@ -4701,7 +4701,7 @@ impl Game<'_> { } /// The server's open menu: its window id and menu type (0, "inventory" /// when none is open). - fn remote_menu(&self) -> (i32, String) { + pub(super) fn remote_menu(&self) -> (i32, String) { match self.remote.as_ref().and_then(|r| r.menu.clone()) { Some((id, name)) => (id, name), None => (0, "inventory".to_owned()), diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 56b19e393..8efd6eed9 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -2104,12 +2104,18 @@ impl Game<'_> { batch: &mut HudBatch, layout: &horizon_client::bundle::TooltipLayout, ) { - for (at, stack) in &layout.slots { + for (i, (at, stack)) in layout.slots.iter().enumerate() { + let selected = layout.selected == Some(i); + let sprite = |name: &str| format!("gui/sprites/container/bundle/{name}"); // Each draw takes the atlas on its own: the item's needs `&mut self`. horizon_client::ui::nine_slice( batch, &self.gui.atlas, - "gui/sprites/container/bundle/slot_background", + &sprite(if selected { + "slot_highlight_back" + } else { + "slot_background" + }), at[0], at[1], 24.0, @@ -2119,6 +2125,18 @@ impl Game<'_> { let stack = stack.clone(); let [x, y] = *at; self.draw_item(batch, &stack, x + 4.0, y + 4.0); + if selected { + horizon_client::ui::nine_slice( + batch, + &self.gui.atlas, + &sprite("slot_highlight_front"), + x, + y, + 24.0, + 24.0, + u32::MAX, + ); + } } let atlas = &self.gui.atlas; if let Some((at, hidden)) = layout.overflow { diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index ac624e85b..253bc6cc5 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -52,6 +52,8 @@ pub struct StackData { pub pot_decorations: Option; 4]>>, /// `minecraft:bundle_contents`. pub bundle_contents: Vec, + /// `BundleContents.selectedItem`: runtime only, never saved or sent. + pub bundle_selected: BundleSelected, /// `minecraft:suspicious_stew_effects`: (effect id, duration). pub stew_effects: Vec<(Arc, i32)>, /// `minecraft:map_post_processing`: 0 lock, 1 scale. @@ -60,6 +62,20 @@ pub struct StackData { /// max stack size...), kept as their saved values in key order. pub other: Vec<(String, Tag)>, } +/// A bundle's selected item index (-1: none). Like vanilla's +/// `BundleContents.equals` it is left out when stacks are compared. +#[derive(Clone, Copy, Debug)] +pub struct BundleSelected(pub i32); +impl Default for BundleSelected { + fn default() -> Self { + Self(-1) + } +} +impl PartialEq for BundleSelected { + fn eq(&self, _: &Self) -> bool { + true + } +} /// The components `components_tag` writes from modelled fields. const MODELLED: &[&str] = &[ "minecraft:banner_patterns", @@ -791,6 +807,7 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Value { /// The resolver's view of a client stack: its item, count and component patch. pub fn stack_view(stack: &crate::items::ItemStack) -> StackView { let mut view = StackView::new(&stack.item, stack.count as i32); + view.bundle_selected = stack.data().map_or(-1, |d| d.bundle_selected.0); if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) { for (k, v) in &c { let key = k.to_string_lossy(); diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 002f95cbb..c5fede5c6 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -421,6 +421,42 @@ impl Hub { drops } + /// `AbstractContainerMenu.setSelectedBundleItemIndex` on the guest's open + /// menu: a container's own slots, or the inventory's. A bundle's selection + /// lives on the server's stack until the click that takes from it. + pub fn select_bundle_item(&mut self, conn: u32, slot: usize, index: i32, world: &mut World) { + let Some(g) = self.guests.iter_mut().find(|g| g.conn == conn) else { + return; + }; + let open = g.menu.as_ref().map(|m| (m.size, m.slots)); + let mut items = match open { + Some((size, source)) if slot < size => source.read(world, g), + _ => None, + }; + let stack = match open { + Some((size, _)) if slot < size => items + .as_mut() + .and_then(|items| items.get_mut(slot)) + .and_then(Option::as_mut), + Some((size, _)) => g + .inventory + .get_mut(player_slot(slot - size)) + .and_then(Option::as_mut), + None => match slot { + 9..=35 => g.inventory.get_mut(slot).and_then(Option::as_mut), + 36..=44 => g.inventory.get_mut(slot - 36).and_then(Option::as_mut), + 45 => g.offhand.as_mut(), + _ => None, + }, + }; + if let Some(stack) = stack { + crate::bundle::toggle_selected(stack, index); + } + if let (Some((_, source)), Some(items)) = (open, items) { + source.write(world, g, items); + } + } + /// A click on the inventory menu (window 0) the game applied itself /// (the crafting grid): the client is corrected like after any click. pub fn inventory_clicked( diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index 859bafa23..641e45b1b 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -5,7 +5,7 @@ //! menu are returned for the game to drop. use super::guest::Guest; use crate::{ - bundle::{Contents, can_be_in_bundle}, + bundle::{Contents, can_be_in_bundle, toggle_selected}, items::{ItemStack, Items}, world::World, }; @@ -514,7 +514,10 @@ fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bo } } (carried, _) => { + // toggleSelectedItem(-1), then the click goes on. view.guest.carried = carried; + toggle_selected(&mut bundle, -1); + view.set(i, Some(bundle)); return false; } } diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs index fba4a488e..78a52655a 100644 --- a/crates/horizon-client/src/menu/bundle.rs +++ b/crates/horizon-client/src/menu/bundle.rs @@ -1,7 +1,7 @@ //! `BundleItem`'s click overrides in a PICKUP click //! (`tryItemClickBehaviourOverride`). use super::{Env, Menu, tidy}; -use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle}; +use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle, toggle_selected}; impl Menu { /// The carried stack's `overrideStackedOnOther`, then the clicked @@ -88,8 +88,11 @@ impl Menu { } } (carried, _) => { - // toggleSelectedItem(-1): Horizon keeps no selected item. + // toggleSelectedItem(-1), then the click goes on. self.carried = carried; + toggle_selected(&mut bundle, -1); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = Some(bundle); return false; } } diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bc09a84..7ab82720d 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2249,6 +2249,11 @@ packet!( /// Input flags: forward 1, backward 2, left 4, right 8, jump 16, shift 32, sprint 64. PlayerInput { flags: u8 => UByte } ); +packet!( + /// ServerboundSelectBundleItemPacket: the menu slot of a bundle and the + /// index of its selected item (-1: none). + SelectBundleItem { slot: i32 => VarInt, index: i32 => VarInt } +); packet!(SetCarriedItem { slot: i16 => Short }); packet!(SetCreativeModeSlot { slot: i16 => Short, item: Option => Slot }); packet!(UseItem { hand: i32 => VarInt, sequence: i32 => VarInt, yaw: f32 => Float, pitch: f32 => Float }); @@ -2317,6 +2322,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SelectBundleItem(SelectBundleItem) = BUNDLE_ITEM_SELECTED, SelectTrade(SelectTrade) = SELECT_TRADE, SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, From efd6c60a272d20f69e498a48afe3e96a759cf164 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:07:36 +0100 Subject: [PATCH 051/132] Axolotl air: refill only where it rains locally, not in deserts or snowy biomes --- crates/horizon-client/src/mobs/ai.rs | 2 +- crates/horizon-client/src/mobs/world.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 403f63101..3499ab29d 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -458,7 +458,7 @@ fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) { m.position.z.floor() as i32, ); let top = (m.position.y + f64::from(m.height())).floor() as i32; - let in_rain = w.raining && (w.can_see_sky(x, y, z) || w.can_see_sky(x, top, z)); + let in_rain = w.raining_at(x, y, z) || w.raining_at(x, top, z); if m.fluids.in_water || in_rain { m.air = super::axolotl::MAX_AIR; } else { diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 7836a49ef..db2557e72 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -177,6 +177,25 @@ impl MobWorld<'_> { } self.world.light(x, y, z) >> 4 == 15 } + /// Level.isRainingAt: raining, open to the sky, nothing motion blocking + /// above, and the biome's precipitation at the position (its temperature + /// lowered above the snow level) is rain, not snow or none. + pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool { + if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y { + return false; + } + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + return false; + }; + let biome = self.biomes.get(chunk.biome(x, y, z)); + let snow_level = self.sea_level + 17; + let temperature = if y > snow_level { + biome.temperature - (y - snow_level) as f32 * 0.05 / 40.0 + } else { + biome.temperature + }; + biome.precipitation && temperature >= 0.15 + } /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve /// at the raw (sky darkened) light level. pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 { From 18f8a6868bb18d843562663835a5298bfdcae1a9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:09:23 +0100 Subject: [PATCH 052/132] Burst a breaking potion into item crumbs and coloured spell particles A thrown potion or experience bottle that breaks sends level events 2002 or 2007 with its colour and the splash sound (1053, 1054). Horizon spawned only eight terrain crumbs, on the server's own side, so a server player saw nothing. --- crates/horizon-client/src/game.rs | 17 ++++- .../src/game/level_particles.rs | 63 +++++++++++++++++++ crates/horizon-client/src/game/potions.rs | 61 +++++------------- 3 files changed, 93 insertions(+), 48 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8b82f7bed..54e017943 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2926,6 +2926,17 @@ impl Game<'_> { pos, data, } => self.smash_dust(pos, data), + // LevelEventHandler 2002 and 2007: a potion's splash. + LevelEvent::LevelEvent { + id: 2002, + pos, + data, + } => self.potion_splash_particles(pos, data, false), + LevelEvent::LevelEvent { + id: 2007, + pos, + data, + } => self.potion_splash_particles(pos, data, true), LevelEvent::LevelEvent { id: id @ 3002..=3005, pos, @@ -2958,6 +2969,8 @@ impl Game<'_> { 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), // LevelEvent.SOUND_PAGE_TURN (a lectern's page). 1043 => Some(("minecraft:item.book.page_turn", 1.0)), + // LevelEvent.SOUND_SPLASH_POTION and its instant twin. + 1053 | 1054 => Some(("minecraft:entity.splash_potion.break", 1.0)), _ => None, }; if let Some((name, volume)) = sound { @@ -2967,12 +2980,12 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } - 1029 | 1030 | 1042 | 1043 | 1044 => { + 1029 | 1030 | 1042 | 1043 | 1044 | 1053 | 1054 => { self.world.random.next_float() * 0.1 + 0.9 } _ => 1.0, }; - if matches!(id, 1029 | 1030) { + if matches!(id, 1029 | 1030 | 1053 | 1054) { // Clients play the anvil sound from its level event; // capturing it also sends a duplicate sound packet. self.audio.play_unshared(name, c, volume, pitch); diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..9fa53eb25 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -3,6 +3,7 @@ //! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax //! off (3004) and scraping (3005). use super::Game; +use horizon_client::items::ItemStack; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; @@ -134,6 +135,68 @@ impl Game<'_> { // Each guest plays it from the global packet. self.audio.play_unshared(sound, at, volume, 1.0); } + /// `LevelEventHandler.potionSplashParticles` (2002 with `Effect`, 2007 + /// with `InstantEffect`): eight splash potion crumbs, and a hundred + /// spell particles in the potion's colour `data`, flung out in a disc. + pub(super) fn potion_splash_particles(&mut self, pos: BlockPos, data: i32, instant: bool) { + let ty = if instant { + ParticleType::InstantEffect + } else { + ParticleType::Effect + }; + // Vec3.atBottomCenterOf. + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ]; + let crumb = self.item_particle(&ItemStack::new("minecraft:splash_potion", 1)); + let r = self.particles.level_random(); + let crumbs: Vec<[f64; 3]> = (0..8) + .map(|_| { + [ + r.next_gaussian() * 0.15, + r.next_double() * 0.2, + r.next_gaussian() * 0.15, + ] + }) + .collect(); + for v in crumbs { + self.particles.add(&crumb, at, v); + } + let channel = |shift: i32| ((data >> shift) & 0xFF) as f32 / 255.0; + let color = [channel(16), channel(8), channel(0)]; + for _ in 0..100 { + let r = self.particles.level_random(); + let dist = r.next_double() * 4.0; + let angle = r.next_double() * std::f64::consts::PI * 2.0; + let velocity = [ + angle.cos() * dist, + 0.01 + r.next_double() * 0.5, + angle.sin() * dist, + ]; + let brightness = 0.75 + r.next_float() * 0.25; + let options = ParticleOptions { + color: [ + color[0] * brightness, + color[1] * brightness, + color[2] * brightness, + 1.0, + ], + scale: dist as f32, + ..ParticleOptions::simple(ty) + }; + self.particles.add( + &options, + [ + at[0] + velocity[0] * 0.1, + at[1] + 0.3, + at[2] + velocity[2] * 0.1, + ], + velocity, + ); + } + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 13eae7d3e..0061fd5d3 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -674,62 +674,31 @@ impl Game<'_> { } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { + let block = [at.x, at.y, at.z].map(|v| v.floor() as i32); if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level - // event 2002) and 3 to 11 experience. - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play( - "minecraft:entity.splash_potion.break", - Some([at.x, at.y, at.z]), - 1.0, - pitch, - ); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - 0x38_5DC6, - ); - self.particles.push(p); - } + // event 2002, its sound 1053) and 3 to 11 experience. + self.level_event_at(2002, block, 0xFF38_5DC6u32 as i32); + self.level_event_at(1053, block, 0); let r = &mut self.world.random; let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0); self.spawn_orbs([at.x, at.y, at.z], value as u32); return; } let lingering = &*stack.item == "minecraft:lingering_potion"; - let event = if lingering { - "minecraft:entity.lingering_potion.break" - } else { - "minecraft:entity.splash_potion.break" - }; - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); + // AbstractThrownPotion.onHit: level event 2007 and sound 1054 for a + // potion with instant effects, 2002 and 1053 otherwise. + let potion = stack.potion().and_then(brewing::potion); + let instant = potion.is_some_and(|d| { + d.effects + .iter() + .any(|(id, ..)| brewing::effect(id).is_some_and(|e| e.instant)) + }); let color = brewing::potion_color(stack.potion()); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - color, - ); - self.particles.push(p); - } + self.level_event_at(if instant { 2007 } else { 2002 }, block, color as i32); + self.level_event_at(if instant { 1054 } else { 1053 }, block, 0); let scale = if lingering { 0.25 } else { 1.0 }; - let Some(def) = stack.potion().and_then(brewing::potion) else { + let Some(def) = potion else { return; }; // Every player in range (`ThrownSplashPotion.applySplash` over From 303281ed09e4236062459aca955c3416a1224dca Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:12:28 +0100 Subject: [PATCH 053/132] Puff a poof where a dead mob's body goes A mob removes its body twenty ticks after dying and tells everyone with entity event 60, which draws twenty poofs about it. Horizon removed dead mobs silently. --- crates/horizon-client/src/game/creatures.rs | 29 +++++++++++++++++++++ crates/horizon-client/src/game/lan.rs | 10 +++++++ crates/horizon-client/src/game/remote.rs | 7 +++++ 3 files changed, 46 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 145717cb3..9f44a4e0b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -525,6 +525,8 @@ impl Game<'_> { _ => Vec::new(), }; let mut guest_events = Vec::new(); + // The mobs whose bodies go this tick: (id, feet, width, height). + let mut gone = Vec::new(); let level_random; { // The level random, lent to the mobs (brain behaviours draw from @@ -597,6 +599,11 @@ impl Game<'_> { let from = events.len(); let kept = m.tick(&w, &mut scratch, &mut events); horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); + // LivingEntity.tickDeath: after twenty ticks the body is removed. + if !kept && !m.removed && !m.alive() && m.death_time >= 20 { + let (width, height) = (f64::from(m.width()), f64::from(m.height())); + gone.push((m.id, m.position, width, height)); + } if let Some(conn) = seen_guest { // ShulkerBullet.finalTarget is the guest's entity: the // bullet homes on it while the projectiles tick, where @@ -655,6 +662,12 @@ impl Game<'_> { } self.mobs.append(&mut mobs); self.died = died; + // ... and entity event 60 goes out as it is: the poof. + for (id, at, width, height) in gone { + let at = [at.x, at.y, at.z]; + self.lan_entity_event(id as i32, 60, at); + self.death_poof(at, width, height); + } self.sync_riders(); self.tick_skeleton_traps(); self.tick_apparition(); @@ -681,6 +694,22 @@ impl Game<'_> { self.handle_mob_events(queued)?; Ok(()) } + /// `LivingEntity.makePoofParticles` (entity event 60) about a mob's box. + pub(super) fn death_poof(&mut self, at: [f64; 3], width: f64, height: f64) { + let options = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Poof, + ); + for _ in 0..20 { + let r = self.particles.level_random(); + let xa = r.next_gaussian() * 0.02; + let ya = r.next_gaussian() * 0.02; + let za = r.next_gaussian() * 0.02; + let x = at[0] + width * (2.0 * r.next_double() - 1.0) - xa * 10.0; + let y = at[1] + height * r.next_double() - ya * 10.0; + let z = at[2] + width * (2.0 * r.next_double() - 1.0) - za * 10.0; + self.particles.add(&options, [x, y, z], [xa, ya, za]); + } + } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let killer = self.last_hurt_by_player.remove(&m.id); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..3478ed6ef 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -952,6 +952,16 @@ impl Game<'_> { host.hub.block_event(pos, b0, b1, state); } let entities = states.as_slice(); + // An entity that left the level since the last tick (a snowball + // that hit) is dropped by the tracker below: its event goes out + // first, as `Level.broadcastEntityEvent` precedes the discard. + let (gone, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.lan_entity_events) + .into_iter() + .partition(|(id, ..)| !entities.iter().any(|e| e.id == *id)); + self.lan_entity_events = later; + for (id, event, at) in gone { + host.hub.entity_event(id, event, at); + } let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { let clock_rate = self.network_clock_rate(); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..64320bd37 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2130,6 +2130,13 @@ impl Game<'_> { { m.health = 0.0; } + // LivingEntity.handleEntityEvent 60: the poof as the dead body goes. + if p.event == 60 + && let Some(m) = self.mobs.iter().find(|m| m.id == p.id as u32) + { + let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); + self.death_poof([at.x, at.y, at.z], w, h); + } if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } From d78238f7651843e1f056a0ecdcfdf4a09adcf8fd Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:14:32 +0100 Subject: [PATCH 054/132] Show the enchanted hit when a melee weapon's enchantments add damage Player.attack shows magic crit particles whenever the enchantments added damage. Horizon showed only the critical hit, for the window's player and for a guest's attack. --- crates/horizon-client/src/game.rs | 23 ++++++++++++++----- crates/horizon-client/src/game/lan.rs | 25 ++++++++++++--------- crates/horizon-client/src/game/lan_pvp.rs | 17 +++++++++----- crates/horizon-client/src/game/levels.rs | 2 +- crates/horizon-client/src/lan/containers.rs | 9 ++++---- 5 files changed, 50 insertions(+), 26 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 30e832eb0..e9add4a82 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1658,7 +1658,7 @@ struct Game<'a> { lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, /// Successful crits (attacking guest, hit entity), queued while the hub is taken. - lan_critical_hits: Vec<(Option, i32)>, + lan_critical_hits: Vec<(Option, i32, bool)>, /// Global level events for every guest (`ServerLevel.globalLevelEvent`). lan_global_events: Vec<(i32, [i32; 3], i32)>, /// `ContainerOpenersCounter`: how many players (the host and the guests) @@ -7602,7 +7602,7 @@ impl Game<'_> { /// strength and whether it is a critical hit): the weapon and effects /// scaled by the attack strength, a mace's smash, the critical hit, then /// enchantments. - pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { + pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); // Riptide's spin replaces the attack damage attribute. let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); @@ -7630,8 +7630,9 @@ impl Game<'_> { amount *= 1.5; } // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. - amount += self.enchant_damage_bonus(target_kind) * scale; - (amount, scale, crit) + let magic_boost = self.enchant_damage_bonus(target_kind) * scale; + amount += magic_boost; + (amount, scale, crit, magic_boost > 0.0) } /// `Player.getAttackStrengthScale(0.5)`. fn attack_strength_scale(&self) -> f32 { @@ -7818,7 +7819,7 @@ impl Game<'_> { pub(super) fn attack_mob(&mut self, index: usize) { let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); - let (amount, scale, crit) = self.melee_damage(&target_kind); + let (amount, scale, crit, magic) = self.melee_damage(&target_kind); let sweep = self.sweep_attack_position(scale, crit); let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale); self.attack_ticks = 0; @@ -7881,6 +7882,18 @@ impl Game<'_> { feet, width, height, + false, + ); + } + // Player.attackVisualEffects: magicCrit when the enchantments added damage. + if magic { + self.critical_hit( + self.lan_acting, + self.mobs[index].id as i32, + feet, + width, + height, + true, ); } if actual > 2.0 { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..f1b14940a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1224,8 +1224,9 @@ impl Game<'_> { self.lan_entity_events.push((id, event, at)); } } - /// `ServerPlayer.crit`: this window's emitter, and an animation for the - /// attacker's client and observers once the hub is back in place. + /// `ServerPlayer.crit` (or `magicCrit` when `magic`): this window's + /// emitter, and an animation for the attacker's client and observers once + /// the hub is back in place. pub(super) fn critical_hit( &mut self, attacker: Option, @@ -1233,16 +1234,18 @@ impl Game<'_> { feet: [f64; 3], width: f64, height: f64, + magic: bool, ) { use horizon_client::particles::{ParticleOptions, ParticleType}; - self.particles.tracking_emitter( - ParticleOptions::simple(ParticleType::Crit), - feet, - width, - height, - ); + let particle = if magic { + ParticleType::EnchantedHit + } else { + ParticleType::Crit + }; + self.particles + .tracking_emitter(ParticleOptions::simple(particle), feet, width, height); if self.audio.capture.is_some() { - self.lan_critical_hits.push((attacker, id)); + self.lan_critical_hits.push((attacker, id, magic)); } } /// Send the tick's level events, sounds and mob animations. @@ -1320,13 +1323,13 @@ impl Game<'_> { seen.insert(m.id, (m.hurt_time, dead, swing)); } host.mob_state.insert(self.dim, seen); - for (attacker, target) in critical_hits { + for (attacker, target, magic) in critical_hits { let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| { host.hub.guest(conn).map(|g| g.entity_id) }) else { continue; }; - host.hub.critical_hit(attacker, target); + host.hub.critical_hit(attacker, target, magic); } } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 8e756b7be..65520221a 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -37,6 +37,8 @@ pub(super) struct Strike { amount: f32, scale: f32, crit: bool, + /// `Player.attack`'s `magicBoost > 0`: the enchantments added damage. + magic: bool, from: [f64; 3], sweep: Option<[f64; 3]>, /// `causeExtraKnockback`: its strength and direction (the attacker's @@ -109,7 +111,7 @@ impl Game<'_> { pub(super) fn pvp_strike(&mut self) -> Option { let p = self.player.as_ref()?; let from = [p.position.x, p.position.y, p.position.z]; - let (amount, scale, crit) = self.melee_damage("minecraft:player"); + let (amount, scale, crit, magic) = self.melee_damage("minecraft:player"); let sweep = self.sweep_attack_position(scale, crit); let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); @@ -125,6 +127,7 @@ impl Game<'_> { amount, scale, crit, + magic, from, sweep, knockback: (strength, xd, zd), @@ -257,7 +260,7 @@ impl Game<'_> { } else { Default::default() }; - if hurt && s.crit { + if hurt && (s.crit || s.magic) { let target = match victim { Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)), Victim::Guest(conn) => host @@ -267,13 +270,17 @@ impl Game<'_> { }; if let Some((id, p)) = target { let d = p.dimensions; - self.critical_hit( - s.attacker, - id, + let (feet, width, height) = ( [p.position.x, p.position.y, p.position.z], f64::from(d.width), f64::from(d.height), ); + if s.crit { + self.critical_hit(s.attacker, id, feet, width, height, false); + } + if s.magic { + self.critical_hit(s.attacker, id, feet, width, height, true); + } } } // `Enchantment.doPostAttack`: thorns hurt the attacking player. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 8d2e0a4a2..12a2184a4 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -75,7 +75,7 @@ pub(super) struct Parked { lan_events: Vec<(i32, [i32; 3], i32, Option)>, lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, - lan_critical_hits: Vec<(Option, i32)>, + lan_critical_hits: Vec<(Option, i32, bool)>, /// Only the per-level parts of these are used (`swap_level`). anims: BlockEntityAnims, raiding: Raiding, diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 002f95cbb..d0f8126b0 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -120,12 +120,13 @@ impl Hub { ); } - /// `ServerPlayer.crit`: send the victim's animation to the players tracking - /// the attacker and the attacker themselves (`sendToTrackingPlayersAndSelf`). - pub fn critical_hit(&self, attacker: i32, target: i32) { + /// `ServerPlayer.crit` (`magicCrit` when `magic`): send the victim's + /// animation to the players tracking the attacker and the attacker + /// themselves (`sendToTrackingPlayersAndSelf`). + pub fn critical_hit(&self, attacker: i32, target: i32, magic: bool) { let body = C::Animate(play::Animate { id: target, - action: 1, + action: if magic { 2 } else { 1 }, }) .encode(); for g in self.guests.iter().filter(|g| { From 591b7b74daab63df7e042a7d270c2490960f39a9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:15:10 +0100 Subject: [PATCH 055/132] Predict the sort and tweak clicks on a server like an ordinary click --- crates/horizon-client/src/game/remote.rs | 20 -------------------- crates/horizon-client/src/game/tweaks.rs | 3 +-- 2 files changed, 1 insertion(+), 22 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..3c333c904 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4791,26 +4791,6 @@ impl Game<'_> { })); } } - /// A `ContainerClick` on game slot `internal` of the server's open menu - /// (`input` is the ContainerInput ordinal). False when the menu has no - /// such slot. - pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool { - let (container, menu) = self.remote_menu(); - let slot = Self::menu_slot_index(&menu, internal); - let Some(slot) = slot else { return false }; - let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); - let state = self.remote.as_ref().map_or(0, |r| r.state_id); - self.send(S::ContainerClick(play::ContainerClick { - container, - state, - slot: slot as i16, - button, - input, - changed: Vec::new(), - carried, - })); - true - } /// The server's open menu is the inventory or a chest-like container /// (chests, barrels, ender chests: `generic_9xN`; shulker boxes). pub(super) fn remote_storage_open(&self) -> bool { diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index cec83e248..648073874 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -70,8 +70,7 @@ impl Game<'_> { /// One ordinary click on a game slot. False when nothing took it. pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool { if self.remote.is_some() { - let ordinal = super::remote::input_ordinal(input); - return self.remote_slot_click(slot, button as i8, ordinal); + return self.remote_menu_ops(&[(Some(slot), button, input)]); } if !self.menu_click(Some(slot), button, input) { return false; From df045f1e9a417b72543e4288e4deabf932473164 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:22:13 +0100 Subject: [PATCH 056/132] CI parity: test the head merged into main A head tested alone keeps failing harnesses that main already fixed. Since 10-25 evening, 9 of 21 failed PR parity jobs failed only on such fixes: server_knockback (heads without #2114, 7 times), mob_ai's oracle heap (without #2270), save_roundtrip (without #2212). #2160 needed 4 parity runs this way. The job now merges main's current tip into the head and selects harnesses against that main commit, so only the pull request's own changes count. A branch that doesn't change the runner scripts or the selection gets main's, which replaces the two steps that copied main's vanilla-data.sh and parity.py in by hand. A head that conflicts with main is tested alone, with a warning. The job summary names the main commit, and the check is still `parity / parity` on the head. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parity.yml | 88 ++++++++++++------------------------ docs/release-flow.md | 9 ++-- 2 files changed, 36 insertions(+), 61 deletions(-) diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index 1fc31d8cb..9f678b43b 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -26,35 +26,46 @@ jobs: steps: - uses: actions/checkout@v4 with: - # The commit the event names: a fork's later pushes need another run-parity label. + # The commit the event names: a fork's later pushes need another run-parity label. The next step merges + # main into it. ref: ${{ inputs.head }} fetch-depth: 0 persist-credentials: false # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. clean: false + - name: The head merged into main (what merging it would land) + id: merge + env: + BASE_SHA: ${{ inputs.base }} + HEAD_SHA: ${{ inputs.head }} + run: | + # Harness fixes and game fixes that reached main since the branch was made then apply here too: a head + # tested alone failed harnesses already fixed on main (server_knockback before #2114, mob_ai's heap before + # #2270, save_roundtrip before #2212). Selection then compares with this main, so it sees only the pull + # request's own changes. A head that conflicts with main is tested alone. + set -euo pipefail + git merge --abort 2>/dev/null || true + git fetch -q --no-tags origin +refs/heads/main:refs/remotes/origin/main + main=$(git rev-parse origin/main) + if git -c user.name=parity -c user.email=parity@localhost merge -q --no-edit --no-ff "$main" >/dev/null 2>&1; then + echo "base=$main" >> "$GITHUB_OUTPUT" + echo "Tested: head ${HEAD_SHA:0:9} merged into main ${main:0:9}" | tee -a "$GITHUB_STEP_SUMMARY" + else + git merge --abort + echo "base=$BASE_SHA" >> "$GITHUB_OUTPUT" + echo "::warning::head ${HEAD_SHA:0:9} conflicts with main ${main:0:9}: tested alone, without main's fixes" + echo "Tested: head ${HEAD_SHA:0:9} alone (it conflicts with main ${main:0:9})" | tee -a "$GITHUB_STEP_SUMMARY" + fi - uses: dtolnay/rust-toolchain@stable - name: Tools from the runner run: bash tools/ci/runner-env.sh - name: Vanilla data, and resources prepared by this preparer - env: - BASE_SHA: ${{ inputs.base }} - run: | - # main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on - # the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own. - set -euo pipefail - if git rev-parse --verify -q origin/main >/dev/null \ - && git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then - git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh" - bash "$RUNNER_TEMP/vanilla-data.sh" - else - bash tools/ci/vanilla-data.sh - fi + run: bash tools/ci/vanilla-data.sh - name: The prepared output is the one the preparer's OUTPUT_VERSION says env: - BASE_SHA: ${{ inputs.base }} + BASE_SHA: ${{ steps.merge.outputs.base }} run: | - # The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither - # the tool nor the number, so there is nothing to check. + # A head made before OUTPUT_VERSION (#1947) that conflicts with main has neither the tool nor the number. if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then echo "This head's preparer has no OUTPUT_VERSION: nothing to check" exit 0 @@ -65,47 +76,8 @@ jobs: - name: The harnesses this change can affect env: PARITY_HOSTS: '' - BASE_SHA: ${{ inputs.base }} - run: | - # main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a - # branch made before a better selection landed gets it too; the head's own runner then runs those - # harnesses. A branch that changes the selection itself selects with its own code. - set -euo pipefail - own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner - fork_point=$(git merge-base "$BASE_SHA" HEAD) - if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then - own - exit - fi - had_reach=$(git ls-files tools/parity_reach.py) - git show origin/main:tools/parity.py > tools/parity.py - git show origin/main:tools/parity_reach.py > tools/parity_reach.py - status=0 - python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$? - git checkout -- tools/parity.py - if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi - cat .local/parity-selection.txt - if [ "$status" != 0 ]; then - echo "main's selection failed: the head's own selection runs" - own - exit - fi - names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true) - # The summary line says how many would run: a count that doesn't match the names read (a format change) - # must not let the job pass untested. - expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p') - count=$(printf '%s' "$names" | grep -c . || true) - if [ -z "$expected" ] || [ "$expected" != "$count" ]; then - echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs" - own - exit - fi - if [ "$count" = 0 ]; then - echo "Nothing to run." - exit 0 - fi - # shellcheck disable=SC2086 - python3 tools/parity.py $names --timeout 2400 + BASE_SHA: ${{ steps.merge.outputs.base }} + run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner - name: Logs of the failed harnesses if: failure() uses: actions/upload-artifact@v4 diff --git a/docs/release-flow.md b/docs/release-flow.md index ce7934824..b0d435c29 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -32,6 +32,12 @@ copy is: the Mac mini, his Linux desktop and playhorizon (below). Their runners between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes stand. +The job tests the pull request's head merged into main's current tip, which is what merging it would land: harness +and game fixes that reached main after the branch was made apply to it too, and an old branch runs main's runner +scripts and selection unless it changes them. The base for the selection is that main commit, so only the pull +request's own changes count. The job summary names the main commit. A head that conflicts with main is tested +alone, with a warning. The check is still reported on the head. + 1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH (Homebrew and `java_home` on the Mac; on Linux what `linux-runner.sh` pinned, else nixpkgs), and sccache when the machine has it. @@ -50,9 +56,6 @@ stand. modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to `Cargo.lock` or `research-lock.json` affects every harness. Each harness has 25 minutes, the job 45. - The selection runs with main's `tools/parity.py` and `tools/parity_reach.py` (`--changed --list`), so a - branch made before a better selection landed gets it too, and the head's own `parity.py` then runs the named - harnesses. A branch that changes either file selects with its own code. Failed harnesses' logs are uploaded as the `parity-logs` artifact. From e82fa3d957b70971510ea267375e9160859ede51 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:27:34 +0100 Subject: [PATCH 057/132] parity: retry a known flaky harness once, and say so tools/parity_hosts.json's new `known_flaky` lists the harnesses that still flake for a cause not fixed yet, each with its reason: dedicated_server (its Java client's 1.5 s step timer), remote_fireball (wall-clock sampling) and world_reopen. One of them that fails runs once more from scratch, and a pass then counts. Every retry prints a RETRIED line at the end of the run and in the CI job's summary, so a harness that passes only on its retry stays visible on PR parity and parity-main alike. The existing fresh rerun of a failure that reused oracle results is reported the same way. A known flaky harness skips that rerun and keeps reusing oracle results, because flaking doesn't mean its cached oracle runs were wrong. Repeated runs (--repeat, --flake-check) are never retried. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 7 ++++ tests/test_parity_runner.py | 84 +++++++++++++++++++++++++++++++++++-- tools/parity.py | 74 +++++++++++++++++++++++++++++--- tools/parity_hosts.json | 5 +++ 4 files changed, 161 insertions(+), 9 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 27505d9de..c0cf3aec5 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -133,6 +133,13 @@ when named and in the nightly audit (`--all`). LAN writes `results.json` with the host mode and each result beside its screenshots and logs. A skipped case is recorded explicitly and does not count as passing coverage. +`known_flaky` in `tools/parity_hosts.json` lists harnesses that fail now and then for a +cause not fixed yet, each with its reason. One that fails runs once more from +scratch, and a pass then counts. `parity.py` prints a `RETRIED` line for it +in its summary and in the CI job's summary (PR parity and parity-main), so the +flake stays visible. No other harness gets this retry. Fix the cause, then take +the harness off the list. + The game-binary fixture audit keeps these complementary direct rule tests: - `command_harness.rs`: command feedback, styled spans and result callbacks, diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 518f23ba4..49a88f0b1 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -290,9 +290,6 @@ class OracleReuseTests(unittest.TestCase): self.assertEqual(self.output.read_text(), "b") -if __name__ == "__main__": - unittest.main() - class LargeOutputTests(unittest.TestCase): def test_a_pass_clears_only_its_own_directory(self): @@ -323,3 +320,84 @@ class LargeOutputTests(unittest.TestCase): listing.write_text(f"{own / 'server.txt'}\n{own / 'client.txt'}\n") parity.clear_large_outputs("state_provider#2", trace) self.assertEqual(sorted(path.name for path in own.iterdir()), ["report.json", "server.txt"]) + + +class FakeExecutor: + """Runs nothing: each start of a harness takes the next status from its script, a list.""" + name, dead, max_peak = "fake", False, None + + def __init__(self): + self.started, self.finished = [], [] + + def free(self): + return 1 + + def accepts(self, name): + return True + + def fits(self, expected, only_here=True): + return True + + def start(self, label, script, reuse, expected, shard=None): + self.started.append((label, reuse)) + self.finished.append((label, {"status": script.pop(0), "seconds": 1.0, "dependencies": []})) + return True + + def poll(self): + finished, self.finished = self.finished, [] + return finished + + +class KnownFlakyTests(unittest.TestCase): + def run_harnesses(self, scripts, flaky, rounds=None): + executor = FakeExecutor() + state = {"harnesses": {name: {"status": "pass", "oracle_reuse": True} for name in scripts}} + with tempfile.TemporaryDirectory() as tmp, mock.patch.multiple(parity, STATE_DIR=Path(tmp), SHARED=Path(tmp)), \ + mock.patch.object(parity, "save_state"), mock.patch.object(parity, "time") as clock: + clock.monotonic.return_value = 0.0 + results, _ = parity.run(scripts, state, None, "env", [executor], True, rounds, flaky) + return results, executor.started + + def test_a_known_flaky_failure_runs_once_more_from_scratch_and_says_so(self): + results, started = self.run_harnesses({"dedicated_server": ["fail", "pass"]}, {"dedicated_server": "timer"}) + self.assertEqual(results["dedicated_server"]["status"], "pass") + self.assertEqual(results["dedicated_server"]["retried"], "known flaky") + # The first run reused oracle results; a known flaky harness doesn't lose that by flaking. + self.assertTrue(results["dedicated_server"]["oracle_reuse"]) + self.assertEqual(started, [("dedicated_server", True), ("dedicated_server", False)]) + + def test_only_once(self): + results, started = self.run_harnesses({"dedicated_server": ["fail", "fail"]}, {"dedicated_server": "timer"}) + self.assertEqual(results["dedicated_server"]["status"], "fail") + self.assertEqual(len(started), 2) + + def test_other_harnesses_keep_only_the_reused_oracle_retry(self): + results, started = self.run_harnesses({"food": ["fail", "pass"]}, {"dedicated_server": "timer"}) + self.assertEqual((results["food"]["status"], results["food"]["retried"]), ("pass", "reused oracle results")) + self.assertEqual(started, [("food", True), ("food", False)]) + self.assertFalse(results["food"]["oracle_reuse"]) + + def test_repeated_runs_get_no_retry(self): + results, started = self.run_harnesses({"dedicated_server": ["pass", "fail"]}, {"dedicated_server": "timer"}, + rounds={"dedicated_server": 2}) + self.assertEqual((results["dedicated_server"]["status"], len(started)), ("fail", 2)) + + def test_retries_reach_the_job_summary(self): + with tempfile.TemporaryDirectory() as tmp: + summary = Path(tmp) / "summary.md" + with mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": str(summary)}), \ + mock.patch("builtins.print"): + parity.report_retries({"dedicated_server": {"status": "pass", "retried": "known flaky"}, + "food": {"status": "pass"}}, {"dedicated_server": "timer"}) + text = summary.read_text() + self.assertIn("RETRIED dedicated_server: failed, then passed on its one retry (known flaky: timer", text) + self.assertNotIn("food", text) + + def test_the_known_flaky_list_has_a_reason_per_harness(self): + flaky = parity.known_flaky(parity.host_config()) + self.assertTrue(all(isinstance(reason, str) and len(reason) > 20 for reason in flaky.values())) + self.assertTrue(set(flaky) <= {parity.base_name(name) for name in parity.harnesses()}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/parity.py b/tools/parity.py index dbff8c146..a5f7f2db1 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -26,6 +26,11 @@ change costs only the Rust side. A harness that fails while reusing oracle results is rerun fresh, and stops reusing them if it then passes. --all and --fresh never reuse them. +A harness listed in parity_hosts.json's "known_flaky" (each with its reason) +that fails runs once more from scratch instead, and a pass then counts. Every +retry is printed as a RETRIED line in the summary and in the CI job's summary. +Fix the cause, then take the harness off the list: nothing else gets this retry. + Harness probes build into .local/parity-target with release optimisations but without LTO and with 16 codegen units (`PROFILE` below), which builds in seconds instead of minutes. Rust does not let those settings change results: @@ -1014,11 +1019,26 @@ def harness_of(label): return label.split("~")[0] -def run(selected, state, hasher, environment_digest, executors, reuse_oracles, rounds=None): +def keep_first_log(label): + """Move a harness's log aside before its retry writes a new one; returns where it went.""" + log = STATE_DIR / "logs" / f"{label}.log" + kept = log.with_name(f"{label}.first-run.log") + try: + log.replace(kept) + except OSError: + return log # a remote host's run: its log stays on that machine + return kept + + +def run(selected, state, hasher, environment_digest, executors, reuse_oracles, rounds=None, known_flaky=None): """Run the selected harnesses on the executors. rounds: how many times each must run (default once); its runs - must agree, and a harness that both passes and fails is reported as flaky and recorded as failing.""" + must agree, and a harness that both passes and fails is reported as flaky and recorded as failing. + known_flaky ({name: reason}, tools/parity_hosts.json): a harness listed there that fails its single round runs + once more, from scratch; its record keeps `retried` (the first run's log is kept beside its own).""" records = state["harnesses"] rounds = rounds or {} + known_flaky = known_flaky or {} + second_chance = set() # known flaky harnesses that already failed once in this run # Longest first, so the slow harnesses don't start last; a harness's later rounds after its first. queue = sorted((name if index == 1 else f"{name}~{index}" for name in selected for index in range(1, rounds.get(name, 1) + 1)), key=lambda label: (-records.get(harness_of(label), {}).get("seconds", 1e9), label)) @@ -1041,7 +1061,9 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r if pick is None: break name = harness_of(pick) - reuse = reuse_oracles and records.get(name, {}).get("oracle_reuse", True) and pick not in retried + # A retry runs the oracle again too: it may be the side that failed (mob_ai's heap). + reuse = reuse_oracles and records.get(name, {}).get("oracle_reuse", True) and pick not in retried \ + and name not in second_chance if not executor.start(pick, selected[name], reuse, records.get(name, {}).get("peak_bytes", DEFAULT_MEMORY), SHARDS.get(name)): break @@ -1066,9 +1088,12 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r queue.insert(0, label) continue passed = record["status"] == "pass" - if not passed and reused and label == name and records.get(name, {}).get("status") != "fail": + flaky_retry = rounds.get(name, 1) == 1 and base_name(name) in known_flaky + if not passed and reused and label == name and records.get(name, {}).get("status") != "fail" \ + and not flaky_retry: # A new failure might come from a reused oracle result: run it again from scratch. Later rounds reuse - # what the first just validated, so their failures count (a flaky harness). + # what the first just validated, so their failures count (a flaky harness). A known flaky harness + # gets its own retry below instead, which keeps reusing oracle results afterwards. retried.add(label) queue.insert(0, label) print(f"retry {label} without reused oracle results", flush=True) @@ -1086,8 +1111,19 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r if len(done[name]) < rounds.get(name, 1): continue runs = done.pop(name) + if runs[0]["status"] != "pass" and flaky_retry and name not in second_chance: + second_chance.add(name) + first_log = keep_first_log(label) + print(f"RETRIED {name}: failed, and it is a known flaky harness ({known_flaky[base_name(name)]}): " + f"running it once more (first run's log: {first_log})", flush=True) + queue.insert(0, label) + continue record = dict(runs[0], status="pass" if all(run["status"] == "pass" for run in runs) else "fail", rounds=len(runs)) + if name in second_chance: + record["retried"] = "known flaky" + elif label in retried: + record["retried"] = "reused oracle results" if len({run["status"] for run in runs}) > 1: record["flaky"] = [run["status"] for run in runs] print(f"FLAKY {name}: {', '.join(record['flaky'])} in {len(runs)} runs", flush=True) @@ -1309,12 +1345,36 @@ def platform_skips(config): return dict(config.get("linux_only", {})) +def known_flaky(config): + """Harnesses tools/parity_hosts.json lists as failing now and then for a cause not fixed yet: one that fails runs + once more, and passing then counts, reported as RETRIED. {name: reason}""" + return dict(config.get("known_flaky", {})) + + def named_only(config): """Harnesses tools/parity_hosts.json keeps out of every automatic selection (--changed, --failed, the default, --flake-check): they run only when named or with --all, the nightly audit. {name: reason}""" return dict(config.get("named_only", {})) +def report_retries(results, flaky): + """Say loudly which harnesses needed their one retry (a known flaky one, or one that failed with reused oracle + results), here and in the CI job's summary: a pass on the retry counts, so this is where flakes stay visible.""" + def why(name, record): + if record["retried"] == "known flaky": + return (f"known flaky: {flaky.get(base_name(name), '?')}; first run's log: " + f"{STATE_DIR / 'logs' / (name + '.first-run.log')}") + return "its first run reused oracle results; it no longer reuses them" if record["status"] == "pass" else \ + "its first run reused oracle results" + lines = [f"RETRIED {name}: failed, then {'passed' if record['status'] == 'pass' else 'failed again'} on its one " + f"retry ({why(name, record)})" for name, record in sorted(results.items()) if record.get("retried")] + for line in lines: + print(line, flush=True) + if lines and os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary: + summary.write("### Harnesses that failed once, then ran again\n" + "".join(f"- {line}\n" for line in lines)) + + def finished_run(failed): """Record that this run completed, for tools/gate.py: a crashed runner never writes it.""" STATE_DIR.mkdir(parents=True, exist_ok=True) @@ -1463,7 +1523,8 @@ def main(): reuse_oracles = not (args.fresh or args.all) executors = [*remotes, LocalExecutor(jobs, int(memory_available() * 0.75), args.timeout, REMOTE_LOCAL_PEAK if remotes and args.jobs is None else None)] - results, elapsed = run(selected, state, hasher, environment_key(hasher), executors, reuse_oracles, rounds) + results, elapsed = run(selected, state, hasher, environment_key(hasher), executors, reuse_oracles, rounds, + known_flaky(config)) finally: for executor in remotes: executor.stop() @@ -1471,6 +1532,7 @@ def main(): failed = sorted(name for name, record in results.items() if record["status"] != "pass") finished_run(failed) print(f"\n{len(results) - len(failed)} passed, {len(failed)} failed in {elapsed / 60:.1f} min.") + report_retries(results, known_flaky(config)) for index, name in enumerate(failed): log = STATE_DIR / 'logs' / (name + '.log') print(f" {name}: {log}") diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index b56106e4d..42b9a46fd 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -42,5 +42,10 @@ "linux_only": {}, "named_only": { "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)" } } From f312aae7dbf6358093ce27906311c4416446c2e1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:29:22 +0100 Subject: [PATCH 058/132] Name the potion, cloud or thrower in magic death messages --- crates/horizon-client/src/game/combat.rs | 47 ++++++++++++- .../src/game/commands/world_cmds.rs | 9 +++ crates/horizon-client/src/game/creatures.rs | 67 ++++++++++++++----- crates/horizon-client/src/game/dispenser.rs | 2 +- crates/horizon-client/src/game/dragon.rs | 5 +- crates/horizon-client/src/game/fangs.rs | 13 +++- crates/horizon-client/src/game/potions.rs | 48 +++++++++++-- 7 files changed, 164 insertions(+), 27 deletions(-) diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 6e1d5d82b..22d5c7d8f 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -1,7 +1,7 @@ //! The player's `CombatTracker`: the damage taken lately, who dealt it and //! where the player fell from, turned into the vanilla death message. use super::{Game, chat::PLAYER_NAME}; -use horizon_client::{health::HealthEvent, motion::MotionEvent, text::Text}; +use horizon_client::{health::HealthEvent, lang, motion::MotionEvent, text::Text}; struct Entry { damage_type: String, @@ -10,6 +10,9 @@ struct Entry { fall_distance: f32, /// The causing entity: its id (for comparisons) and display name. attacker: Option<(u32, Text)>, + /// The direct entity's display name when no entity caused the damage + /// (`DamageSource.directEntity`: a potion with no thrower, a cloud). + direct: Option, } #[derive(Default)] pub(super) struct CombatTracker { @@ -19,6 +22,8 @@ pub(super) struct CombatTracker { /// Attackers of damage dealt this tick, claimed by the matching /// `RecordedDamage` event. pending: Vec<(String, (u32, Text))>, + /// `pending` for a direct entity with no causing entity: only its name. + pending_direct: Vec<(String, Text)>, /// `LivingEntity.lastHurtByMob` and its timestamp (the kill credit). last_hurt_by: Option<((u32, Text), i64)>, /// The mob the player last hurt (`getLastHurtMob`) and when. @@ -66,6 +71,14 @@ impl Game<'_> { .pending .push((damage_type.to_owned(), (id, name))); } + /// The `DamageSource.directEntity` of the next `damage_type` damage when + /// nothing caused it (a splash potion nobody threw): the death message + /// names it instead (`getLocalizedDeathMessage`). It is no kill credit. + pub(super) fn note_direct_entity(&mut self, damage_type: &str, name: Text) { + self.combat + .pending_direct + .push((damage_type.to_owned(), name)); + } /// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the /// source's `DamageEffects` (`Player.getHurtSound`). pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) { @@ -94,6 +107,15 @@ impl Game<'_> { .iter() .position(|(t, _)| *t == name) .map(|i| self.combat.pending.remove(i).1); + let direct = match attacker { + Some(_) => None, + None => self + .combat + .pending_direct + .iter() + .position(|(t, _)| *t == name) + .map(|i| self.combat.pending_direct.remove(i).1), + }; let (fall_location, fall_distance) = self.fall_location(); let now = self.world.game_time; if let Some(a) = &attacker { @@ -111,10 +133,12 @@ impl Game<'_> { fall_location, fall_distance, attacker, + direct, }); self.combat.last_damage = now; } self.combat.pending.clear(); + self.combat.pending_direct.clear(); self.combat.fall_before = self.player.as_ref().map_or(0.0, |p| p.fall_distance); } /// `FallLocation.getCurrentFallLocation` and the fall distance so far. @@ -224,6 +248,7 @@ impl Game<'_> { let entries = std::mem::take(&mut self.combat.entries); let killing = entries.last().expect("checked above"); let killer = killing.attacker.clone(); + let direct = killing.direct.clone(); if def.1 == "fall_variants" && let Some(knock) = knock.and_then(|i| entries.get(i)) { @@ -248,15 +273,33 @@ impl Game<'_> { .append(Text::literal("]")); return Text::translate(&format!("{key}.message"), &[me, link]); } + // `getLocalizedDeathMessage`: the causing entity's name, or the + // direct entity's when nothing caused the damage. if let Some((_, name)) = killer { return Text::translate(&key, &[me, name]); } + if let Some(name) = direct { + return Text::translate(&key, &[me, name]); + } // getKillCredit: the last mob that hurt the player in the past 100 ticks. if let Some(((_, name), at)) = &self.combat.last_hurt_by && self.world.game_time - at <= 100 { return Text::translate(&format!("{key}.player"), &[me, name.clone()]); } - Text::translate(&key, &[me]) + killerless_message(&key, me) } } +/// A death message with no entity behind it. One that names a second actor +/// (`%2$s`) has nobody to name here, so it falls back to its plain sibling +/// (`indirectMagic` to `magic`, anything else to `generic`) instead of +/// showing the raw template. +fn killerless_message(key: &str, me: Text) -> Text { + if key == "death.attack.indirectMagic" { + return Text::translate("death.attack.magic", &[me]); + } + if lang::get(key).contains("%2$s") { + return Text::translate("death.attack.generic", &[me]); + } + Text::translate(key, &[me]) +} diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 687eb3f88..15fbbe017 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -146,6 +146,15 @@ impl Game<'_> { }; let hurt = match target { Target::Player => { + // `DamageSource(type, by)`: the death message names `by`. + match by { + Some(Target::Mob(i)) => self.note_attacker(&ty, i), + Some(t @ (Target::Player | Target::Guest(_))) => { + let name = self.target_name(t); + self.note_direct_entity(&ty, name); + } + _ => {} + } if self.creative || self.spectator() { false } else if let Some(player) = self.player.as_mut() { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index be8480c27..e5d7660da 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -18,6 +18,7 @@ use horizon_client::{ spawning::{self, BiomeFacts}, }, projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}, + text::Text, }; use horizon_core::{ geometry::{Aabb, Vec3, traverse_blocks}, @@ -1546,11 +1547,33 @@ impl Game<'_> { pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { self.mob_hits_player(amount, from, kind); } + /// Damage whose causing mob is known (`cause`, or none): not guessed + /// from the mob nearest to `from`. + pub(super) fn mob_hits_player_caused( + &mut self, + amount: f32, + from: [f64; 3], + kind: &str, + cause: Option, + ) { + self.hit_player(amount, from, kind, Some(cause)); + } pub(super) fn mob_hits_player( &mut self, amount: f32, from: [f64; 3], damage_type: &str, + ) -> bool { + self.hit_player(amount, from, damage_type, None) + } + /// `known_cause` is the source's causing mob when the caller knows it + /// (`Some(None)`: none); `None` takes the mob nearest to `from`. + fn hit_player( + &mut self, + amount: f32, + from: [f64; 3], + damage_type: &str, + known_cause: Option>, ) -> bool { // ServerPlayer.canHarmPlayer refused another player's projectile. if self.creative || self.combat.refuse_player_hit { @@ -1566,20 +1589,22 @@ impl Game<'_> { let blocking = self.player_blocking(Some(from), damage_type, false); let raised = blocking.is_some(); // Melee: the attacker stands at `from` (another player's hit has no mob behind it). - let attacker = (!projectile && damage_type != "minecraft:player_attack") - .then(|| { - self.mobs - .iter() - .filter(|m| m.alive()) - .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| { - (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2) - }; - d(a).total_cmp(&d(b)) - }) - .map(|m| m.id) - }) - .flatten(); + let attacker = known_cause.unwrap_or_else(|| { + (!projectile && damage_type != "minecraft:player_attack") + .then(|| { + self.mobs + .iter() + .filter(|m| m.alive()) + .min_by(|a, b| { + let d = |m: &horizon_client::mobs::Mob| { + (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2) + }; + d(a).total_cmp(&d(b)) + }) + .map(|m| m.id) + }) + .flatten() + }); // The causing entity for the death message. let owner = self.combat.projectile_owner.take(); if let Some(a) = attacker.or(owner) { @@ -2402,8 +2427,18 @@ impl Game<'_> { if d2 < 16.0 && !self.creative { let scale = 1.0 - d2.sqrt() / 4.0; let t = (f64::from(*ticks) * scale + 0.5) as i32; - if let Some(owner) = self.combat.projectile_owner { - self.note_attacker("minecraft:indirect_magic", owner); + // indirectMagic(potion, owner): the thrower, or the + // potion itself when it has none. + let owner = self + .combat + .projectile_owner + .filter(|id| self.mob_display_name(*id).is_some()); + match owner { + Some(owner) => self.note_attacker("minecraft:indirect_magic", owner), + None => self.note_direct_entity( + "minecraft:indirect_magic", + Text::translate("entity.minecraft.splash_potion", &[]), + ), } match *effect { "minecraft:instant_damage" => self.hurt_player_by( diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 61725c6ab..f902f1c05 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -982,7 +982,7 @@ impl Game<'_> { | "minecraft:lingering_potion" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); shot.shoot(&mut own, dir, power, uncertainty); - self.launch_thrown(one, at, shot.velocity); + self.launch_thrown(one, at, shot.velocity, None); } "minecraft:firework_rocket" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..2338c14f8 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2157,11 +2157,14 @@ impl Game<'_> { } /// Damage from the dragon, which is its causing entity /// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the - /// death message names it. + /// death message names it, or the cloud once the dragon is gone. fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) { if let Some(id) = self.dragon.as_ref().map(|d| d.id) { let name = Text::translate("entity.minecraft.ender_dragon", &[]); self.note_named_attacker(damage_type, id, name); + } else if damage_type == "minecraft:indirect_magic" { + let name = Text::translate("entity.minecraft.area_effect_cloud", &[]); + self.note_direct_entity(damage_type, name); } self.hurt_player_by(damage_type, amount); } diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index aed692649..2f7abdfd4 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -71,12 +71,23 @@ impl Game<'_> { let b = horizon_core::geometry::Aabb::new(lo, hi); // Every player in the box, the server's players too. let pos = f.pos; + // `EvokerFangs.dealDamageTo`: indirectMagic(fangs, owner) while the + // owner lives, plain magic (nobody to name) once it is gone. + let owner = self + .mobs + .iter() + .any(|m| m.id == f.owner && m.alive()) + .then_some(f.owner); let bite = move |g: &mut Self| { if let Some(p) = g.player_view() && p.alive && p.bounds.intersects(b) { - g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic"); + let kind = match owner { + Some(_) => "minecraft:indirect_magic", + None => "minecraft:magic", + }; + g.mob_hits_player_caused(6.0, pos, kind, owner); } }; bite(self); diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 2ccfd4116..a91c550ad 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -12,6 +12,7 @@ use horizon_client::{ hud_layout, hud_overlays, inventory_effects, items::ItemStack, mesher::Vertex, + text::Text, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -26,6 +27,9 @@ pub(super) struct ThrownPotion { position: Vec3, velocity: Vec3, age: u32, + /// `Projectile.getOwner`'s display name: the player who threw it (none + /// for a dispenser's). + owner: Option, } /// A mob's effect ids carry the `minecraft:` namespace. fn mob_effect_id(id: &str) -> Option<&'static str> { @@ -47,7 +51,13 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). - pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { + pub(super) fn launch_thrown( + &mut self, + stack: ItemStack, + position: Vec3, + velocity: Vec3, + owner: Option, + ) { self.potions.thrown.push(ThrownPotion { id: 0, stack, @@ -55,6 +65,7 @@ impl Game<'_> { position, velocity, age: 0, + owner, }); } } @@ -135,6 +146,7 @@ impl PotionState { position: at, velocity, age: 0, + owner: None, }); } /// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows. @@ -237,6 +249,7 @@ impl Game<'_> { }, Vec3::new(eye[0], eye[1] - 0.1, eye[2]), v, + Some(self.player_display_text()), ); self.swing_arm(); self.consume_held(); @@ -548,15 +561,15 @@ impl Game<'_> { } } if let Some(p) = hit { - landed.push((t.stack.clone(), p)); + landed.push((t.stack.clone(), p, t.owner.clone())); return false; } t.position = next; t.age < 1200 && t.position.y > -128.0 }); self.potions.thrown = thrown; - for (stack, at) in landed { - self.splash(&stack, at); + for (stack, at, owner) in landed { + self.splash(&stack, at, owner); } } /// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which @@ -664,6 +677,7 @@ impl Game<'_> { effects: &'static [(&'static str, i32, i32)], at: Vec3, scale: f64, + source: &Text, ) { if let Some(p) = self.player.as_ref() { let center = Vec3::new( @@ -679,6 +693,18 @@ impl Game<'_> { let instant = brewing::effect(id).is_some_and(|e| e.instant); if instant { if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + // HealOrHarmMobEffect.applyInstantaneousEffect with + // a source: indirectMagic, not plain magic. + let a = match a { + EffectAction::Hurt("minecraft:magic", amount) => { + self.note_direct_entity( + "minecraft:indirect_magic", + source.clone(), + ); + EffectAction::Hurt("minecraft:indirect_magic", amount) + } + a => a, + }; self.apply_effect_action(a); } } else { @@ -694,7 +720,7 @@ impl Game<'_> { } } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3) { + fn splash(&mut self, stack: &ItemStack, at: Vec3, owner: Option) { if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level // event 2002) and 3 to 11 experience. @@ -755,7 +781,17 @@ impl Game<'_> { }; // Every player in range (`ThrownSplashPotion.applySplash` over // `LivingEntity`s, the players among them). - self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); + // Instant damage is indirectMagic(potion or cloud, owner), which the + // death message names by the owner, else by the potion or cloud. + let source = owner.unwrap_or_else(|| { + let entity = if lingering { + "entity.minecraft.area_effect_cloud" + } else { + "entity.minecraft.splash_potion" + }; + Text::translate(entity, &[]) + }); + self.for_each_player(|g| g.splash_on_player(def.effects, at, scale, &source)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); From 08cd05ed6eae200558f6f3fac3a24f2e6d0be181 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:30:05 +0100 Subject: [PATCH 059/132] Make the Entity Shadows option turn shadows off --- crates/horizon-client/src/game.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 671ba6cc9..5f25e215c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7212,7 +7212,12 @@ impl Game<'_> { self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). self.mark_translucent_entity(out.len(), "minecraft:entity_shadow"); - if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() { + let shadow_sprite = self + .settings + .entity_shadows + .then(|| self.gui.atlas.sprites.get("misc/shadow").copied()) + .flatten(); + if let Some(sprite) = shadow_sprite { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; From f9b8b40a7dfd59ed5877c2333d8e43afcf8a6484 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:30:13 +0100 Subject: [PATCH 060/132] Show score components in /tellraw and /title --- .../src/game/commands/text_commands.rs | 57 ++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index dead07d71..a1ea4d673 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -14,10 +14,11 @@ impl Game<'_> { serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?; // NbtContents.resolve: the path's values in the entity, block or // storage data, rich-styled (or plain, or interpreted), ", "-joined. + // ScoreContents.resolve: the holder's score in the objective. let nbt_values = std::cell::RefCell::new(Vec::new()); { let mut collect = |o: &serde_json::Map| { - if o.contains_key("nbt") { + if o.contains_key("nbt") || o.contains_key("score") { nbt_values.borrow_mut().push(o.clone()); } }; @@ -40,7 +41,11 @@ impl Game<'_> { } let mut resolved: Vec<(serde_json::Map, Text)> = Vec::new(); for o in nbt_values.into_inner() { - let t = self.resolve_nbt_component(&o); + let t = if o.contains_key("score") { + self.resolve_score_component(&o)? + } else { + self.resolve_nbt_component(&o) + }; resolved.push((o, t)); } let mut resolve = |raw: &str| -> Text { @@ -73,6 +78,54 @@ impl Game<'_> { }, )) } + /// The text of a `score` component (ScoreContents.resolve): the named + /// holder's score, `*` being the player the command runs for. + fn resolve_score_component( + &mut self, + o: &serde_json::Map, + ) -> R { + let score = o.get("score"); + let field = |k: &str| score.and_then(|s| s.get(k)).and_then(|v| v.as_str()); + let (name, objective) = ( + field("name").unwrap_or(""), + field("objective").unwrap_or(""), + ); + // findTargetName: a selector that matches one entity is that entity, + // one that matches none is just the name. + let mut reader = horizon_client::command::Reader::new(name); + let ty = horizon_client::command::args::ArgType::Entity { + single: false, + players: false, + }; + let mut holder = name.to_owned(); + if let Ok(Arg::Entity(sel)) = ty.parse(&mut reader, &self.ui.registries) + && !reader.can_read() + { + let found = self.select(&sel); + if found.len() > 1 { + return Err(err("argument.entity.toomany", &[])); + } + if let Some(t) = found.first().and_then(|t| self.holder_name(*t)) { + holder = t; + } + } + if holder == "*" { + holder = self.acting_player_name().to_owned(); + } + let board = &self.score.board; + let (Some(objective), Some(score)) = + (board.objective(objective), board.score(&holder, objective)) + else { + return Ok(Text::empty()); + }; + // numberFormatOrDefault(StyledFormat.NO_STYLE). + let format = (score.number_format.clone()) + .or_else(|| objective.number_format.clone()) + .unwrap_or(horizon_client::scoreboard::NumberFormat::Styled( + serde_json::json!({}), + )); + Ok(format.format(score.value)) + } /// The text of an `nbt` component. fn resolve_nbt_component(&mut self, o: &serde_json::Map) -> Text { use horizon_world::nbt::Tag; From 82d2b61a4a5a1eb01030a0e8516eddb39d0587da Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:30:33 +0100 Subject: [PATCH 061/132] Swing a horse's tail now and then --- crates/horizon-client/src/game/remote.rs | 10 +++++++++ crates/horizon-client/src/mobs/ai.rs | 2 +- crates/horizon-client/src/mobs/equine.rs | 26 +++++++++++++++++++++++- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..5432713dc 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3507,6 +3507,16 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Rabbit { horizon_client::mobs::rabbit::base_tick(m); } + if matches!( + m.species(), + horizon_client::mobs::Species::Horse + | horizon_client::mobs::Species::Donkey + | horizon_client::mobs::Species::Mule + | horizon_client::mobs::Species::SkeletonHorse + | horizon_client::mobs::Species::ZombieHorse + ) { + horizon_client::mobs::equine::tail_tick(m); + } if m.species() == horizon_client::mobs::Species::Creeper { horizon_client::mobs::hostile::creeper_client_tick(m); } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index f82117aee..10535971e 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -641,7 +641,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & } // AbstractHorse.aiStep: the tail swishes now and then (moveTail). if super::equine::is_equine(m.species()) { - let _ = m.random.next_int_bound(200); + super::equine::tail_tick(m); } // Monster.aiStep: updateNoActionTime (Raider: always +2). if is_monster(m.species()) diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 5bb5faf53..1155388fd 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -28,6 +28,8 @@ pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackd pub const EAT: usize = 0; pub const STAND: usize = 1; pub const MOUTH: usize = 2; +/// `AbstractHorse.tailCounter`: client-side, it only drives the model. +pub const TAIL: usize = 3; /// What a rider asks of its mount this tick. #[derive(Clone, Copy, Debug, Default)] @@ -418,6 +420,20 @@ pub fn ridden_step(m: &mut Mob) { } } } +/// `AbstractHorse.aiStep`'s `moveTail` (one in 200 ticks) and the counter's +/// step in `tick` (it runs to 8, then stops). A client runs it on its own +/// random, as vanilla's client-side `aiStep` does. +pub fn tail_tick(m: &mut Mob) { + if m.random.next_int_bound(200).unwrap_or(1) == 0 { + m.anim.v[TAIL] = 1.0; + } + if m.anim.v[TAIL] > 0.0 { + m.anim.v[TAIL] += 1.0; + if m.anim.v[TAIL] > 8.0 { + m.anim.v[TAIL] = 0.0; + } + } +} /// `AbstractHorse.aiStep` and `tick`: healing, grazing, the rear and the /// eating/standing/mouth animations. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { @@ -603,7 +619,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { t[1] += speed * age; t[2] += speed * 2.0 * age; } - p.yrot("tail", 0.0); + // animateTail: the tail swings while the counter runs. + p.yrot( + "tail", + if m.anim.v[TAIL] > 0.0 { + (s.age * 0.7).mcos() + } else { + 0.0 + }, + ); if baby && donkey { // BabyDonkeyModel overrides the state's pitch with -30 degrees and // sets the head parts again. From 41ca489d4e066b9c0a82ff6df1e08b10b27f321b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:31:14 +0100 Subject: [PATCH 062/132] Move /particle count 0 particles at speed times delta --- crates/horizon-client/src/game/commands/world_cmds.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 687eb3f88..d58b477b0 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -605,8 +605,11 @@ impl Game<'_> { let reached = reached.len() as i32; if !local { } else if count <= 0 { - // No count: one particle with the delta as velocity. - self.particles.create(&options, pos, delta); + // handleParticleEvent, count 0: one particle, the speed times + // the delta as velocity (both sent as floats). + let speed = f64::from(speed); + self.particles + .create(&options, pos, delta.map(|d| speed * f64::from(d as f32))); } else { for _ in 0..count { let r = self.particles.random(); From 041ecb7b7ab6cfef260341f73a95dc1ae720b5f5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:31:16 +0100 Subject: [PATCH 063/132] Structures: load the template's block entity NBT into every container and sign --- crates/horizon-client/src/structure_blocks.rs | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 604cf7925..0c15bd1ad 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -185,23 +185,27 @@ fn text(nbt: &Compound, key: &str) -> Option { /// The client block entity for one of a chunk's generated block entities, /// before a container's loot is unpacked: `StructureTemplate.placeInWorld` -/// hands the template's block entity NBT to the level's block entity. +/// hands the template's block entity NBT to `loadWithComponents`, which is +/// what a chunk load does with a saved one. fn generated_block_entity(block: &str, nbt: &Compound) -> Option { - let mut entity = BlockEntity::for_block(block)?; - match &mut entity { - // MonsterRoomFeature and the structures' setEntityId. - BlockEntity::Spawner(s) => { - **s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone())); - } - BlockEntity::TrialSpawner(s) => { - **s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone())); - } - BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())), - // BannerBlockEntity.loadAdditional: the End cities' black triangles. - BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())), - _ => {} + let fallback = BlockEntity::for_block(block)?; + let mut tag = nbt.clone(); + // RandomizableContainer.tryLoadLootTable: with a table the items are not read. + if text(&tag, "LootTable").is_some() { + tag.remove(&JavaString::from("Items")); } - Some(entity) + // Programmatic block entities (and a template that saved none) carry no id. + if !tag.contains_key(&JavaString::from("id")) { + tag.insert("id".into(), Tag::String(fallback.id().into())); + } + for axis in ["x", "y", "z"] { + tag.insert(axis.into(), Tag::Int(0)); + } + // A saved kind the client cannot decode keeps the block's own entity. + Some( + crate::save::decode_block_entity(&Tag::Compound(tag)) + .map_or(fallback, |(_, entity)| entity), + ) } /// Client block entities for the generated block entities of a chunk, and the From 0e658e3e6249e132db5f2dc2add61593a7205480 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:31:21 +0100 Subject: [PATCH 064/132] Make drowned throw real tridents instead of arrows --- .../examples/probe/arrow_probe.rs | 2 + crates/horizon-client/src/arrows.rs | 51 ++++++++++- crates/horizon-client/src/game/commands.rs | 3 +- crates/horizon-client/src/game/creatures.rs | 89 +++++++++++++++++-- .../horizon-client/src/game/lan_entities.rs | 14 +++ crates/horizon-client/src/mobs/undead.rs | 27 +++--- crates/horizon-client/src/projectiles.rs | 16 ++-- 7 files changed, 171 insertions(+), 31 deletions(-) diff --git a/crates/horizon-client/examples/probe/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs index f72e6276e..411561c4e 100644 --- a/crates/horizon-client/examples/probe/arrow_probe.rs +++ b/crates/horizon-client/examples/probe/arrow_probe.rs @@ -163,6 +163,8 @@ pub fn main() -> Result<()> { ArrowSound::HitGround => "hit", ArrowSound::Splash => "splash", ArrowSound::Extinguish => "extinguish", + ArrowSound::TridentHitGround => "trident_hit_ground", + ArrowSound::TridentHit => "trident_hit", }, volume.to_bits(), pitch.to_bits() diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index f3c9c63bd..6d8dc528b 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -9,7 +9,7 @@ use crate::{ collisions::SceneCollisions, mobs::Who, motion::{FluidResources, LAVA, WATER}, - projectiles::{Hit, Projectile}, + projectiles::{Hit, Projectile, ProjectileKind}, world::World, }; use horizon_core::{ @@ -132,6 +132,10 @@ pub enum ArrowSound { HitGround, /// `entity.generic.extinguish_fire`. Extinguish, + /// A thrown trident's `getDefaultHitGroundSoundEvent` (`item.trident.hit_ground`). + TridentHitGround, + /// `ThrownTrident.onHitEntity`'s `item.trident.hit`. + TridentHit, } /// What a burning arrow does to the block it hits (`onProjectileHit`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -169,6 +173,9 @@ pub struct ArrowState { pub was_eye_in_water: bool, pub first_tick: bool, pub has_been_shot: bool, + /// `ThrownTrident.dealtDamage`: it has hit an entity (or sat in a block + /// for over 4 ticks) and hits no more. + pub dealt_damage: bool, pub removed: bool, /// The arrow's own random (`Entity.random`). pub random: LegacyRandom, @@ -211,6 +218,7 @@ impl ArrowState { was_eye_in_water: false, first_tick: true, has_been_shot: false, + dealt_damage: false, removed: false, random, events: Vec::new(), @@ -451,12 +459,14 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity let Some(mut st) = p.arrow.take() else { return false; }; + let trident = matches!(p.kind, ProjectileKind::Trident); let mut ticker = Ticker { p, st: &mut st, scene, }; match outcome { + EntityHit::Hurt | EntityHit::Refused if trident => ticker.trident_bounce(), EntityHit::Hurt => { ticker.hit_sound(); // A piercing arrow flies on (`getPierceLevel() <= 0` discards). @@ -501,7 +511,16 @@ impl Ticker<'_, '_, '_, '_> { p.z, )) } + /// Whether this is a `ThrownTrident` (`AbstractArrow` with its own water + /// inertia, sounds and hit). + fn trident(&self) -> bool { + matches!(self.p.kind, ProjectileKind::Trident) + } fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit { + // ThrownTrident.tick. + if self.trident() && self.st.in_ground_time > 4 { + self.st.dealt_damage = true; + } let physics = !self.st.no_physics; let movement = self.p.velocity; let block_pos = self.block_position(); @@ -549,8 +568,9 @@ impl Ticker<'_, '_, '_, '_> { self.st.in_ground_time = 0; let original = self.position(); if self.st.was_touching_water { - // getWaterInertia, then the bubbles behind it. - self.p.velocity = self.p.velocity.scale(f64::from(0.6f32)); + // getWaterInertia (0.99 for a trident), then the bubbles behind it. + let inertia = if self.trident() { 0.99f32 } else { 0.6f32 }; + self.p.velocity = self.p.velocity.scale(f64::from(inertia)); let v = self.p.velocity; for _ in 0..4 { self.st.events.push(ArrowEvent::Particle { @@ -687,6 +707,8 @@ impl Ticker<'_, '_, '_, '_> { .expand_towards(self.p.velocity) .inflate(Vec3::new(1.0, 1.0, 1.0)); let mut best: Option<(Who, Vec3, f64)> = None; + // ThrownTrident.findHitEntity: none once it has dealt damage. + let targets = if self.st.dealt_damage { &[] } else { targets }; for (who, b) in targets { if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) { continue; @@ -757,12 +779,33 @@ impl Ticker<'_, '_, '_, '_> { /// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`. fn hit_sound(&mut self) { let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9); + let sound = if self.trident() { + ArrowSound::TridentHitGround + } else { + ArrowSound::HitGround + }; self.st.events.push(ArrowEvent::Sound { - sound: ArrowSound::HitGround, + sound, volume: 1.0, pitch, }); } + /// `ThrownTrident.onHitEntity` after the hurt, whether it landed or not: + /// the hit sound, then `deflect(REVERSE, ..., (0.02, 0.2, 0.02))`. The + /// trident keeps flying (it has dealt its damage) and falls. + fn trident_bounce(&mut self) { + self.st.dealt_damage = true; + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::TridentHit, + volume: 1.0, + pitch: 1.0, + }); + // ProjectileDeflection.REVERSE. + let rotation = 170.0 + self.st.random.next_float() * 20.0; + let v = self.p.velocity; + self.p.velocity = Vec3::new(v.x * (-0.02 * 0.5), v.y * (-0.2 * 0.5), v.z * (-0.02 * 0.5)); + self.p.yaw += rotation; + } /// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`, /// a half turn give or take ten degrees at a tenth of the speed; one /// left almost still drops its pickup (ALLOWED) and is discarded. diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 22041c3b2..f308cfec6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -541,8 +541,7 @@ impl Game<'_> { .enumerate() // The kinds /data can write (entity_nbt). .filter(|(_, p)| { - p.arrow.is_some() - || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) + p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) }) .map(|(i, _)| Target::Projectile(i)), ); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 4c5726757..b3618af5c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1946,6 +1946,23 @@ impl Game<'_> { None => self.projectile_hit(p, hit), } } + /// What an arrow or a thrown trident hits an entity for + /// (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a trident's + /// 8, plus Impaling on aquatic `victim`s. + fn shot_damage(&mut self, shot: &mut Projectile, victim: Option) -> f32 { + if !matches!(shot.kind, ProjectileKind::Trident) { + return arrow_damage(shot, &mut self.world.random) + shot.bonus.damage; + } + let impaling = shot + .arrow + .as_ref() + .map_or(0, |a| a.pickup_item.enchantment_level("minecraft:impaling")) + as f32; + let aquatic = victim + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .is_some_and(|m| m.kind.flags.aquatic_swimmer || m.kind.flags.breathes_water); + 8.0 + if aquatic { 2.5 * impaling } else { 0.0 } + } /// What an arrow's tick asked for: its particles and sounds. fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction}; @@ -1974,6 +1991,8 @@ impl Game<'_> { ArrowSound::Splash => "minecraft:entity.generic.splash", ArrowSound::HitGround => "minecraft:entity.arrow.hit", ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire", + ArrowSound::TridentHitGround => "minecraft:item.trident.hit_ground", + ArrowSound::TridentHit => "minecraft:item.trident.hit", }; self.audio .play(name, Some([at.x, at.y, at.z]), volume, pitch); @@ -2123,11 +2142,11 @@ impl Game<'_> { && id >= super::dragon::SPECIAL { let by_player = p.owner == Some(Who::Player); - if let ProjectileKind::Arrow { .. } = p.kind { + if p.arrow.is_some() { // AbstractArrow.onHitEntity: spent if the part or crystal took // it, else turned back (a perched dragon sets it alight first). let mut arrow = p.clone(); - let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let amount = self.shot_damage(&mut arrow, None); let outcome = match self.hit_special(id, amount, by_player, true) { super::dragon::Hurt::Landed { .. } => EntityHit::Hurt, super::dragon::Hurt::Refused => EntityHit::Refused, @@ -2148,17 +2167,15 @@ impl Game<'_> { self.hit_special(id, amount, by_player, false); return Ok(()); } - if let ( - ProjectileKind::Arrow { .. }, - Hit::Entity { + if p.arrow.is_some() + && let Hit::Entity { who: Who::Mob(id), .. - }, - ) = (&p.kind, hit) + } = hit && let Some(i) = self.carts.iter().position(|c| c.id == id) { // AbstractArrow.onHitEntity on a minecart. let mut arrow = p.clone(); - let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let amount = self.shot_damage(&mut arrow, None); let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire()); let creative = p.owner == Some(Who::Player) && self.creative; self.arrow_hits_cart(i, amount, p.velocity, burning, creative); @@ -2169,7 +2186,7 @@ impl Game<'_> { // Projectile.onHit: the landing is heard. self.projectile_event("minecraft:projectile_land", p.owner, atp); let source_kind = match p.kind { - ProjectileKind::Arrow { .. } => DamageKind::Arrow, + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => DamageKind::Arrow, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { DamageKind::Fireball } @@ -2181,6 +2198,36 @@ impl Game<'_> { from: Some([p.previous.x, p.previous.y, p.previous.z]), }; match (&p.kind, hit) { + // ThrownTrident.onHitEntity: 8 damage (Impaling on aquatic mobs), + // dealt whether or not the hurt lands, then it bounces off. + (ProjectileKind::Trident, Hit::Entity { who, .. }) => { + let mut trident = p.clone(); + let victim = match who { + Who::Mob(id) => Some(id), + Who::Player => None, + }; + let amount = self.shot_damage(&mut trident, victim); + let hurt = match who { + Who::Player => self.mob_hits_player( + amount, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:trident", + ), + Who::Mob(id) => self + .mobs + .iter_mut() + .find(|m| m.id == id) + .is_some_and(|m| m.damage(amount, source)), + }; + let outcome = if hurt { + EntityHit::Hurt + } else { + EntityHit::Refused + }; + self.finish_arrow_hit(trident, outcome); + } + // AbstractArrow.onHitBlock plays its sound itself (ArrowEvent). + (ProjectileKind::Trident, Hit::Block { .. }) => {} (ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => { let mut arrow = p.clone(); let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; @@ -3305,6 +3352,30 @@ impl Game<'_> { } continue; } + // ThrownTridentRenderer. + if matches!(a.kind, ProjectileKind::Trident) { + let Some(model) = self.trident_model.as_ref() else { + continue; + }; + let Some(r) = atlas.sprites.get("entity/trident/trident").copied() else { + continue; + }; + let m = glam::Mat4::from_translation(c) + * glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians()) + * glam::Mat4::from_rotation_z((a.pitch + 90.0).to_radians()); + let poses = horizon_client::mobs::anim::Poses::new(model); + horizon_client::mobs::render::draw( + model, + m, + &poses, + [r.u0, r.v0, r.u1, r.v1], + 0xFFFF_FFFF, + packed, + 0, + out, + ); + continue; + } // WindChargeRenderer. if matches!( a.kind, diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 529666590..b41dc5c23 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -354,6 +354,20 @@ impl Game<'_> { a.is_some_and(|a| a.in_ground) || p.stuck, )); } + // ThrownTrident.ID_LOYALTY (none for a mob's) and ID_FOIL, on + // AbstractArrow's flags. + K::Trident => { + let a = p.arrow.as_deref(); + e.meta.extend(arrow_meta( + false, + a.is_some_and(|a| a.no_physics), + 0, + a.is_some_and(|a| a.in_ground) || p.stuck, + )); + if a.is_some_and(|a| a.pickup_item.has_any_enchantments()) { + e.meta.push((12, serializer::BOOLEAN, Value::Bool(true))); + } + } // WitherSkull.DATA_DANGEROUS. K::WitherSkull { dangerous: true } => { e.meta.push((8, serializer::BOOLEAN, Value::Bool(true))); diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index bbc903288..3c3a48bd5 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -228,8 +228,10 @@ pub fn drowned_travel( m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); true } -/// The trident throw of `Drowned.performRangedAttack`, until thrown tridents -/// exist: an arrow-like shot with the trident's damage. +/// The trident throw of `Drowned.performRangedAttack`: a `ThrownTrident` of +/// the held trident (a plain one when it holds none), owned by the drowned, +/// which cannot be picked up and does not return (`AbstractArrow` constructor: +/// only a player's projectile is `Pickup.ALLOWED`). fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let Some(t) = cx.w.target_info(who) else { return; @@ -239,15 +241,18 @@ fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let yd = t.position.y + (t.bounds.max_position().y - t.bounds.min_position().y) / 3.0 - start.y; let zd = t.position.z - m.position.z; let dist = (xd * xd + zd * zd).sqrt(); - let mut p = Projectile::new( - ProjectileKind::Arrow { - base_damage: 8.0, - critical: false, - effect: None, - }, - start, - Some(Who::Mob(m.id)), - ); + let mut trident = crate::items::ItemStack::new("minecraft:trident", 1); + if m.extra.main_hand.as_deref() == Some("minecraft:trident") + && let Some(g) = super::gear::gear(m) + { + for (e, l) in &g.slots[super::gear::MAIN] { + trident.enchant(e, *l); + } + } + let mut p = Projectile::new(ProjectileKind::Trident, start, Some(Who::Mob(m.id))); + if let Some(a) = p.arrow.as_mut() { + a.set_item(&trident); + } p.shoot( &mut crate::projectiles::own_random(m), [xd, yd + dist * f64::from(0.2_f32), zd], diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 8a709067d..aae9b296b 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -28,6 +28,10 @@ pub enum ProjectileKind { critical: bool, effect: Option<(&'static str, i32)>, }, + /// `ThrownTrident` of a mob (a drowned's): flies and sticks with + /// `AbstractArrow`'s tick; the trident itself is the arrow state's + /// `pickup_item`. + Trident, Snowball, Egg, EnderPearl, @@ -66,6 +70,7 @@ impl ProjectileKind { pub fn id(&self) -> &'static str { match self { Self::Arrow { .. } => "minecraft:arrow", + Self::Trident => "minecraft:trident", Self::Snowball => "minecraft:snowball", Self::Egg => "minecraft:egg", Self::EnderPearl => "minecraft:ender_pearl", @@ -152,7 +157,7 @@ fn axis_of(d: u8) -> u8 { } impl Projectile { pub fn new(kind: ProjectileKind, position: Vec3, owner: Option) -> Self { - let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. }); + let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. } | ProjectileKind::Trident); Self { id: 0, kind, @@ -253,7 +258,7 @@ impl Projectile { } fn gravity(&self) -> f64 { match self.kind { - ProjectileKind::Arrow { .. } => 0.05, + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => 0.05, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } | ProjectileKind::WitherSkull { .. } => 0.0, @@ -604,8 +609,8 @@ impl Projectile { | ProjectileKind::WitherSkull { .. } => { self.apply_hurting_inertia(water); } - // Arrows tick with `arrows::tick`. - ProjectileKind::Arrow { .. } => {} + // Arrows and tridents tick with `arrows::tick`. + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => {} ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {} // LlamaSpit.tick: gone in water; drag and gravity follow the move. ProjectileKind::LlamaSpit => { @@ -746,7 +751,8 @@ impl Projectile { ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => return None, ProjectileKind::WitherSkull { dangerous: false } => "entity/wither/wither", ProjectileKind::WitherSkull { dangerous: true } => "entity/wither/wither_invulnerable", - ProjectileKind::Arrow { .. } => return None, + // Drawn as their models by the game. + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => return None, }) } /// Render scale of the item billboard (fireball renderers). From 41d8b9e48aa8c5604fb2674ad60c2726de3e6857 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:32:20 +0100 Subject: [PATCH 065/132] Jigsaw structures: default max distance vertical and padding top like vanilla --- .../src/worldgen/structure/start.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 810332c61..f84a953a1 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -275,16 +275,15 @@ fn terrain(name: Option<&str>) -> TerrainAdjustment { _ => TerrainAdjustment::None, } } -fn pair(value: Option<&Value>, a: &str, b: &str, default: i32) -> [i32; 2] { +/// A jigsaw field given as one number or as an object of two. In the object a +/// missing `a` is 0 and a missing `b` is `missing_b` (`JigsawStructure.MaxDistance` +/// and `DimensionPadding` default their second value, not copy the first). +fn pair(value: Option<&Value>, a: &str, b: &str, default: i32, missing_b: i32) -> [i32; 2] { match value { Some(Value::Number(n)) => [n.as_i64().unwrap_or(0) as i32; 2], Some(Value::Object(o)) => { - let get = |k: &str| o.get(k).and_then(Value::as_i64).unwrap_or(0) as i32; - let first = get(a); - [ - first, - o.get(b).and_then(Value::as_i64).map_or(first, |v| v as i32), - ] + let get = |k: &str| o.get(k).and_then(Value::as_i64).map(|v| v as i32); + [get(a).unwrap_or(0), get(b).unwrap_or(missing_b)] } _ => [default; 2], } @@ -326,9 +325,11 @@ impl StructureRegistry { "horizontal", "vertical", 80, + // DimensionType.Y_SIZE. + 4064, ), aliases: v["pool_aliases"].as_array().cloned().unwrap_or_default(), - padding: pair(v.get("dimension_padding"), "bottom", "top", 0), + padding: pair(v.get("dimension_padding"), "bottom", "top", 0, 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")), piece_limited: v From bf62ccdabc6edff2ece53f895f5a4fe9a2e5e65d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:33:16 +0100 Subject: [PATCH 066/132] Place the bonus chest in new worlds --- crates/horizon-client/src/game.rs | 6 ++ .../horizon-client/src/game/initial_spawn.rs | 77 +++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 20f6e01bc..03fa05669 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4293,6 +4293,12 @@ impl Game<'_> { // The world's spawn from the start, not only once saved: a bed set // before the first save must not become it. self.level.world_spawn.get_or_insert([x, y, z]); + // The "Bonus Chest" create-world option, placed once with the spawn. + if horizon_client::save::WorldGen::read(&self.world_root) + .is_some_and(|g| g.bonus_chest) + { + self.place_bonus_chest([x, y, z])?; + } } let s = self .level diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 3f7a071bb..bbd0a766c 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -121,6 +121,83 @@ impl Game<'_> { } Ok(Some([ox * 16 + 8, height, oz * 16 + 8])) } + /// MinecraftServer.setInitialSpawn's bonus chest: BonusChestFeature.place + /// in the spawn chunk, a chest with the spawn bonus loot and a torch on + /// each side that can hold one, on the first free column of a shuffled + /// walk over the chunk. Skipped while the chunk is not loaded. + pub(super) fn place_bonus_chest(&mut self, origin: [i32; 3]) -> Result<()> { + use horizon_client::containers::BlockEntity; + let (cx, cz) = (origin[0] >> 4, origin[2] >> 4); + let registry = &self.pack.assets.registry; + let (Some(chest), Some(torch)) = ( + registry.default_state("minecraft:chest"), + registry.default_state("minecraft:torch"), + ) else { + return Ok(()); + }; + if !self.streaming.is_lit(cx, cz) { + return Ok(()); + } + let mut random = entity_random(); + // Util.toShuffledList of the chunk's x and z. + let mut shuffled = |min: i32| -> [i32; 16] { + let mut values: [i32; 16] = std::array::from_fn(|i| min + i as i32); + for end in (2..=16usize).rev() { + let other = random.next_int_bound(end as i32).unwrap_or(0) as usize; + values.swap(end - 1, other); + } + values + }; + let (xs, zs) = (shuffled(cx * 16), shuffled(cz * 16)); + for x in xs { + for z in zs { + let y = self + .spawn_columns() + .height(HeightmapType::MotionBlockingNoLeaves, x, z); + if self.world.block(x, y, z) != self.world.air && !self.collision_empty([x, y, z]) { + continue; + } + self.level_set([x, y, z], chest)?; + let seed = random.next_long(); + self.world + .block_entities + .insert((x, y, z), BlockEntity::Chest(Vec::new())); + self.load_block_entity_nbt( + [x, y, z], + &format!( + "{{LootTable:\"minecraft:chests/spawn_bonus_chest\",LootTableSeed:{seed}L}}" + ), + ); + for [dx, dz] in [[0, -1], [1, 0], [0, 1], [-1, 0]] { + let at = [x + dx, y, z + dz]; + let survives = self.with_level(|b, level, ticks| { + b.can_survive(level, ticks, BlockPos::new(at[0], at[1], at[2]), torch) + }); + if survives { + self.level_set(at, torch)?; + } + } + return Ok(()); + } + } + Ok(()) + } + /// The block at `pos` has no collision shape. + fn collision_empty(&self, pos: [i32; 3]) -> bool { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape_with_context( + &mut scene, + self.world.block(pos[0], pos[1], pos[2]), + BlockPos::new(pos[0], pos[1], pos[2]), + &CollisionContext::empty(false), + ) + .is_ok_and(|shape| shape.is_empty()) + } /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a /// player who has no position yet. None while a candidate's chunk loads. pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { From c417556834aee38cd1a8f4a2815e5f09a753fb6b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:33:36 +0100 Subject: [PATCH 067/132] Send /tellraw, /title and /playsound to LAN guests --- .../src/game/commands/text_commands.rs | 71 +++++++++++++------ .../src/game/commands/world_cmds.rs | 33 ++++++++- crates/horizon-client/src/lan/containers.rs | 39 ++++++---- 3 files changed, 106 insertions(+), 37 deletions(-) diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index dead07d71..225028adc 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -136,28 +136,40 @@ impl Game<'_> { } out } - fn player_targets(&mut self, ctx: &Context) -> R { - // Only the local player can receive messages and titles. + /// The players the command reaches: the window's own and the LAN guests. + fn player_targets(&mut self, ctx: &Context) -> R> { let targets = self.entities(ctx, "targets", true)?; - Ok(targets.iter().filter(|t| **t == Target::Player).count()) + Ok(targets + .into_iter() + .filter(|t| matches!(t, Target::Player | Target::Guest(_))) + .collect()) } pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R { - let n = self.player_targets(ctx)?; + let players = self.player_targets(ctx)?; let message = self.component_arg(ctx, "message")?; - if n > 0 { - self.system_message(message); + // Each player's chat (a guest's through the connection). + for &t in &players { + self.for_player(t, |g| g.system_message(message.clone())); } - Ok(n as i32) + Ok(players.len() as i32) } pub(super) fn cmd_title(&mut self, ctx: &Context) -> R { - let n = self.player_targets(ctx)?; - let name = self.target_name(Target::Player); + let players = self.player_targets(ctx)?; + let n = players.len(); + let name = players + .first() + .map_or_else(Text::empty, |t| self.target_name(*t)); let single = n == 1; let key = if ctx.has("clear") { - self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false })); + self.titles_or_packet( + &players, + Titles::clear, + C::ClearTitles(play::Bool1 { value: false }), + ); "cleared" } else if ctx.has("reset") { self.titles_or_packet( + &players, |t| { t.clear(); t.reset_times(); @@ -172,6 +184,7 @@ impl Game<'_> { }; let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut")); self.titles_or_packet( + &players, |t| t.set_times(fade_in, stay, fade_out), C::SetTitlesAnimation(play::TitlesAnimation { fade_in, @@ -186,13 +199,17 @@ impl Game<'_> { text: component_nbt(&text.component()), }; if ctx.has("subtitle") { - self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent)); + self.titles_or_packet(&players, |t| t.set_subtitle(text), C::SetSubtitleText(sent)); "show.subtitle" } else if ctx.has("actionbar") { - self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent)); + self.titles_or_packet( + &players, + |t| t.set_overlay(text, false), + C::SetActionBarText(sent), + ); "show.actionbar" } else { - self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent)); + self.titles_or_packet(&players, |t| t.set_title(text), C::SetTitleText(sent)); "show.title" } }; @@ -207,13 +224,27 @@ impl Game<'_> { self.feedback(message); Ok(n as i32) } - /// The player the title is for: the guest acting now is sent the packet - /// (TitleCommand's `connection.send`), the window's own player shows it. - fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) { - if self.lan_acting.is_some() { - self.guest_packets.push(packet); - } else { - local(&mut self.titles); + /// TitleCommand's `connection.send` for each player: a guest is sent the + /// packet, the window's own player shows it. + fn titles_or_packet(&mut self, players: &[Target], local: impl FnOnce(&mut Titles), packet: C) { + let mut local = Some(local); + for &t in players { + match t { + Target::Player if self.lan_acting.is_some() => { + self.guest_packets.push(packet.clone()); + } + Target::Player => { + if let Some(local) = local.take() { + local(&mut self.titles); + } + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, &packet); + } + } + _ => {} + } } } } diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 687eb3f88..2e328b922 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -301,9 +301,18 @@ impl Game<'_> { float("minVolume", 0.0), ); let range = if volume > 1.0 { 16.0 * volume } else { 16.0 }; + // PlaySoundCommand: one seed for every player. + let seed = self.world.random.next_long(); + let here = self.dim.id(); let mut tracker = Tracker::default(); for t in targets { - if t != Target::Player { + if !matches!(t, Target::Player | Target::Guest(_)) { + continue; + } + // Only players in the source's level hear it. + if let Target::Guest(conn) = t + && self.command_guest(conn).is_none_or(|g| g.dimension != here) + { continue; } let Some(p) = self.target_position(t) else { @@ -327,8 +336,26 @@ impl Game<'_> { } else { (pos, volume) }; - self.audio.play_on(source, &sound, Some(at), v, pitch); - tracker.mark(&holder(Text::literal(self.acting_player_name()))); + // The connection is sent the sound; the window's own player + // plays it. + let guest = match t { + Target::Guest(conn) => Some(conn), + _ => self.lan_acting, + }; + match guest.and_then(|conn| Some((conn, self.lan.as_ref()?))) { + Some((conn, host)) => { + let packet = host + .hub + .sound_packet(&sound, at, v, pitch, source as i32, seed); + if t == Target::Player { + self.guest_packets.push(packet); + } else { + host.hub.send_to(conn, &packet); + } + } + None => self.audio.play_on(source, &sound, Some(at), v, pitch), + } + tracker.mark(&holder(self.target_name(t))); } let name = Text::literal(sound.clone()); let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 002f95cbb..7ea8f0baf 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -36,6 +36,30 @@ impl Hub { /// ClientboundSoundPacket for a sound event name (an inline event when /// the registry does not know it). + pub fn sound_packet( + &self, + name: &str, + at: [f64; 3], + volume: f32, + pitch: f32, + source: i32, + seed: i64, + ) -> C { + let sound = match self.sync.id("minecraft:sound_event", name) { + Some(id) => (id, None), + None => (-1, Some((name.to_owned(), None))), + }; + C::Sound(play::Sound { + sound, + source, + x: (at[0] * 8.0) as i32, + y: (at[1] * 8.0) as i32, + z: (at[2] * 8.0) as i32, + volume, + pitch, + seed, + }) + } pub fn sound( &self, name: &str, @@ -45,20 +69,7 @@ impl Hub { source: i32, except: Option, ) { - let sound = match self.sync.id("minecraft:sound_event", name) { - Some(id) => (id, None), - None => (-1, Some((name.to_owned(), None))), - }; - let packet = C::Sound(play::Sound { - sound, - source, - x: (at[0] * 8.0) as i32, - y: (at[1] * 8.0) as i32, - z: (at[2] * 8.0) as i32, - volume, - pitch, - seed: self.ticks as i64, - }); + let packet = self.sound_packet(name, at, volume, pitch, source, self.ticks as i64); self.broadcast_near(at, f64::from(volume.max(1.0)) * 16.0, &packet, except); } From 7b3595b8f29cb00d0a29a40a726a1492484566b7 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:34:18 +0100 Subject: [PATCH 068/132] Draw the snow golem's pumpkin and the mooshroom's mushrooms --- crates/horizon-client/src/game/lan.rs | 14 ++++ crates/horizon-client/src/game/mob_blocks.rs | 74 ++++++++++++++++++- .../src/game/remote_mob_data.rs | 6 ++ 3 files changed, 93 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..c469472b5 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -223,6 +223,20 @@ fn mob_meta( } defaults.push((16, serializer::BYTE, Value::Byte(0))); } + // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on (the default). + "minecraft:snow_golem" => { + if e.sheared { + meta.push((16, serializer::BYTE, Value::Byte(0))); + } + defaults.push((16, serializer::BYTE, Value::Byte(16))); + } + // MushroomCow.DATA_TYPE: 0 red, 1 brown. + "minecraft:mooshroom" => { + if e.variant == 1 { + meta.push((17, serializer::INT, Value::Int(1))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + } // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared. "minecraft:sheep" => { let value = (e.color & 15) | if e.sheared { 16 } else { 0 }; diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 083c96a66..a0ce5e9db 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -1,6 +1,7 @@ //! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the //! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like -//! dropped block items. +//! dropped block items. Also the block models mobs wear (`SnowGolemHeadLayer`, +//! `MushroomCowMushroomLayer`). use super::Game; use horizon_client::{ items::ItemStack, @@ -218,6 +219,7 @@ impl Game<'_> { ) { self.captain_banner_geometry(mob, camera, alpha, light, out); self.held_item_geometry(mob, camera, alpha, light, true, out); + self.worn_block_geometry(mob, camera, alpha, light, out); if mob.species() == Species::Enderman && let Some(state) = mob.extra.carried && let Some((sprite, tint)) = self.block_face_sprite(state) @@ -244,6 +246,76 @@ impl Game<'_> { ); } } + /// `SnowGolemHeadLayer` and `MushroomCowMushroomLayer`: the carved pumpkin + /// on a snow golem's head, and the mushrooms on an adult mooshroom's back + /// and head, as baked block models. + fn worn_block_geometry( + &self, + mob: &Mob, + camera: glam::DVec3, + alpha: f64, + light: u32, + out: &mut Vec, + ) { + use glam::{Mat4, Vec3}; + let species = mob.species(); + let on_head = match species { + Species::SnowGolem => !mob.extra.sheared, + Species::Mooshroom => !mob.is_baby(), + _ => false, + }; + // The layers draw nothing on an invisible mob (the glow outline is not drawn). + if !on_head || horizon_client::mobs::trader::is_invisible(mob) { + return; + } + let registry = &self.pack.assets.registry; + let block = match species { + Species::SnowGolem => "minecraft:carved_pumpkin", + _ if mob.extra.variant == 1 => "minecraft:brown_mushroom", + _ => "minecraft:red_mushroom", + }; + let Some(state) = registry.default_state(block) else { + return; + }; + let alpha = alpha as f32; + let Some(head) = render::part_transform(mob, alpha, camera, self.res.mob_data(), "head") + else { + return; + }; + let unit = Mat4::from_translation(Vec3::splat(-0.5)); + let flip = Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0)); + let at = |x: f32, y: f32, z: f32| Mat4::from_translation(Vec3::new(x, y, z)); + let spin = |degrees: f32| Mat4::from_rotation_y(degrees.to_radians()); + let transforms = if species == Species::SnowGolem { + vec![ + head * at(0.0, -0.34375, 0.0) + * spin(180.0) + * Mat4::from_scale(Vec3::new(0.625, -0.625, -0.625)) + * unit, + ] + } else { + let base = render::base_transform(mob, alpha, camera); + vec![ + base * at(0.2, -0.35, 0.5) * spin(-48.0) * flip * unit, + base * at(0.2, -0.35, 0.5) + * spin(42.0) + * at(0.1, 0.0, -0.6) + * spin(-48.0) + * flip + * unit, + head * at(0.0, -0.7, -0.2) * spin(-78.0) * flip * unit, + ] + }; + // The hurt tint reaches these blocks as it does the body. + let overlay = horizon_client::overlay::living(0.0, mob.hurt_time > 0 || mob.death_time > 0); + for t in transforms { + let start = out.len(); + self.block_model_vertices(state, 0, t, light, true, out); + for vertex in &mut out[start..] { + vertex.layer = overlay; + } + } + } /// `ItemInHandLayer`: both hands through the item model pipeline; `lit` /// applies the level's diffuse lighting (off for GUI previews, which /// light the projected quads themselves). diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..110281363 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -66,6 +66,12 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti m.extra.color = (*wool & 15) as u8; m.extra.sheared = wool & 16 != 0; } + // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on. + (Species::SnowGolem, 16, Value::Byte(flags)) => m.extra.sheared = flags & 16 == 0, + // MushroomCow.DATA_TYPE: 0 red, 1 brown. + (Species::Mooshroom, 17, Value::Int(variant)) => { + m.extra.variant = (*variant == 1) as u8 + } // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. (Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => { m.extra.sitting = flags & 1 != 0; From e23fcb1040d573c9254223af79a1f4c27c30bd35 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:35:46 +0100 Subject: [PATCH 069/132] Scale a baby's walk position when it is read, as vanilla does --- crates/horizon-client/src/mobs/anim.rs | 3 ++- crates/horizon-client/src/mobs/living.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b81f224ae..d71b303dc 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -197,7 +197,8 @@ pub fn state(m: &Mob, alpha: f32) -> State { let walking = m.alive() && !m.extra.passenger; State { pos: if walking { - m.limb_position - m.limb_speed * (1.0 - alpha) + // WalkAnimationState.position(partial): babies' legs move 3 times as far. + (m.limb_position - m.limb_speed * (1.0 - alpha)) * if m.is_baby() { 3.0 } else { 1.0 } } else { 0.0 }, diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..e9cd42798 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -908,7 +908,7 @@ impl Mob { (distance * 4.0).min(1.0) }; self.limb_speed += (target - self.limb_speed) * 0.4; - self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 }; + self.limb_position += self.limb_speed; } else { self.limb_speed = 0.0; } From 4cf9ffd8472ef7e4c23045b503772ba5fd46d31f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:36:40 +0100 Subject: [PATCH 070/132] Draw the autosave indicator --- crates/horizon-client/src/game.rs | 13 +++++- crates/horizon-client/src/game/integrated.rs | 12 +++++ crates/horizon-client/src/game/titles.rs | 22 +++++++++ crates/horizon-client/src/hud_overlays.rs | 47 ++++++++++++++++++++ 4 files changed, 93 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 20f6e01bc..99c471fa6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1427,6 +1427,10 @@ struct Game<'a> { titles: titles::Titles, /// `Hud.toolHighlightTimer`: the selected item name. tool_highlight: horizon_client::hud_overlays::ToolHighlight, + /// `Hud.autosaveIndicatorValue`. + saving_indicator: horizon_client::hud_overlays::SavingIndicator, + /// This game's world is autosaving this tick (`MinecraftServer.isSaving`). + autosaving: bool, applied_modifiers: Vec<(String, String)>, experience: Experience, orbs: Vec, @@ -4396,7 +4400,11 @@ impl Game<'_> { self.world.weather.tick_levels(); self.tick_weather_effects(); } - if self.ticks.is_multiple_of(6000) { + self.autosaving = self.ticks.is_multiple_of(6000); + if let Some(serving) = &self.serving { + serving.set_saving(self.autosaving); + } + if self.autosaving { self.save_game_with(false)?; } if running { @@ -5399,6 +5407,7 @@ impl Game<'_> { Screen::Mod => self.draw_mod_screen(&mut batch), Screen::Playing | Screen::Options | Screen::Win => {} } + self.draw_saving_indicator(&mut batch); self.draw_toasts(&mut batch); self.draw_pack_toasts(&mut batch); self.remote_hud(&mut batch); @@ -12689,6 +12698,8 @@ impl<'a> Game<'a> { command_source: None, titles: Default::default(), tool_highlight: Default::default(), + saving_indicator: Default::default(), + autosaving: false, applied_modifiers: Vec::new(), experience: Experience::default(), orbs: Vec::new(), diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index dd1c04e23..7d81c971d 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -52,6 +52,8 @@ struct Flags { /// server follows while it runs (IntegratedServer.tickServer). render_distance: AtomicI32, simulation_distance: AtomicI32, + /// `MinecraftServer.isCurrentlySaving`: the server is autosaving. + saving: AtomicBool, } /// Work the window hands its server thread (`MinecraftServer.execute`). @@ -69,6 +71,10 @@ impl Integrated { pub fn smoothed_tick_ms(&self) -> f32 { f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed)) } + /// `MinecraftServer.isCurrentlySaving`. + pub fn is_saving(&self) -> bool { + self.flags.saving.load(Ordering::Relaxed) + } /// `IntegratedServer.tickServer` skips the world while the game is paused. pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); @@ -148,6 +154,12 @@ pub(super) struct Serving { /// is out of its place: applied after the tick. pending: Option, } +impl Serving { + /// The window reads this as `MinecraftServer.isCurrentlySaving`. + pub(super) fn set_saving(&self, saving: bool) { + self.flags.saving.store(saving, Ordering::Relaxed); + } +} enum Publish { Open(TcpListener, LanSettings), Close, diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index cbae1f6b4..9bb000314 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -21,6 +21,22 @@ impl Game<'_> { draws.extend(self.titles.title(w, h, partial, font, background)); hud_layout::paint(batch, &self.gui.atlas, &draws); } + /// `Hud.extractSavingIndicator`, under the screens: the option, then the + /// fading "Saving world" text. + pub(super) fn draw_saving_indicator(&self, batch: &mut HudBatch) { + if !self.settings.autosave_indicator { + return; + } + let draws = self.saving_indicator.draw( + batch.width as i32, + batch.height as i32, + self.clock.fraction() as f32, + &self.gui.atlas.font, + Text::literal(self.translate("menu.savingLevel", "Saving world")), + self.settings.text_background(0.0), + ); + hud_layout::paint(batch, &self.gui.atlas, &draws); + } /// The selected stack as `Hud.tick` compares it for the name highlight. fn held_name(&self) -> Option { let stack = self.inventory.get(self.selected)?.as_ref()?; @@ -44,6 +60,12 @@ impl Game<'_> { /// The title, action bar and selected-item parts of `Hud.tick`. pub(super) fn tick_hud(&mut self) { self.titles.tick(); + // `MinecraftServer.isCurrentlySaving` of single player's server. + let saving = self + .integrated + .as_ref() + .map_or(self.autosaving, |server| server.is_saving()); + self.saving_indicator.tick(saving); let held = self.held_name(); self.tool_highlight .tick(held, f64::from(self.settings.notification_display_time)); diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index ebd860e08..c6b098f75 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -191,6 +191,53 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec { out } +/// The saving indicator: `Hud.tickAutosaveIndicator` fades a value towards 1 +/// while the server is saving and `extractSavingIndicator` draws the text. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SavingIndicator { + last: f32, + value: f32, +} +impl SavingIndicator { + /// `Hud.tickAutosaveIndicator`: `Mth.lerp(0.2F, value, saving ? 1 : 0)`. + pub fn tick(&mut self, saving: bool) { + self.last = self.value; + self.value += (if saving { 1.0 } else { 0.0 } - self.value) * 0.2; + } + /// `Hud.extractSavingIndicator` without the option check: the text in the + /// bottom right corner. + pub fn draw( + &self, + w: i32, + h: i32, + partial: f32, + font: &Font, + label: Text, + background: u32, + ) -> Vec { + let mut out = Vec::new(); + if self.value <= 0.0 && self.last <= 0.0 { + return out; + } + let fade = (self.last + (self.value - self.last) * partial).clamp(0.0, 1.0); + let alpha = (255.0 * fade).floor() as u32; + if alpha > 0 { + let label_width = width(font, &label); + let color = crate::hud_layout::argb(alpha, 255, 255, 255); + text_with_backdrop( + &mut out, + label, + w - label_width - 5, + h - 9 - 5, + label_width, + color, + background, + ); + } + out + } +} + /// Titles and the action bar: `Hud.title`, `subtitle`, `titleTime`, the /// fade times and `overlayMessageString` / `overlayMessageTime`. #[derive(Clone, Debug, PartialEq)] From ffc343aadd48cefd6d4aa95c6fa946ae9f6310f8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:37:39 +0100 Subject: [PATCH 071/132] Make execute on origin and leasher find their entity --- .../src/game/commands/execute.rs | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..88d24e9bc 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -606,6 +606,68 @@ impl Game<'_> { .collect(), _ => Vec::new(), }, + // Leashable.getLeashHolder: a fence knot is not an entity here. + Some("leasher") => match entity { + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .and_then(|m| m.extra.leash) + .and_then(|holder| match holder { + horizon_client::mobs::leash::Holder::Player => Some(Target::Player), + horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)), + horizon_client::mobs::leash::Holder::Knot(_) => None, + }) + .into_iter() + .collect(), + _ => Vec::new(), + }, + // TraceableEntity.getOwner: who shot a projectile, who threw an + // item, who summoned a vex. + Some("origin") => match entity { + Target::Projectile(i) => self + .creatures + .projectiles + .get(i) + .and_then(|p| match (p.owner?, p.guest) { + // A guest's shot: `Who::Player` is them. + (horizon_client::mobs::Who::Player, Some(conn)) + if self.lan_acting == Some(conn) => + { + Some(Target::Player) + } + (horizon_client::mobs::Who::Player, Some(conn)) => { + Some(Target::Guest(conn)) + } + (horizon_client::mobs::Who::Player, None) => Some(Target::Player), + (horizon_client::mobs::Who::Mob(id), _) => Some(Target::Mob(id)), + }) + .into_iter() + .collect(), + Target::Item(id) => self + .dropped + .iter() + .find(|d| d.id == id) + .and_then(|d| d.thrower) + .and_then(|words| { + let uuid = words + .iter() + .fold(0u128, |all, w| all << 32 | u128::from(*w as u32)); + self.target_by_uuid(uuid) + }) + .into_iter() + .collect(), + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id && m.kind.id == "minecraft:vex") + .map(|m| m.extra.counter2 as u32) + .filter(|owner| *owner != 0) + .map(Target::Mob) + .into_iter() + .collect(), + _ => Vec::new(), + }, Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(), Some("controller") | Some("passengers") => match entity { Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => { From b92a53e47cbed57d92d0c6a38f605dd8cec12ec9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:37:52 +0100 Subject: [PATCH 072/132] Swing and pose the main arm of a left-handed mob --- .../examples/probe/entity_anim_fixture.rs | 1 + crates/horizon-client/src/mobs/anim.rs | 39 +++++++++----- crates/horizon-client/src/mobs/illager.rs | 11 ++-- crates/horizon-client/src/mobs/piglin.rs | 52 +++++++++++-------- 4 files changed, 67 insertions(+), 36 deletions(-) diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs index 4aceb9f6f..4582033fe 100644 --- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -592,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> { pose, num("maxCrossbowChageDuration"), num("ticksUsingItem"), + false, ); } Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => { diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b81f224ae..c183aa59d 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -248,18 +248,24 @@ pub enum ArmPose { pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } -/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm. -pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) { +/// `AnimationUtils.swingWeaponDown`: the main arm swings down, the other +/// one hangs and bobs. +pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32, left_main: bool) { let attack2 = (swing * PI).msin(); let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); + let (main, off) = if left_main { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); - p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15); - p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5); - p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4; - p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4; + p.xrot(main, -1.884_955_8 + (age * 0.09).mcos() * 0.15); + p.xrot(off, -0.0 + (age * 0.19).mcos() * 0.5); + p.get(main)[3] += attack2 * 2.2 - attack * 0.4; + p.get(off)[3] += attack2 * 1.2 - attack * 0.4; bob(p, "right_arm", age, 1.0); bob(p, "left_arm", age, -1.0); } @@ -286,6 +292,8 @@ pub struct Hum { pub using_item: bool, /// The arm the current swing moves (`Some(true)` for the right one). pub swing_right_arm: Option, + /// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it. + pub left_main: bool, } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -303,6 +311,7 @@ impl Hum { swim: 0.0, using_item: false, swing_right_arm: None, + left_main: false, } } } @@ -315,7 +324,7 @@ impl ArmPose { } } /// `AnimationUtils.animateCrossbowHold`. -fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { +pub(super) fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { let (hold, shoot) = if in_right { ("right_arm", "left_arm") } else { @@ -327,7 +336,7 @@ fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { p.xrot(shoot, -1.5 + hx); } /// `AnimationUtils.animateCrossbowCharge`. -fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { +pub(super) fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { let (hold, pull) = if in_right { ("right_arm", "left_arm") } else { @@ -418,13 +427,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { pose_arm(p, h.right, true, h); } } - // setupAttackAnimation (WHACK swing with the right arm). + // setupAttackAnimation (WHACK swing with the arm of the swinging hand). let hx = p.get("head")[3]; let swing = s.swing; + let swing_left = h.swing_right_arm.map_or(h.left_main, |right| !right); if swing > 0.0 && h.weapon_swing { - swing_weapon_down(p, swing, s.age); + swing_weapon_down(p, swing, s.age, h.left_main); } else if swing > 0.0 { - let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + let mut body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + if swing_left { + body_y = -body_y; + } p.yrot("body", body_y); let age_scale = if s.baby { 0.5 } else { 1.0 }; { @@ -444,7 +457,7 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { let eased = 1.0 - (1.0 - swing).powi(4); let aa = (eased * PI).msin(); let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75; - let r = p.get("right_arm"); + let r = p.get(if swing_left { "left_arm" } else { "right_arm" }); r[3] -= aa * 1.2 + bb; r[4] += body_y * 2.0; r[5] += (swing * PI).msin() * -0.4; @@ -652,6 +665,7 @@ pub fn setup( } else { Hum::new(main, ArmPose::Empty) }; + h.left_main = m.main_arm_left(); h.zombie = Some(m.ai.aggressive); h.holding = m.extra.main_hand.is_some(); h.crouching = m.extra.crouching; @@ -715,6 +729,7 @@ pub fn setup( h.swim = m.extra.swim.amount(s.partial); h.using_item = m.extra.using_item > 0; h.swing_right_arm = m.extra.swing_right_arm; + h.left_main = m.main_arm_left(); humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index a037e7c5f..9bdfec3e2 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -672,7 +672,12 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.xrot("right_arm", x + a * 1.2 - b * 0.4); p.xrot("left_arm", x + a * 1.2 - b * 0.4); } else { - // swingWeaponDown (right-handed). + // swingWeaponDown: the main arm swings down. + let (main, off) = if m.main_arm_left() { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; let swing = s.swing; let a2 = (swing * PI).msin(); let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); @@ -681,11 +686,11 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); p.xrot( - "right_arm", + main, -1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4), ); p.xrot( - "left_arm", + off, -0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4), ); } diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index de9ba42dd..a057581e6 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -431,7 +431,14 @@ pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { } else { PiglinPose::Default }; - piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32); + piglin_pose( + p, + s, + pose, + 25.0, + m.extra.using_item as f32, + m.main_arm_left(), + ); } /// `PiglinArmPose`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -443,11 +450,19 @@ pub enum PiglinPose { CrossbowCharge, AdmiringItem, } -/// `PiglinModel.setupAnim` for a piglin facing right-handed. -pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) { - use super::anim::{ArmPose, Hum, humanoid}; +/// `PiglinModel.setupAnim`; `left` when the piglin's main arm is the left one. +pub fn piglin_pose( + p: &mut Poses, + s: &State, + pose: PiglinPose, + max_charge: f32, + ticks: f32, + left: bool, +) { + use super::anim::{ArmPose, Hum, crossbow_charge, crossbow_hold, humanoid}; let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); h.weapon_swing = pose == PiglinPose::MeleeWeapon; + h.left_main = left; h.charge = (max_charge, ticks); humanoid(p, s, &h); ears(p, s); @@ -474,27 +489,22 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5; p.get("body")[1] += (dance * 40.0).msin() * 0.35; } - PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8), - PiglinPose::CrossbowHold => { - p.yrot("right_arm", -0.3 + hy); - p.yrot("left_arm", 0.6 + hy); - p.xrot("right_arm", -PI / 2.0 + hx + 0.1); - p.xrot("left_arm", -1.5 + hx); - } - PiglinPose::CrossbowCharge => { - p.yrot("right_arm", -0.8); - p.xrot("right_arm", -0.970_796_35); - p.xrot("left_arm", -0.970_796_35); - let alpha = ticks.clamp(0.0, max_charge) / max_charge; - p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4)); - let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35); - p.xrot("left_arm", x); + // holdWeaponHigh + PiglinPose::MeleeWeapon if s.swing == 0.0 => { + p.xrot(if left { "left_arm" } else { "right_arm" }, -1.8) } + PiglinPose::CrossbowHold => crossbow_hold(p, hx, hy, !left), + PiglinPose::CrossbowCharge => crossbow_charge(p, max_charge, ticks, !left), PiglinPose::AdmiringItem => { p.xrot("head", 0.5); p.yrot("head", 0.0); - p.yrot("left_arm", 0.5); - p.xrot("left_arm", -0.9); + if left { + p.yrot("right_arm", -0.5); + p.xrot("right_arm", -0.9); + } else { + p.yrot("left_arm", 0.5); + p.xrot("left_arm", -0.9); + } } _ => {} } From 46b71954e162c8b355e26d8afb132d2060bf5fcf Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:38:38 +0100 Subject: [PATCH 073/132] Make the High Contrast option turn its resource pack on and off --- crates/horizon-client/src/options_ui.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..b6a3a0f3e 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -2533,6 +2533,17 @@ impl OptionsUi { if opt == Opt::Preset { apply_preset(s); } + if opt == Opt::HighContrast { + // Options.highContrast: the built-in pack follows the option. + let on = s.resource_packs.iter().any(|id| id == "high_contrast"); + if on != s.high_contrast { + s.resource_packs.retain(|id| id != "high_contrast"); + if s.high_contrast { + s.resource_packs.push("high_contrast".into()); + } + events.push(Event::Packs(s.resource_packs.clone())); + } + } events.push(Event::Changed); } Act::Extra(item) => { 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 074/132] 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 4201fd23c0dda6ab5ff3624cc79e4c322800980c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:39:05 +0100 Subject: [PATCH 075/132] Use real eye heights in /execute and keep the anchor on positioned as --- .../src/game/commands/execute.rs | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..c48cd8adf 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -145,9 +145,44 @@ impl Game<'_> { .iter() .find(|m| m.id == id) .map_or(0.0, |m| m.eye_y() - m.position.y), - _ => 0.0, + // An armor stand's dimensions are halved when small and empty + // when a marker (ArmorStand.getDefaultDimensions). + Target::Stand(id) => { + let stand = self.armor_stands.iter().find(|a| a.id == id); + let scale = match stand { + Some(a) if a.marker => 0.0, + Some(a) if a.small => 0.5, + _ => 1.0, + }; + scale * self.type_eye_height(&self.target_type(t)) + } + // Entity.getEyeHeight: the type's dimensions. + _ => self.type_eye_height(&self.target_type(t)), } } + /// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`, + /// read once. + fn type_eye_height(&self, ty: &str) -> f64 { + static EYE_HEIGHTS: std::sync::OnceLock> = + std::sync::OnceLock::new(); + EYE_HEIGHTS + .get_or_init(|| { + std::fs::read(self.options.resources.join("entity-types.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v.as_object().map(|o| { + o.iter() + .filter_map(|(k, t)| Some((k.clone(), t["eye_height"].as_f64()?))) + .collect() + }) + }) + .unwrap_or_default() + }) + .get(ty) + .copied() + .unwrap_or(0.0) + } /// EntityAnchorArgument.Anchor.apply. pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] { match s.entity { @@ -467,9 +502,10 @@ impl Game<'_> { "positioned" if c.has("as") => targets(self)? .into_iter() .filter_map(|t| { + // withPosition keeps the anchor (only `positioned ` + // resets it to the feet). Some(Source { pos: self.target_position(t)?, - eyes: false, ..s }) }) From ad6f2320b0a6bbfaa016f9b1f978d8348989015a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:40:06 +0100 Subject: [PATCH 076/132] Wire the Music Frequency option to the music manager --- crates/horizon-client/src/game.rs | 9 ++++++++- crates/horizon-client/src/game/music.rs | 7 ++++++- crates/horizon-client/src/options_ui.rs | 15 ++++++++++++++- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 20f6e01bc..0e4756abf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -12645,7 +12645,14 @@ impl<'a> Game<'a> { level, session_lock: None, audio, - music: Default::default(), + music: { + // The manager starts with the saved option (MusicManager's constructor). + let mut music = horizon_client::music::MusicManager::default(); + music.frequency = horizon_client::music::MusicFrequency::parse( + &settings.file.name("musicFrequency"), + ); + music + }, ambience: Default::default(), sound_paused: false, cart_sounds: HashSet::new(), diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index fa5e71f7b..97ca3763e 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -3,7 +3,7 @@ use super::Game; use horizon_client::{ blocks::Fluid, - music::{BackgroundMusic, Music, Situation}, + music::{BackgroundMusic, Music, MusicFrequency, Situation}, sound_engine::TickContext, }; @@ -11,6 +11,11 @@ impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. pub(super) fn tick_music(&mut self) { let (music, volume) = self.situational_music(); + // Options.musicFrequency's listener: MusicManager.setMinutesBetweenSongs. + let frequency = MusicFrequency::parse(&self.settings.file.name("musicFrequency")); + if frequency != self.music.frequency { + self.music.set_frequency(frequency, music.as_ref()); + } // LevelLoadingScreen: no new track before the player is in the world. let loading = self.title.is_none() && self.player.is_none() && self.win.is_none(); self.music diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..50eb50f6f 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -67,6 +67,7 @@ pub enum Opt { ReducedDebugInfo, HighContrast, ShowSubtitles, + MusicFrequency, NotificationDisplayTime, Narrator, TextBackground, @@ -192,6 +193,7 @@ impl Opt { Opt::NarratorHotkey => "narratorHotkey", Opt::RotateWithMinecarts => "rotateWithMinecart", Opt::HighContrastBlockOutlines => "highContrastBlockOutline", + Opt::MusicFrequency => "musicFrequency", _ => return None, }) } @@ -248,6 +250,7 @@ impl Opt { Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", + Opt::MusicFrequency => "options.music_frequency", Opt::NotificationDisplayTime => "options.notifications.display_time", Opt::Narrator => "options.narrator", Opt::TextBackground => "options.accessibility.text_background", @@ -578,6 +581,11 @@ impl Opt { Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), Opt::ShowSubtitles => on_off(s.show_subtitles), + Opt::MusicFrequency => tr([ + "options.music_frequency.default", + "options.music_frequency.frequent", + "options.music_frequency.constant", + ][s.file.int("musicFrequency").clamp(0, 2) as usize]), Opt::ForceUnicode => on_off(s.force_unicode), Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), Opt::PadEnabled => on_off(s.controller.enabled), @@ -747,6 +755,11 @@ impl Opt { Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles, + Opt::MusicFrequency => { + let n = next(s.file.int("musicFrequency").clamp(0, 2) as u8, 3); + s.file + .set("musicFrequency", crate::options_file::V::Int(i32::from(n))); + } Opt::ForceUnicode => s.force_unicode = !s.force_unicode, Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, Opt::PadEnabled => s.controller.enabled = !s.controller.enabled, @@ -1411,7 +1424,7 @@ impl OptionsUi { let mut rows = vec![Row::Big(Opt::Volume(0))]; let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); rows.extend(pairs(&others)); - rows.extend(pairs(&[Opt::ShowSubtitles])); + rows.extend(pairs(&[Opt::ShowSubtitles, Opt::MusicFrequency])); rows } Page::Controls => { From 34dabe4afdfafd89c5bb1240843d4253d4f74fa2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:41:49 +0100 Subject: [PATCH 077/132] Grey out Chunk Fade-in, Improved Transparency and Chunk Builder --- crates/horizon-client/src/options_ui.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..d441819d8 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -172,6 +172,10 @@ impl Opt { | Opt::MonochromeLogo | Opt::RotateWithMinecarts | Opt::HighContrastBlockOutlines + // Saved, but nothing in rendering reads them yet. + | Opt::ChunkFade + | Opt::ImprovedTransparency + | Opt::ChunkBuilder ) } fn file_key(self) -> Option<&'static str> { From c85f6f2e398eb73ececd12a1dadf3c10383de945 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:50:13 +0100 Subject: [PATCH 078/132] Give polar bears their attack AI and rearing pose Polar bears only panicked and strolled. They now follow vanilla's goals: melee attack that rears up and growls before each strike, hurt-by and cub-defending targets, anger at the player, and fox hunting. A hurt cub calls the adults. The standing flag is synched and the client animates it. --- crates/horizon-client/src/game/lan.rs | 8 + crates/horizon-client/src/game/remote.rs | 4 + .../src/game/remote_mob_data.rs | 2 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/ai.rs | 4 + crates/horizon-client/src/mobs/body_anim.rs | 2 +- crates/horizon-client/src/mobs/goals.rs | 41 +++- crates/horizon-client/src/mobs/polar_bear.rs | 191 ++++++++++++++++++ 8 files changed, 250 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/mobs/polar_bear.rs diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..b82d0ed1a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -337,6 +337,14 @@ fn mob_meta( } defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); } + // PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear + // rears up; the client animates it. + "minecraft:polar_bear" => { + if e.flag { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + } // SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose. "minecraft:evoker" | "minecraft:illusioner" => { if e.variant2 != 0 { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..a8ed5800d 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3517,6 +3517,10 @@ impl Game<'_> { ) { horizon_client::mobs::guardian::client_tick(m); } + // PolarBear.tick: the stand animation follows the synched flag. + if m.species() == horizon_client::mobs::Species::PolarBear { + horizon_client::mobs::polar_bear::client_tick(m); + } if m.hurt_time > 0 { m.hurt_time -= 1; } diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..b023cdd01 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -59,6 +59,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti Who::Mob(*target as u32) }); } + // PolarBear.DATA_STANDING_ID: the client animates the rearing. + (Species::PolarBear, 18, Value::Bool(standing)) => m.extra.flag = *standing, // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f88fa7b06..39ac31ce4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -50,6 +50,7 @@ pub mod nether; pub mod path; pub mod phantom; pub mod piglin; +pub mod polar_bear; pub mod rabbit; pub mod raider; pub mod ravager; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8505d71d2..d3a0df0ac 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -106,6 +106,7 @@ pub enum Family { Strider, Bat, Bee, + PolarBear, } pub fn family(s: Species) -> Family { use Species as S; @@ -167,6 +168,7 @@ pub fn family(s: Species) -> Family { S::Strider => Family::Strider, S::Bat => Family::Bat, S::Bee => Family::Bee, + S::PolarBear => Family::PolarBear, _ => Family::Generic, } } @@ -224,6 +226,7 @@ pub fn register(m: &mut Mob) { Family::Strider => super::strider::register(m), Family::Bat => super::bat::register(m), Family::Bee => super::bee::register(m), + Family::PolarBear => super::polar_bear::register(m), } // FloatGoal's constructor lets the navigation float, as do the // constructors of these brain-driven and flying mobs. A floater rises @@ -984,6 +987,7 @@ fn species_ai_step( Species::Wither => super::wither::ai_step(m, w, events), Species::Allay => super::allay::ai_step(m), Species::Bee => super::bee::ai_step(m, w), + Species::PolarBear => super::polar_bear::ai_step(m, w), Species::Breeze => super::breeze::ai_step(m), Species::Sniffer => super::sniffer::ai_step(m, events), Species::HappyGhast => super::happy_ghast::ai_step(m, w), diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 4411d347b..4cc6662ce 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -959,7 +959,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { let st = &m.anim.states; match m.species() { Species::Goat => goat(p, s, &Goat::from_mob(m)), - Species::PolarBear => polar_bear(p, s, 0.0), + Species::PolarBear => polar_bear(p, s, super::polar_bear::standing_scale(m, s.partial)), Species::Panda => panda(p, s, &Panda::default()), Species::Llama | Species::TraderLlama => { llama(p, s, m.extra.chested && !s.baby); diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index cbb7cfec5..3b82f3094 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1017,6 +1017,8 @@ pub struct MeleeAttack { pub speed: f64, pub follow_unseen: bool, pub zombie: bool, + /// `PolarBear.PolarBearMeleeAttackGoal`: rears up before each strike. + pub polar_bear: bool, path_target: [f64; 3], recalc: i32, pub until_attack: i32, @@ -1031,6 +1033,7 @@ impl MeleeAttack { speed, follow_unseen, zombie: false, + polar_bear: false, path_target: [0.0; 3], recalc: 0, until_attack: 0, @@ -1043,6 +1046,10 @@ impl MeleeAttack { self.zombie = true; self } + pub fn polar_bear(mut self) -> Self { + self.polar_bear = true; + self + } pub fn interval(mut self, ticks: i32) -> Self { self.interval = ticks; self @@ -1098,6 +1105,9 @@ impl Goal for MeleeAttack { } m.ai.aggressive = false; m.nav_stop(); + if self.polar_bear { + super::polar_bear::set_standing(m, false); + } } fn every_tick(&self) -> bool { true @@ -1131,7 +1141,17 @@ impl Goal for MeleeAttack { self.recalc = adjusted(true, self.recalc); } self.until_attack = (self.until_attack - 1).max(0); - if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { + if self.polar_bear { + let cooldown = adjusted(true, self.interval); + super::polar_bear::check_and_perform_attack( + &mut self.until_attack, + cooldown, + m, + who, + &t, + cx, + ); + } else if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { self.until_attack = adjusted(true, self.interval); m.swing(); super::ai::do_hurt_target(m, who, cx); @@ -1422,6 +1442,9 @@ pub struct HurtByTarget { /// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others /// only when the attacker is in sight. pub bee: bool, + /// `PolarBear.PolarBearHurtByTargetGoal`: a hurt cub only calls the + /// adult bears and drops the target itself. + pub polar_bear: bool, timestamp: i32, st: TargetState, } @@ -1432,6 +1455,7 @@ impl HurtByTarget { alert_except: vec![], ignore: vec![], bee: false, + polar_bear: false, timestamp: 0, st: TargetState { unseen_memory: 300, @@ -1451,6 +1475,10 @@ impl HurtByTarget { self.bee = true; self } + pub fn polar_bear(mut self) -> Self { + self.polar_bear = true; + self + } } impl Default for HurtByTarget { fn default() -> Self { @@ -1462,6 +1490,8 @@ impl Goal for HurtByTarget { fn name(&self) -> &'static str { if self.bee { "BeeHurtByOtherGoal" + } else if self.polar_bear { + "PolarBearHurtByTargetGoal" } else { "HurtByTarget" } @@ -1500,7 +1530,9 @@ impl Goal for HurtByTarget { self.timestamp = m.ai.last_hurt_by_time; self.st.unseen_memory = 300; self.st.unseen = 0; - if self.alert + // PolarBearHurtByTargetGoal.start: a cub alerts the adults itself. + let cub = self.polar_bear && m.is_baby(); + if (self.alert || cub) && let Some(by) = m.ai.target { let range = m.attrs.follow_range; @@ -1520,6 +1552,8 @@ impl Goal for HurtByTarget { && (s.position.z - pos.z).abs() <= range + 1.0 }) .filter(|s| !self.alert_except.contains(&s.species)) + // PolarBearHurtByTargetGoal.alertOther: adults only. + .filter(|s| !(self.polar_bear && s.baby)) .filter(|s| Who::Mob(s.id) != by) .map(|s| s.id) .collect(); @@ -1534,6 +1568,9 @@ impl Goal for HurtByTarget { }); } } + if cub { + m.ai.target = None; + } } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { m.ai.target = None; diff --git a/crates/horizon-client/src/mobs/polar_bear.rs b/crates/horizon-client/src/mobs/polar_bear.rs new file mode 100644 index 000000000..bfd464a93 --- /dev/null +++ b/crates/horizon-client/src/mobs/polar_bear.rs @@ -0,0 +1,191 @@ +//! Polar bears (`PolarBear`): a neutral animal that defends its cubs, +//! fights back when hurt, and rears up before each swing. A cub flees what +//! hurts it and calls the adults. +//! +//! `extra.flag` is `DATA_STANDING_ID`, `extra.counter` the warning sound's +//! delay, `extra.anger` the `NeutralMob` anger left and `extra.flag2` whether +//! the player is who it is angry at. `anim.v[STAND]` is +//! `clientSideStandAnimation`. +use horizon_core::{geometry::Vec3, random::RandomSource}; + +use super::{ + DamageKind, Mob, MobWorld, Species, Who, + goals::{ + Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, MOVE, MeleeAttack, + NearestTarget, Panic, RandomLookAround, Stroll, goal_clone, + }, + world::TargetInfo, +}; + +/// `anim.v` slot of `clientSideStandAnimation`. +pub const STAND: usize = 0; +/// `STAND_ANIMATION_TICKS`. +const STAND_TICKS: f32 = 6.0; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, MeleeAttack::new(1.25, true).polar_bear()); + g.add(1, PolarBearPanic(Panic::new(2.0))); + g.add(4, FollowParent::new(1.25)); + g.add(5, Stroll::new(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + let t = &mut m.ai.targets; + t.add(1, HurtByTarget::new().polar_bear()); + // PolarBearAttackPlayersGoal: players near a cub, within half the + // follow range, never for a cub itself. + t.add( + 2, + NearestTarget::player(true) + .interval(20) + .follow_scale(0.5) + .reach() + .gate(|m, _| !m.is_baby()) + .when(cub_nearby) + .named("PolarBearAttackPlayersGoal"), + ); + t.add( + 3, + NearestTarget::player(true).when(|m, _| m.extra.anger > 0 && m.extra.flag2), + ); + t.add( + 4, + NearestTarget::species(&[Species::Fox], true) + .interval(10) + .reach() + .when(|m, _| !m.is_baby()), + ); +} + +/// `PolarBearAttackPlayersGoal.canUse`: a polar bear cub within 8 blocks +/// (4 up and down). +fn cub_nearby(m: &Mob, w: &MobWorld) -> bool { + let area = m.bounds().inflate(Vec3::new(8.0, 4.0, 8.0)); + w.others_near(area) + .any(|s| s.species == Species::PolarBear && s.baby && s.bounds.intersects(area)) +} + +/// `PanicGoal` with a function of the bear's age for the damage tag: a cub +/// panics at `PANIC_CAUSES`, an adult only at `PANIC_ENVIRONMENTAL_CAUSES`. +#[derive(Clone, Debug)] +struct PolarBearPanic(Panic); +impl Goal for PolarBearPanic { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (m.is_baby() || environmental_panic(m)) && self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES` (fire, lava, cactus), or +/// burning. +fn environmental_panic(m: &Mob) -> bool { + m.fire_ticks > 0 && !m.kind.flags.fire_immune + || m.last_damage.is_some_and(|(d, t)| { + matches!( + d.kind, + DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Cactus + ) && i64::from(m.age) - t <= 40 + }) +} + +/// `PolarBear.setStanding`. +pub fn set_standing(m: &mut Mob, standing: bool) { + m.extra.flag = standing; +} + +/// `PolarBear.playWarningSound`. +fn play_warning_sound(m: &mut Mob, cx: &mut Cx) { + if m.extra.counter <= 0 { + m.voice("entity.polar_bear.warning", cx.events); + m.extra.counter = 40; + } +} + +/// `PolarBearMeleeAttackGoal.checkAndPerformAttack`: strike when ready and +/// in reach, rear up and growl in the last 10 ticks while close. +pub fn check_and_perform_attack( + until_attack: &mut i32, + cooldown: i32, + m: &mut Mob, + who: Who, + t: &TargetInfo, + cx: &mut Cx, +) { + if *until_attack <= 0 && m.within_melee_range(t) && m.sees(cx.w, who) { + *until_attack = cooldown; + super::ai::do_hurt_target(m, who, cx); + set_standing(m, false); + return; + } + let reach = t.bounds.size().x as f32 + 3.0; + if m.distance_sqr(t.position) < f64::from(reach * reach) { + if *until_attack <= 0 { + set_standing(m, false); + *until_attack = cooldown; + } + if *until_attack <= 10 { + set_standing(m, true); + play_warning_sound(m, cx); + } + } else { + *until_attack = cooldown; + set_standing(m, false); + } +} + +/// `PolarBear.tick`'s client half: `clientSideStandAnimation` follows the +/// synched standing flag by one tick a tick. A client of a server runs it +/// too. +pub fn client_tick(m: &mut Mob) { + let v = m.anim.v[STAND]; + m.anim.vo[STAND] = v; + let step = if m.extra.flag { 1.0 } else { -1.0 }; + m.anim.v[STAND] = (v + step).clamp(0.0, STAND_TICKS); +} +/// `PolarBear.getStandingAnimationScale`. +pub fn standing_scale(m: &Mob, partial: f32) -> f32 { + m.anim.lerp(STAND, partial) / STAND_TICKS +} + +/// `PolarBear.tick`: the stand animation, the warning sound's delay and +/// `NeutralMob.updatePersistentAnger`. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + client_tick(m); + if m.extra.counter > 0 { + m.extra.counter -= 1; + } + if m.ai.target.is_some() { + // Anger follows the target and starts over every tick it is held: + // 20 to 39 seconds (`PERSISTENT_ANGER_TIME`). + m.extra.flag2 = m.ai.target == Some(Who::Player); + m.extra.anger = 400 + m.random.next_int_bound(381).unwrap_or(0); + } else if m.extra.anger > 0 { + m.extra.anger -= 1; + if m.extra.anger == 0 { + stop_being_angry(m); + } + } + // A player in creative or spectator mode is forgiven at once. + if m.extra.flag2 && w.player.as_ref().is_some_and(|p| p.creative || p.spectator) { + stop_being_angry(m); + } +} +/// `NeutralMob.stopBeingAngry`. +fn stop_being_angry(m: &mut Mob) { + m.ai.last_hurt_by = None; + m.ai.target = None; + m.extra.anger = 0; + m.extra.flag2 = false; +} From bb9b0424b44606cd7af0bb57e4610d24c0af2a68 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:52:11 +0100 Subject: [PATCH 079/132] Axolotl rain: the biome's height-adjusted temperature Level.isRainingAt takes Biome.getHeightAdjustedTemperature, which applies the frozen oceans' temperature modifier and the height noise above the snow level; reuse horizon-world's version instead of a simplified copy. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/biome.rs | 25 ++++++++++++++++++++++++- crates/horizon-client/src/mobs/world.rs | 12 +++--------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 63ad004d4..9d68bfefa 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -1,7 +1,7 @@ //! Biome colours from the pinned biome definitions and colormaps //! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`). use crate::Result; -use horizon_core::{noise::SimplexNoise, random::LegacyRandom}; +use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -30,6 +30,8 @@ pub struct BiomeInfo { pub creature_probability: f32, pub name: String, pub temperature: f32, + /// `temperature_modifier: frozen` (the frozen oceans). + pub frozen: bool, pub downfall: f32, pub precipitation: bool, pub grass: u32, @@ -42,6 +44,26 @@ pub struct BiomeInfo { pub fog: Option, pub water_fog: u32, } +impl BiomeInfo { + /// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler + /// with height above `sea_level + 17`. + pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 { + use horizon_world::worldgen::biome_temperature::{ + BiomeTemperatureSettings, TemperatureModifier, + }; + BiomeTemperatureSettings { + base_temperature: self.temperature, + modifier: if self.frozen { + TemperatureModifier::Frozen + } else { + TemperatureModifier::None + }, + has_precipitation: self.precipitation, + downfall: self.downfall, + } + .height_adjusted(pos, sea_level) + } +} pub struct Biomes { pub list: Vec, pub index: HashMap, @@ -129,6 +151,7 @@ impl Biomes { .as_f64() .unwrap_or(0.1) as f32, temperature, + frozen: v["temperature_modifier"].as_str() == Some("frozen"), downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), grass: color(&effects["grass_color"]) diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index db2557e72..f893559f6 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -178,8 +178,8 @@ impl MobWorld<'_> { self.world.light(x, y, z) >> 4 == 15 } /// Level.isRainingAt: raining, open to the sky, nothing motion blocking - /// above, and the biome's precipitation at the position (its temperature - /// lowered above the snow level) is rain, not snow or none. + /// above, and the biome's precipitation at the position is rain, not snow + /// or none. pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool { if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y { return false; @@ -188,13 +188,7 @@ impl MobWorld<'_> { return false; }; let biome = self.biomes.get(chunk.biome(x, y, z)); - let snow_level = self.sea_level + 17; - let temperature = if y > snow_level { - biome.temperature - (y - snow_level) as f32 * 0.05 / 40.0 - } else { - biome.temperature - }; - biome.precipitation && temperature >= 0.15 + biome.precipitation && biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15 } /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve /// at the raw (sky darkened) light level. 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 080/132] 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 06b046d8fc3046bc83ad0ee1ba946e2e25676931 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:07:17 +0100 Subject: [PATCH 081/132] Light, scaffolding and shulker box outlines follow the held item and the lid --- crates/horizon-client/src/blocks.rs | 2 +- crates/horizon-client/src/game.rs | 48 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index 27a36396a..8e906e1bc 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -90,7 +90,7 @@ pub const MAP_COLORS: [u32; 62] = [ 14200723, 8365974, ]; /// The 12 edges of the unit cube (outline data predating the export). -fn cube_edges() -> Vec<[f64; 6]> { +pub fn cube_edges() -> Vec<[f64; 6]> { let mut edges = Vec::new(); for a in 0..3 { for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..20cd34e0c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1806,9 +1806,46 @@ impl Game<'_> { fn reach(&self) -> f64 { if self.creative { 5.0 } else { 4.5 } } + /// Outline shapes that depend on more than the block state, as one box + /// in block space: `LightBlock` and `ScaffoldingBlock.getShape` are a full + /// block while the main hand holds the block's own item + /// (`CollisionContext.isHoldingItem`), and `ShulkerBoxBlock.getShape` + /// grows with the lid (`ShulkerBoxBlockEntity.getBoundingBox`). + fn context_outline(&self, pos: [i32; 3], state: BlockStateId) -> Option<[f64; 6]> { + let name = &self.res.facts().get(state).name; + if matches!(&**name, "minecraft:light" | "minecraft:scaffolding") { + return self + .held() + .is_some_and(|s| *s.item == **name) + .then_some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + } + if !name.ends_with("shulker_box") { + return None; + } + let progress = self.be_anims.shulkers.get(&pos).map_or(0.0, |s| s.progress); + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + let d = facing_offset(facing.as_deref().unwrap_or("up")); + let mut b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + for a in 0..3 { + match d[a] { + 1 => b[a + 3] += 0.5 * f64::from(progress), + -1 => b[a] -= 0.5 * f64::from(progress), + _ => {} + } + } + Some(b) + } /// A block's outline boxes in world space (`getShape` plus the random offset). fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> { let state = self.world.block(pos[0], pos[1], pos[2]); + if let Some(b) = self.context_outline(pos, state) { + return vec![std::array::from_fn(|i| f64::from(pos[i % 3]) + b[i])]; + } let f = self.res.facts().get(state); let o = if f.outline_offset { self.pack @@ -10756,6 +10793,17 @@ impl Game<'_> { [0.0; 3] }; let p = h.pos.map(f64::from); + if let Some(b) = self.context_outline(h.pos, state) { + return horizon_client::blocks::cube_edges() + .iter() + .map(|e| { + std::array::from_fn(|i| { + let k = i % 3; + p[k] + b[k] + e[i] * (b[k + 3] - b[k]) + }) + }) + .collect(); + } f.outline_edges .iter() .map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + e[i])) From 94748162bc6103baa74ce633b88b702bebfb5923 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:08:59 +0100 Subject: [PATCH 082/132] Handle a dig packet before the move queued behind it The client breaks the block under its feet and falls in the same tick. The hub checked that move against the block that was still there and sent the player back. Moves queued behind a dig packet now wait for the next tick, after the break. --- crates/horizon-client/src/lan/hub.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..e2b36428a 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2043,6 +2043,20 @@ impl Hub { S::Chat(c) => self.handle_chat(i, c, events), S::ChatAck(p) => self.chat_ack(i, p.offset, events), S::ChatSessionUpdate(p) => self.chat_session_update(i, p, events), + // handlePlayerAction (a dig starting, stopping or finishing) is the + // game's, run after this pass. A move queued behind it is checked + // against the block the player just broke and falls through, so it + // would be sent back; it waits for the next tick, when the block is + // gone, as vanilla handles the two packets in order. + S::PlayerAction(p) if p.action <= 3 => { + events.push(HostEvent::Packet(conn, Box::new(S::PlayerAction(p)))); + if matches!( + self.guests[i].inbox.front(), + Some(S::MovePlayerPos(_) | S::MovePlayerPosRot(_)) + ) { + break; + } + } other => events.push(HostEvent::Packet(conn, Box::new(other))), } } From 3755bb7d7763a38c5b81900abba45510212a28ae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:10:41 +0100 Subject: [PATCH 083/132] parity: stop harnesses on SIGTERM, and reap orphaned harness JVMs Nine vanilla Java servers from harness runs had been orphaned on the Mac mini for 2 to 5 days. Each harness runs in its own session (killpg on a timeout), so when a CI job was cancelled, its harnesses and their servers outlived parity.py. - parity.py: SIGTERM and SIGHUP exit through the finally blocks, which now stop the local executor's harnesses too, not only the remote hosts'. The worker (--worker) stops its harnesses the same way. - runner-gc.sh (every 6 h from launchd): stops Java processes whose parent is gone (launchd, init or systemd --user) and whose command line names a runner's checkout or a worktree's .local/, once ORPHAN_HOURS (default 3) old. Co-Authored-By: Claude Opus 5.5 --- docs/release-flow.md | 5 ++++- tools/ci/runner-gc.sh | 23 +++++++++++++++++++++++ tools/parity.py | 32 +++++++++++++++++++++++++------- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/docs/release-flow.md b/docs/release-flow.md index b0d435c29..7d33b5585 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -420,6 +420,9 @@ Releases ship often, so nothing they leave behind may grow without bound. (`~/.actions-runners/runner-gc.sh`, plist `dev.horizon.runner-gc`), never from a pull request's checkout. It skips a runner in a job, removes a checkout's cargo build folders past 12 GB (`MAX_TARGET_GB`) and harness work folders under `.local/` untouched for 3 days (`STALE_DAYS`), and keeps the 2 newest shared preparations (`KEEP_PREPARED`) - while no runner works. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes + while no runner works. It also stops harness JVMs (vanilla servers, oracles) left orphaned for 3 hours + (`ORPHAN_HOURS`): parent gone, command line under a runner's checkout or a worktree's `.local/`. `tools/parity.py` + stops its own harnesses on SIGTERM and SIGHUP (a cancelled job), so these come only from a SIGKILL or a harness run + by hand. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes comes back from the cache. Update the copy after changing the script: `ssh macmini 'curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/tools/ci/runner-gc.sh -o ~/.actions-runners/runner-gc.sh'`. diff --git a/tools/ci/runner-gc.sh b/tools/ci/runner-gc.sh index 0f4f1e4c2..7ccf69ff0 100755 --- a/tools/ci/runner-gc.sh +++ b/tools/ci/runner-gc.sh @@ -9,6 +9,10 @@ # the shared vanilla data) that nothing touched for STALE_DAYS go; a harness that runs again rebuilds its own. # .local/parity-runner (run state, oracle cache) stays. # - The shared prepared resources keep their KEEP_PREPARED newest preparations, only while no runner works. +# - Java processes harnesses left behind (vanilla servers, oracles) go once ORPHAN_HOURS old: those whose parent +# is gone (adopted by launchd, init or systemd --user) and whose command line names a runner's checkout or a +# worktree's .local/. A job cancelled while it ran left such servers for days (2026-10-26); tools/parity.py now +# stops its harnesses on SIGTERM, and this catches what it can't (SIGKILL, a harness run by hand). set -euo pipefail root=${RUNNERS:-$HOME/.actions-runners} max_kb=$(( ${MAX_TARGET_GB:-12} * 1024 * 1024 )) @@ -42,6 +46,25 @@ for runner in "$root"/horizon "$root"/horizon-[0-9]*; do fi done +# [[dd-]hh:]mm:ss, as ps prints a process's age, in minutes. +minutes() { + local t=$1 d=0 h=0 m a b c + if [[ $t == *-* ]]; then d=${t%%-*}; t=${t#*-}; fi + IFS=: read -r a b c <<< "$t" + if [ -n "$c" ]; then h=$a m=$b; else m=$a; fi + echo $(( 10#$d * 1440 + 10#$h * 60 + 10#$m )) +} +orphan_min=$(( ${ORPHAN_HOURS:-3} * 60 )) +ps -A -o pid=,ppid=,etime=,command= | while read -r pid ppid etime command; do + case "$command" in *java*) ;; *) continue ;; esac + case "$command" in *"$root"/*/_work/*|*/.claude/worktrees/*/.local/*|*/code/horizon/.local/*) ;; *) continue ;; esac + [ "$(minutes "$etime")" -ge "$orphan_min" ] || continue + if [ "$ppid" != 1 ]; then + case "$(ps -o command= -p "$ppid" 2>/dev/null)" in *"systemd --user"*) ;; *) continue ;; esac + fi + if kill "$pid" 2>/dev/null; then echo "orphaned java $pid ($etime old) stopped: ${command:0:160}"; fi +done + prepared="$root/horizon/_work/horizon/shared-local/prepared" if [ "$any_busy" = 0 ] && [ -d "$prepared" ] && mkdir "$prepared/.lock" 2>/dev/null; then trap 'rmdir "$prepared/.lock" 2>/dev/null || true' EXIT diff --git a/tools/parity.py b/tools/parity.py index a5f7f2db1..426c843ca 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -48,6 +48,7 @@ import os from pathlib import Path, PurePosixPath import re import shutil +import signal import socket import subprocess import sys @@ -1134,6 +1135,14 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r return results, time.monotonic() - started_all +def exit_on_termination(): + """SIGTERM and SIGHUP (a cancelled CI job, a dropped ssh) end this process through its finally blocks, which stop + the running harnesses. Each runs in its own session, so without that they, and the vanilla servers they started, + outlive it (orphans of days were found on the Mac mini's runners, 2026-10-26).""" + for number in (signal.SIGTERM, signal.SIGHUP): + signal.signal(number, lambda received, _frame: sys.exit(128 + received)) + + def worker_main(shared_local): """`parity.py --worker SHARED_LOCAL`: run harnesses sent as JSON lines on stdin, answer on stdout.""" import queue as queues @@ -1169,13 +1178,20 @@ def worker_main(shared_local): built, errors = prebuild(first["prebuild"], default_build_jobs()) if first["prebuild"] else (True, "") executor = LocalExecutor(MACHINE_JOBS, int(memory_available() * 0.75), first["timeout"]) send({"hello": {"jobs": MACHINE_JOBS, "memory": executor.memory_budget, "built": built, "errors": errors[-4000:]}}) + try: + return serve(executor, inbox, queues.Empty, send, state, hasher) + finally: + executor.stop() + + +def serve(executor, inbox, empty, send, state, hasher): + """The worker's loop: start what the coordinating runner sends, report what finished, until its stdin ends.""" while True: try: message = inbox.get(timeout=0.2) - except queues.Empty: + except empty: message = False if message is None: - executor.stop() save_state(state) return 0 if message: @@ -1384,6 +1400,7 @@ def finished_run(failed): def main(): if len(sys.argv) > 1 and sys.argv[1] == "--trace": return trace_main(sys.argv[2], sys.argv[3], sys.argv[4:]) + exit_on_termination() if len(sys.argv) > 1 and sys.argv[1] == "--worker": return worker_main(sys.argv[2]) parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) @@ -1509,6 +1526,7 @@ def main(): jobs = 1 # harnesses that can only run here still need a slot remotes = [RemoteExecutor(host, config["hosts"][host], artifacts, config.get("local_only", {}), args.timeout) for host in hosts] + local = None try: if jobs: print("Building probes...", flush=True) @@ -1521,12 +1539,12 @@ def main(): where = "".join(f", plus {host}" for host in hosts) print(f"Running {len(selected)} harnesses, {jobs} at a time here{where}...", flush=True) reuse_oracles = not (args.fresh or args.all) - executors = [*remotes, LocalExecutor(jobs, int(memory_available() * 0.75), args.timeout, - REMOTE_LOCAL_PEAK if remotes and args.jobs is None else None)] - results, elapsed = run(selected, state, hasher, environment_key(hasher), executors, reuse_oracles, rounds, - known_flaky(config)) + local = LocalExecutor(jobs, int(memory_available() * 0.75), args.timeout, + REMOTE_LOCAL_PEAK if remotes and args.jobs is None else None) + results, elapsed = run(selected, state, hasher, environment_key(hasher), [*remotes, local], reuse_oracles, + rounds, known_flaky(config)) finally: - for executor in remotes: + for executor in [*remotes, *([local] if local else [])]: executor.stop() save_state(state) failed = sorted(name for name, record in results.items() if record["status"] != "pass") From 69bb81312816fc283a3c74c02c365e7391ef6608 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:16:34 +0100 Subject: [PATCH 084/132] game: cut a recipe page's title with an ellipsis A title wider than the panel ended at its edge mid-word ("Recipes: Oak P"); it now ends with vanilla's "..." (CommonComponents.ELLIPSIS). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mod_browser_recipes.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/mod_browser_recipes.rs b/crates/horizon-client/src/game/mod_browser_recipes.rs index 13b3b78e1..557ae9029 100644 --- a/crates/horizon-client/src/game/mod_browser_recipes.rs +++ b/crates/horizon-client/src/game/mod_browser_recipes.rs @@ -272,8 +272,14 @@ impl Game<'_> { batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true); horizon_client::widgets::record(&label, back, true); let room = layout.width() - back[2] - 4.0; - let fit = atlas.font.fit(&title, room); - let shown: String = title.chars().take(fit).collect(); + // Cut to the panel with vanilla's ellipsis (CommonComponents.ELLIPSIS). + let shown = if atlas.font.fit(&title, room) >= title.chars().count() { + title + } else { + let fit = atlas.font.fit(&title, room - atlas.font.width("...")); + let kept: String = title.chars().take(fit).collect(); + format!("{}...", kept.trim_end()) + }; batch.text( atlas, &shown, 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 085/132] 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 f4a235e02792a38530ea9058bc4bbbde2ef771e2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:20:45 +0100 Subject: [PATCH 086/132] Record a witch potion source only when it deals damage --- crates/horizon-client/src/game/creatures.rs | 40 ++++++++++++--------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e5d7660da..d266e62c4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2427,24 +2427,30 @@ impl Game<'_> { if d2 < 16.0 && !self.creative { let scale = 1.0 - d2.sqrt() / 4.0; let t = (f64::from(*ticks) * scale + 0.5) as i32; - // indirectMagic(potion, owner): the thrower, or the - // potion itself when it has none. - let owner = self - .combat - .projectile_owner - .filter(|id| self.mob_display_name(*id).is_some()); - match owner { - Some(owner) => self.note_attacker("minecraft:indirect_magic", owner), - None => self.note_direct_entity( - "minecraft:indirect_magic", - Text::translate("entity.minecraft.splash_potion", &[]), - ), - } match *effect { - "minecraft:instant_damage" => self.hurt_player_by( - "minecraft:indirect_magic", - 6.0 * (1 << *amplifier) as f32 * scale as f32, - ), + "minecraft:instant_damage" => { + // indirectMagic(potion, owner), built where the + // hurt happens: the thrower, or the potion + // itself when it has none. A status effect + // deals no damage, so it records no source. + let owner = self + .combat + .projectile_owner + .filter(|id| self.mob_display_name(*id).is_some()); + match owner { + Some(owner) => { + self.note_attacker("minecraft:indirect_magic", owner) + } + None => self.note_direct_entity( + "minecraft:indirect_magic", + Text::translate("entity.minecraft.splash_potion", &[]), + ), + } + self.hurt_player_by( + "minecraft:indirect_magic", + 6.0 * (1 << *amplifier) as f32 * scale as f32, + ) + } e if t > 20 => self.give_player_effect(e, t, *amplifier), _ => {} } From 0e96fb6d2a87ba22b6a640ac27d6a075b8626214 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:21:06 +0100 Subject: [PATCH 087/132] Disable unavailable options in the Graphics Advanced screen --- crates/horizon-client/src/graphics_style.rs | 3 +- crates/horizon-client/src/graphics_ui.rs | 33 ++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/graphics_style.rs b/crates/horizon-client/src/graphics_style.rs index e02a0e1d9..62979903b 100644 --- a/crates/horizon-client/src/graphics_style.rs +++ b/crates/horizon-client/src/graphics_style.rs @@ -118,8 +118,9 @@ impl Style { (x, y, w): (f32, f32, f32), label: &Text, hover: bool, + active: bool, ) { - ui::button(batch, atlas, x, y, w, 20.0, label, true, hover); + ui::button(batch, atlas, x, y, w, 20.0, label, active, hover); } pub fn slider( &self, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 3c7a40e02..d55e44d99 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -468,6 +468,10 @@ fn max_workers() -> u32 { } impl Item { + /// False for a setting whose system is not in Horizon yet (`Opt::available`). + fn available(self) -> bool { + !matches!(self, Item::Vanilla(o) if !o.available()) + } /// On/off settings and their value. pub fn switch(self, s: &Settings) -> Option { let g = &s.horizon; @@ -510,6 +514,9 @@ impl Item { } } pub fn set_slider(self, s: &mut Settings, v: f32) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.set_slider(s, v), Item::Horizon(h) => h.set_slider(s, v), @@ -517,6 +524,9 @@ impl Item { self.touched(s); } pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.cycle(s, back, framebuffer), Item::Horizon(h) => h.cycle(s, back), @@ -689,6 +699,7 @@ impl GraphicsUi { }) .collect(); let mut index = 0; + let mut tooltip = None; for wd in &widgets { let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0) && (!wd.list || (cursor.1 >= top && cursor.1 < bottom)); @@ -700,6 +711,13 @@ impl GraphicsUi { continue; } let label = item.label(s); + let live = item.available(); + if hover && !live { + tooltip = Some(atlas.font.split( + &Text::literal("This feature is not yet available in Horizon."), + 170.0, + )); + } match item.slider(s) { Some(value) => STYLE.slider( batch, @@ -709,7 +727,14 @@ impl GraphicsUi { value, hover || self.dragging == Some(item), ), - None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover), + None => STYLE.button( + batch, + atlas, + (wd.x, wd.y, wd.w), + &label, + hover && live, + live, + ), } STYLE.description( batch, @@ -732,6 +757,7 @@ impl GraphicsUi { (wd.x, wd.y, wd.w), &Text::literal(label), hover, + true, ); } } @@ -751,6 +777,9 @@ impl GraphicsUi { Level::Advanced => "Graphics: Advanced", }; STYLE.title(batch, atlas, &Text::literal(title)); + if let Some(lines) = tooltip { + ui::tooltip(batch, atlas, &lines, cursor); + } } /// A press (or a drag with `drag`) at `(x, y)`. pub fn click( @@ -788,6 +817,8 @@ impl GraphicsUi { } return match wd.target { Target::Button(action) => vec![Action::ButtonClick, action], + // A disabled control does nothing: no sound, no preset change. + Target::Item(item) if !item.available() => Vec::new(), Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); From abb4e7b5cd6a22fce0aa543e4266fbff8ae275ac Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:21:40 +0100 Subject: [PATCH 088/132] Record the thrower of guest drops and the player behind a lead --- crates/horizon-client/src/game.rs | 11 +++++++++-- crates/horizon-client/src/game/commands/execute.rs | 10 +++++++--- crates/horizon-client/src/game/leads.rs | 5 +++++ crates/horizon-client/src/mobs.rs | 2 ++ 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 20f6e01bc..48c182d10 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2320,11 +2320,18 @@ impl Game<'_> { yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, ]; self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); - if thrown_from_hand && self.lan_acting.is_none() { - let uuid = self.level.ensure_player_uuid(); + if thrown_from_hand { + let uuid = self.acting_player_uuid(); self.dropped.last_mut().unwrap().thrower = Some(uuid); } } + /// The UUID of the player acting: the guest whose turn it is, else the host. + pub(super) fn acting_player_uuid(&mut self) -> [i32; 4] { + match self.lan_acting_uuid { + Some(guest) => horizon_client::lan::playerdata::uuid_ints(guest), + None => self.level.ensure_player_uuid(), + } + } fn tick_items(&mut self) { let mut items = std::mem::take(&mut self.dropped); // ServerLevel.tick: only entities in entity-ticking chunks tick. diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 88d24e9bc..6635fc457 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -612,9 +612,13 @@ impl Game<'_> { .mobs .iter() .find(|m| m.id == id) - .and_then(|m| m.extra.leash) - .and_then(|holder| match holder { - horizon_client::mobs::leash::Holder::Player => Some(Target::Player), + .and_then(|m| m.extra.leash.map(|holder| (holder, m.extra.leash_player))) + .and_then(|(holder, player)| match holder { + // The player who tied it (the host's when unrecorded). + horizon_client::mobs::leash::Holder::Player => { + let uuid = player.or(self.level.player_uuid)?; + self.target_by_uuid(horizon_client::lan::playerdata::ints_uuid(uuid)) + } horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)), horizon_client::mobs::leash::Holder::Knot(_) => None, }) diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 8867157ee..ca70351c6 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -104,6 +104,9 @@ impl Game<'_> { }; let m = &mut self.mobs[i]; if let Some(h) = holder { + if h == Holder::Player { + m.extra.leash_player = Some(player_uuid); + } m.extra.leash = Some(h); m.extra.leash_pending = None; } else if m.age > 100 { @@ -201,7 +204,9 @@ impl Game<'_> { if self.mobs[index].extra.leash.is_some() { self.break_leash(id, true, false); } + let holder = self.acting_player_uuid(); self.mobs[index].extra.leash = Some(Holder::Player); + self.mobs[index].extra.leash_player = Some(holder); self.lead_sound("tied", at); // The lead is always used up. if let Some(stack) = self.held_mut().as_mut() { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 512339976..624c89f58 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -728,6 +728,8 @@ pub struct Extra { /// the spin the rope's torque gives it. pub leash: Option, pub leash_pending: Option, + /// The UUID of the player behind `Holder::Player` (host or guest). + pub leash_player: Option<[i32; 4]>, pub leash_spin: f64, /// More species scratch values. pub scratch: [i32; 4], 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 089/132] 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 56bf45cee512556c8c0a01eea04371876a117606 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:23:03 +0100 Subject: [PATCH 090/132] Keep the pack screen selection in step with High Contrast --- crates/horizon-client/src/options_ui.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index b6a3a0f3e..9170fd66e 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -2541,6 +2541,10 @@ impl OptionsUi { if s.high_contrast { s.resource_packs.push("high_contrast".into()); } + // PackSelectionScreen reads the repository each time it + // opens: the next one starts from this selection. + self.pack_selection = s.resource_packs.clone(); + self.pack_screen = None; events.push(Event::Packs(s.resource_packs.clone())); } } @@ -2712,6 +2716,7 @@ impl OptionsUi { { let ids = p.commit(); s.resource_packs = ids.clone(); + self.pack_selection = ids.clone(); events.push(Event::Packs(ids)); } } From 65c60ab996f596a020f614fa3f8e1f8ab1a83b7f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:23:38 +0100 Subject: [PATCH 091/132] Play remote sounds in the category the packet names --- crates/horizon-client/src/game/remote.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..e2c0be9c3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1741,7 +1741,17 @@ impl Game<'_> { f64::from(p.y) / 8.0, f64::from(p.z) / 8.0, ]; - self.audio.play(&name, Some(at), p.volume, p.pitch); + // ClientPacketListener.handleSoundEvent plays with packet.getSource(). + match usize::try_from(p.source) + .ok() + .filter(|s| *s < horizon_client::settings::SOUND_SOURCES.len()) + { + Some(source) => { + self.audio + .play_on(source, &name, Some(at), p.volume, p.pitch) + } + None => self.audio.play(&name, Some(at), p.volume, p.pitch), + } } } C::StopSound(p) => self From 26561d315c5d187c4d1f70af4f92455d030f9967 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:26:47 +0100 Subject: [PATCH 092/132] Preload the world data while the player chooses a world The worldgen bundle, the loot tables and the registries a server sends are read on a helper thread from the moment the player opens Singleplayer or Create World, so a world opening finds them ready. A world opened meanwhile waits for the part being read. If the player goes back to the title or to Multiplayer and opens no world for a minute, the preload is dropped: the three caches can now let go of what they hold. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 12 +++ crates/horizon-client/src/game/lan.rs | 22 ++++-- .../horizon-client/src/game/world_loading.rs | 75 +++++++++++++++++++ crates/horizon-client/src/structure_blocks.rs | 19 ++++- crates/horizon-client/src/vanillagen.rs | 14 +++- 5 files changed, 129 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..5acacd05c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8069,6 +8069,7 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { + world_loading::world_data_used(); if self.defer_world_entry(PendingWorldEntry::Local { folder: folder.to_owned(), name: name.map(str::to_owned), @@ -13025,6 +13026,17 @@ impl Game<'_> { if self.rest_loader.is_some() { return Ok(()); } + let on_world_screens = self.title.as_ref().is_some_and(|title| { + !matches!( + title.mode, + horizon_client::title::Mode::Main | horizon_client::title::Mode::Multiplayer(_) + ) + }); + world_loading::preload_world_data( + on_world_screens, + &self.options.resources, + self.pack.assets.registry, + ); if std::mem::take(&mut self.pending_pack_reload) { self.reload_packs(); } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..3ec2cca47 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -24,11 +24,24 @@ use horizon_protocol::{ }; use std::{ collections::HashMap, - sync::{Arc, OnceLock}, + sync::{Arc, Mutex}, }; /// The registries and tags are the same for every world: load them once. -static SYNC: OnceLock, String>> = OnceLock::new(); +static SYNC: Mutex, String>>> = Mutex::new(None); + +/// The registries and tags a server sends, loaded from `root` the first time. +pub(super) fn sync_data(root: &std::path::Path) -> std::result::Result, String> { + let mut sync = SYNC.lock().unwrap_or_else(|e| e.into_inner()); + sync.get_or_insert_with(|| SyncData::load(root).map(Arc::new)) + .clone() +} + +/// Let go of what `sync_data` loaded: for a preload no world used +/// (game/world_loading.rs). +pub(super) fn forget_sync_data() { + *SYNC.lock().unwrap_or_else(|e| e.into_inner()) = None; +} /// The settings of the open world (WorldOptionsScreen's multiplayer section). #[derive(Clone, Copy, Debug)] @@ -562,10 +575,7 @@ impl Game<'_> { config: HubConfig, host: Option, ) -> Result<()> { - let root = self.options.resources.clone(); - let sync = SYNC - .get_or_init(|| SyncData::load(&root).map(Arc::new)) - .clone()?; + let sync = sync_data(&self.options.resources)?; let biome_names: Vec = self .res .biomes() diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index e9ee8e3e8..b16bcffb6 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -196,6 +196,81 @@ impl WorldLoader { } } +/// How long the preloaded world data outlives the world screens: a player +/// who goes back to the title or to Multiplayer and opens no world for this +/// long gets the memory back. +const PRELOAD_KEPT: std::time::Duration = std::time::Duration::from_secs(60); + +enum Preload { + Idle, + /// Read, or being read, on the "World data preload" thread. `left`: when + /// the player last left the world screens. + Started { + thread: std::thread::JoinHandle<()>, + left: Option, + }, + /// A world opened: the data is the world's now, and stays. + Used, +} + +static PRELOAD: std::sync::Mutex = std::sync::Mutex::new(Preload::Idle); + +/// Each frame of the title: read what every world opening loads and keeps +/// for the rest of the process (the worldgen bundle, the loot tables and the +/// registries the server sends) on a helper thread while the player is on the +/// world screens (`on_world_screens`: Singleplayer, Create World and their +/// dialogs), so it overlaps the time spent choosing a world. A world opened +/// meanwhile waits for the part being read instead of reading it again. Not +/// at the title screen itself: many players only go to Multiplayer, and +/// small machines need the memory. Dropped after `PRELOAD_KEPT` away from +/// the world screens without a world opening. +pub(super) fn preload_world_data( + on_world_screens: bool, + resources: &std::path::Path, + registry: &'static horizon_world::registry::BlockRegistry, +) { + let mut preload = PRELOAD.lock().unwrap_or_else(|e| e.into_inner()); + match &mut *preload { + Preload::Used => {} + Preload::Idle if on_world_screens => { + let resources = resources.to_owned(); + let spawned = std::thread::Builder::new() + .name("World data preload".into()) + .spawn(move || { + horizon_threads::behind_server(); + // Errors are left for the world opening to report. + let _ = horizon_client::vanillagen::shared_data( + &resources.join("worldgen"), + registry, + ); + let _ = horizon_client::structure_blocks::loot_data(&resources); + let _ = super::lan::sync_data(&resources); + }); + match spawned { + Ok(thread) => *preload = Preload::Started { thread, left: None }, + Err(e) => log::warn!("Horizon: world data preload: {e}"), + } + } + Preload::Idle => {} + Preload::Started { left, .. } if on_world_screens => *left = None, + Preload::Started { thread, left } => { + let left = *left.get_or_insert_with(std::time::Instant::now); + if left.elapsed() >= PRELOAD_KEPT && thread.is_finished() { + horizon_client::vanillagen::forget_shared_data(); + horizon_client::structure_blocks::forget_loot_data(); + super::lan::forget_sync_data(); + *preload = Preload::Idle; + log::info!("Horizon: preloaded world data dropped, no world opened"); + } + } + } +} + +/// A world opens: what `preload_world_data` read is the world's from now on. +pub(super) fn world_data_used() { + *PRELOAD.lock().unwrap_or_else(|e| e.into_inner()) = Preload::Used; +} + pub(super) fn make_streaming( res: &Resources, pack: &PackResources, diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 604cf7925..01c60ed71 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -9,7 +9,7 @@ use horizon_world::{ }; use std::{ path::Path, - sync::{Arc, OnceLock}, + sync::{Arc, Mutex}, }; /// The `custom_data` key holding an exploration map's search until the game @@ -114,11 +114,13 @@ pub fn has_pending_map(item: &ItemStack) -> bool { }) } -static LOOT: OnceLock>> = OnceLock::new(); +/// None until `loot_data` runs; `Some(None)` when the tables failed to load. +static LOOT: Mutex>>> = Mutex::new(None); /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { - LOOT.get_or_init(|| match LootData::load(root) { + let mut loot = LOOT.lock().unwrap_or_else(|e| e.into_inner()); + loot.get_or_insert_with(|| match LootData::load(root) { Ok(data) => Some(Arc::new(data)), Err(e) => { log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}"); @@ -130,7 +132,16 @@ pub fn loot_data(root: &Path) -> Option> { /// The loot data `loot_data` loaded, if it ran. pub fn loaded_loot_data() -> Option> { - LOOT.get().cloned().flatten() + LOOT.lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .flatten() +} + +/// Let go of the loot data: for a preload no world used +/// (game/world_loading.rs). The next `loot_data` loads it again. +pub fn forget_loot_data() { + *LOOT.lock().unwrap_or_else(|e| e.into_inner()) = None; } /// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table` diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 923818a08..79d316969 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -333,15 +333,23 @@ impl VanillaTerrain { u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX) } } +static SHARED_DATA: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); +/// Let go of the bundles `shared_data` loaded: for a preload no world used +/// (game/world_loading.rs). A generator that holds one keeps it. +pub fn forget_shared_data() { + SHARED_DATA + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); +} /// The worldgen bundle at `dir`, loaded once and shared by every generator /// and by live feature placement (sapling growth, bone meal). pub fn shared_data( dir: &Path, registry: &'static BlockRegistry, ) -> crate::Result> { - static CACHE: std::sync::Mutex)>> = - std::sync::Mutex::new(Vec::new()); - let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut cache = SHARED_DATA.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) { return Ok(data.clone()); } From c808fae288d36c682b143edb4e1283438437e165 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:37:30 +0100 Subject: [PATCH 093/132] Keep a stronger active effect when a weaker one is added --- crates/horizon-client/src/mobs.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..330c2901c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1879,8 +1879,15 @@ impl Mob { } pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { - e.1 = e.1.max(ticks); - e.2 = e.2.max(amplifier); + // MobEffectInstance.update: a stronger effect replaces the old one + // with its own duration, an equal one keeps the longer duration, + // and a weaker one never changes the active effect. + if amplifier > e.2 { + e.1 = ticks; + e.2 = amplifier; + } else if amplifier == e.2 { + e.1 = e.1.max(ticks); + } } else { self.extra.effects.push((effect, ticks, amplifier)); } From 9eb913affea478d58d127e08f39fcacf379103f0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:37:33 +0100 Subject: [PATCH 094/132] Show the crouching pose of a guest who is not holding sneak --- crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/lan/hub.rs | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4ccbb0ec8..2d7302e61 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -839,6 +839,7 @@ impl Game<'_> { gliding: p.fall_flying, swimming: p.swimming, crawling: p.pose == horizon_client::pose::Pose::Swimming && !p.swimming, + crouching: p.pose == horizon_client::pose::Pose::Crouching, spin_attack: p.auto_spin_attack_ticks > 0, on_fire: p.fire_ticks > 0, invisible: self.potions.effects.get("invisibility").is_some(), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c3a18ee86..ba21bdee1 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -100,6 +100,8 @@ pub struct BodyFlags { pub swimming: bool, /// The swimming pose of a player crawling under a block. pub crawling: bool, + /// The crouching pose, held without sneaking under a low ceiling. + pub crouching: bool, /// `LivingEntity.isAutoSpinAttack`: Riptide's spin. pub spin_attack: bool, /// `Entity.isOnFire`. @@ -1549,7 +1551,7 @@ impl Hub { 1 } else if body.spin_attack { 4 - } else if sneaking { + } else if sneaking || body.crouching { 5 } else { 0 @@ -2615,6 +2617,7 @@ fn guest_body(g: &Guest) -> BodyFlags { gliding: g.fall_flying, swimming: m.is_some_and(|m| m.swimming), crawling: m.is_some_and(|m| m.pose == crate::pose::Pose::Swimming && !m.swimming), + crouching: m.is_some_and(|m| m.pose == crate::pose::Pose::Crouching), spin_attack: m.is_some_and(|m| m.auto_spin_attack_ticks > 0), on_fire: m.is_some_and(|m| m.fire_ticks > 0), invisible: g.effects.get("invisibility").is_some(), From bab42517154cead302186e24fd9dfd1b62b98ae3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:37:47 +0100 Subject: [PATCH 095/132] Give armor stands, frames, paintings, boats, carts and other entities a scoreboard name --- crates/horizon-client/src/game/scoreboard.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 81c03e288..72b3ab000 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -132,8 +132,16 @@ impl Game<'_> { match t { Target::Player => Some(self.acting_player_name().to_owned()), Target::Guest(conn) => self.command_guest(conn).map(|g| g.name.clone()), - Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), - _ => None, + Target::Mob(id) + | Target::Item(id) + | Target::Stand(id) + | Target::Frame(id) + | Target::Painting(id) + | Target::Boat(id) + | Target::Cart(id) + | Target::Other(id) => Some(uuid_text(self.uuid_for(id))), + // Orbs and projectiles are addressed by index and have no UUID here. + Target::Orb(_) | Target::Projectile(_) => None, } } fn holder_for(&mut self, t: Target) -> Option { From eab8d0f91120e6f9732196a01e2b2a9fb03bf0bf Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:45:02 +0100 Subject: [PATCH 096/132] Slide on honey for the server's player and show the slide effects to multiplayer clients --- crates/horizon-client/src/game.rs | 51 ++++++++++++------- crates/horizon-client/src/game/lan_actions.rs | 21 ++++++++ crates/horizon-client/src/game/remote.rs | 24 +++++++++ crates/horizon-client/src/motion.rs | 12 +++-- 4 files changed, 87 insertions(+), 21 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ab63124d6..e9c81348d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2097,6 +2097,33 @@ impl Game<'_> { } /// `TerrainParticle` at `pos`: the model's particle sprite and tint source /// 0's `colorAsTerrainParticle` (white when the block has none). + /// `HoneyBlock.showSlideParticles` (entity event 53): five honey block + /// particles at the entity. + fn honey_slide_particles(&mut self, at: [f64; 3]) { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let Some(honey) = self + .pack + .assets + .registry + .default_state("minecraft:honey_block") + else { + return; + }; + let block = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + if let Some((sprite, tint)) = self.particle_sprite(honey, block) { + for _ in 0..5 { + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite.clone(), tint), + at, + [0.0; 3], + ); + } + } + } fn particle_sprite(&self, state: BlockStateId, pos: [i32; 3]) -> Option<(String, u32)> { let sprite = Self::block_particle_sprite(&self.pack, state)?; let chunks = &self.world.chunks; @@ -4545,28 +4572,18 @@ impl Game<'_> { MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), MotionEvent::HoneySlide { - pos, - sound, - particles, + sound, particles, .. } => { if sound { self.audio .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); } - // HoneyBlock.showSlideParticles: five block particles. - if particles - && let Some((sprite, tint)) = self.particle_sprite( - self.world.block(pos.x, pos.y, pos.z), - [pos.x, pos.y, pos.z], - ) - { - use horizon_client::particles::{ParticleOptions, ParticleType}; - for _ in 0..5 { - self.particles.add( - &ParticleOptions::block(ParticleType::Block, sprite.clone(), tint), - feet, - [0.0; 3], - ); + if particles { + self.honey_slide_particles(feet); + // The server's event 53 reaches the guests too. + let id = self.lan.as_ref().map(|h| h.host_entity); + if let Some(id) = id { + self.lan_entity_event(id, 53, feet); } } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..fb484f94d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2311,6 +2311,27 @@ impl Game<'_> { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at), MotionEvent::Fall(event) => self.landing_block_updates(&event), + // HoneyBlock.maybeDoSlideEffects: the sound reaches the + // others (Player.playSound excludes the player, whose client + // plays it), the entity event 53 everyone around. + MotionEvent::HoneySlide { + sound, particles, .. + } => { + let Some((id, at)) = host.hub.guest(conn).map(|g| (g.entity_id, g.position)) + else { + continue; + }; + if sound { + let name = "minecraft:block.honey_block.slide"; + let source = horizon_client::settings::sound_source(name) as i32; + self.audio.play_unshared(name, Some(at), 1.0, 1.0); + host.hub.sound(name, at, 1.0, 1.0, source, Some(conn)); + } + if particles { + self.honey_slide_particles(at); + host.hub.entity_event(id, 53, at); + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..a290d6e1a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2133,6 +2133,23 @@ impl Game<'_> { if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + // Entity event 53: the honey slide particles of a player + // sliding down a honey block (HoneyBlock.showSlideParticles). + if p.event == 53 { + let at = if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + self.player + .as_ref() + .map(|q| [q.position.x, q.position.y, q.position.z]) + } else { + self.mobs + .iter() + .find(|m| m.id == p.id as u32) + .map(|m| [m.position.x, m.position.y, m.position.z]) + }; + if let Some(at) = at { + self.honey_slide_particles(at); + } + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings @@ -3326,6 +3343,13 @@ impl Game<'_> { horizon_client::motion::MotionEvent::InsidePortal { .. } => { self.client_inside_nether_portal(); } + // HoneyBlock.maybeDoSlideEffects on the client's own level: + // the slide sound, heard here (LocalPlayer.playSound); the + // particles come from the server's event 53. + horizon_client::motion::MotionEvent::HoneySlide { sound: true, .. } => { + self.audio + .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); + } _ => {} } } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 04341b66f..2ff68093c 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -204,8 +204,8 @@ pub enum MotionEvent { position: Vec3, }, /// `HoneyBlock.maybeDoSlideEffects` for a player sliding down the side of - /// the honey block at `pos`: its slide sound, and the client's five - /// block particles (entity event 53) at the player. + /// the honey block at `pos`: its slide sound, and the server's entity + /// event 53 (the five block particles at the player). HoneySlide { pos: BlockPos, sound: bool, @@ -1381,6 +1381,9 @@ impl MotionWorld<'_, '_, '_> { "minecraft:sweet_berry_bush" if damage_only => { self.sweet_berry_bush_damage(state)?; } + // HoneyBlock.entityInside: a server's player slides too, so + // its fall distance resets (its client moves it). + "minecraft:honey_block" => self.honey_block_inside(p)?, // PowderSnowBlock.entityInside's FREEZE. "minecraft:powder_snow" if damage_only => entered.push((step, p)), _ => {} @@ -1394,7 +1397,6 @@ impl MotionWorld<'_, '_, '_> { entered.push((step, p)); } "minecraft:cobweb" => self.web_inside(), - "minecraft:honey_block" => self.honey_block_inside(p)?, "minecraft:sweet_berry_bush" => self.sweet_berry_bush_inside(state)?, "minecraft:bubble_column" => { let precise = moved_far || deflated.intersects(Aabb::block(p)); @@ -1444,7 +1446,9 @@ impl MotionWorld<'_, '_, '_> { // maybeDoSlideEffects: the sound, then the server's event 53. let random = &mut self.scene.random; let sound = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; - let particles = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + // Only the server broadcasts event 53 (`!level.isClientSide()`). + let particles = !self.player.client_side + && random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; if sound || particles { self.player.events.push(MotionEvent::HoneySlide { pos, From 3bb6e4030479493f15e366b3ad0081aa178bb7b6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:46:13 +0100 Subject: [PATCH 097/132] Clear a bundle's selection when the cursor leaves it on a server's client too --- crates/horizon-client/src/game/remote.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 32f5f6093..3a04019d2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3136,6 +3136,8 @@ impl Game<'_> { // server says the entry ended. `onCooldownEnded` is the plain // ItemCooldowns' no-op on a client. self.cooldowns.tick(); + // Leaving a slot clears its bundle's selection here and on the server. + self.tick_bundle_hover(); // Options.broadcastOptions: a changed render distance or Chat option // is sent again. let view = client_view_distance(self.settings.render_distance); 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 098/132] 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)" } From 1258c2473b806540ea3fb31496af859e0958f1f0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:54:53 +0100 Subject: [PATCH 099/132] Multiply the particle speed and delta as floats, as handleParticleEvent does Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/commands/world_cmds.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index d58b477b0..90abc5e71 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -606,10 +606,9 @@ impl Game<'_> { if !local { } else if count <= 0 { // handleParticleEvent, count 0: one particle, the speed times - // the delta as velocity (both sent as floats). - let speed = f64::from(speed); + // the delta as velocity (both sent as floats, multiplied as floats). self.particles - .create(&options, pos, delta.map(|d| speed * f64::from(d as f32))); + .create(&options, pos, delta.map(|d| f64::from(speed * d as f32))); } else { for _ in 0..count { let r = self.particles.random(); From c4d0cb1ec0c686b4efba990964055795af0f2576 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:55:51 +0100 Subject: [PATCH 100/132] A small armor stand's eyes are at 0.9875, and eye heights are floats ArmorStand.BABY_DIMENSIONS keeps its own eye height rather than half the type's, and EntityDimensions.eyeHeight is a float widened by getEyeY. Co-Authored-By: Claude Opus 5.5 --- .../src/game/commands/execute.rs | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index c48cd8adf..d715ce0ab 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -145,23 +145,19 @@ impl Game<'_> { .iter() .find(|m| m.id == id) .map_or(0.0, |m| m.eye_y() - m.position.y), - // An armor stand's dimensions are halved when small and empty - // when a marker (ArmorStand.getDefaultDimensions). - Target::Stand(id) => { - let stand = self.armor_stands.iter().find(|a| a.id == id); - let scale = match stand { - Some(a) if a.marker => 0.0, - Some(a) if a.small => 0.5, - _ => 1.0, - }; - scale * self.type_eye_height(&self.target_type(t)) - } + // ArmorStand.getDefaultDimensions: a marker's are empty, a small + // stand's are BABY_DIMENSIONS, whose eye height is 0.9875F. + Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) { + Some(a) if a.marker => 0.0, + Some(a) if a.small => f64::from(0.9875f32), + _ => self.type_eye_height(&self.target_type(t)), + }, // Entity.getEyeHeight: the type's dimensions. _ => self.type_eye_height(&self.target_type(t)), } } /// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`, - /// read once. + /// read once: a float, widened as `Entity.getEyeY` does. fn type_eye_height(&self, ty: &str) -> f64 { static EYE_HEIGHTS: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -173,7 +169,9 @@ impl Game<'_> { .and_then(|v| { v.as_object().map(|o| { o.iter() - .filter_map(|(k, t)| Some((k.clone(), t["eye_height"].as_f64()?))) + .filter_map(|(k, t)| { + Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32))) + }) .collect() }) }) From 83b544f04fe5f89d4835b59daa41f2bc4b1967d8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:57:31 +0100 Subject: [PATCH 101/132] Bonus chest: draw from the level random and set blocks with UPDATE_CLIENTS MinecraftServer.setInitialSpawn passes level.getRandom() to BonusChestFeature.place, which sets the chest and torches with flags 2. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/initial_spawn.rs | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index bbd0a766c..68e754dfc 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -20,7 +20,8 @@ use horizon_core::{ }; use horizon_world::{ block_collision::BlockCollisionRegistry, collision_context::CollisionContext, - heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates, + heightmap::HeightmapType, level::flags::UPDATE_CLIENTS, registry::BlockStateId, + worldgen::terrain::TerrainBlockStates, }; /// The loaded world as the spawn searches query it. @@ -138,8 +139,8 @@ impl Game<'_> { if !self.streaming.is_lit(cx, cz) { return Ok(()); } - let mut random = entity_random(); - // Util.toShuffledList of the chunk's x and z. + // `level.getRandom()`. Util.toShuffledList of the chunk's x and z. + let random = &mut self.world.random; let mut shuffled = |min: i32| -> [i32; 16] { let mut values: [i32; 16] = std::array::from_fn(|i| min + i as i32); for end in (2..=16usize).rev() { @@ -157,8 +158,8 @@ impl Game<'_> { if self.world.block(x, y, z) != self.world.air && !self.collision_empty([x, y, z]) { continue; } - self.level_set([x, y, z], chest)?; - let seed = random.next_long(); + self.set_block_clients([x, y, z], chest)?; + let seed = self.world.random.next_long(); self.world .block_entities .insert((x, y, z), BlockEntity::Chest(Vec::new())); @@ -174,7 +175,7 @@ impl Game<'_> { b.can_survive(level, ticks, BlockPos::new(at[0], at[1], at[2]), torch) }); if survives { - self.level_set(at, torch)?; + self.set_block_clients(at, torch)?; } } return Ok(()); @@ -182,6 +183,19 @@ impl Game<'_> { } Ok(()) } + /// `Level.setBlock(pos, state, UPDATE_CLIENTS)`: no neighbour updates. + fn set_block_clients(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { + self.with_level(|b, level, ticks| { + b.set_block( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + state, + UPDATE_CLIENTS, + ); + }); + self.process_level_events() + } /// The block at `pos` has no collision shape. fn collision_empty(&self, pos: [i32; 3]) -> bool { let mut scene = SceneCollisions { From 34f57dbcac49598cb18fc68ae4c1d6421594f6f4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:59:31 +0100 Subject: [PATCH 102/132] Trident: Impaling through the enchantment's damage effect ThrownTrident.onHitEntity runs EnchantmentHelper.modifyDamage on the trident, so Impaling adds to the 8 for the entity types in #sensitive_to_impaling (its minecraft:damage requirement), not for every mob that swims or breathes water. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 46 ++++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index b3618af5c..6ac554d68 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1946,22 +1946,32 @@ impl Game<'_> { None => self.projectile_hit(p, hit), } } - /// What an arrow or a thrown trident hits an entity for - /// (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a trident's - /// 8, plus Impaling on aquatic `victim`s. - fn shot_damage(&mut self, shot: &mut Projectile, victim: Option) -> f32 { + /// What an arrow or a thrown trident hits an entity of type `victim` + /// for (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a + /// trident's 8 through `EnchantmentHelper.modifyDamage` of the trident + /// (Impaling's `minecraft:damage` on `#sensitive_to_impaling`). + fn shot_damage(&mut self, shot: &mut Projectile, victim: Option<&str>) -> f32 { if !matches!(shot.kind, ProjectileKind::Trident) { return arrow_damage(shot, &mut self.world.random) + shot.bonus.damage; } - let impaling = shot - .arrow - .as_ref() - .map_or(0, |a| a.pickup_item.enchantment_level("minecraft:impaling")) - as f32; - let aquatic = victim - .and_then(|id| self.mobs.iter().find(|m| m.id == id)) - .is_some_and(|m| m.kind.flags.aquatic_swimmer || m.kind.flags.breathes_water); - 8.0 + if aquatic { 2.5 * impaling } else { 0.0 } + let Some(trident) = shot.arrow.as_ref().map(|a| a.pickup_item.clone()) else { + return 8.0; + }; + let ctx = horizon_client::enchant::EffectContext { + this: victim, + attacker: (shot.owner == Some(Who::Player)).then_some("minecraft:player"), + direct_attacker: Some("minecraft:trident"), + damage_type: Some("minecraft:trident"), + items: Some(self.res.items()), + ..Default::default() + }; + self.res.stations().enchantments.modify_value( + Some(&trident), + "minecraft:damage", + &ctx, + &mut self.world.random, + 8.0, + ) } /// What an arrow's tick asked for: its particles and sounds. fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { @@ -2203,10 +2213,14 @@ impl Game<'_> { (ProjectileKind::Trident, Hit::Entity { who, .. }) => { let mut trident = p.clone(); let victim = match who { - Who::Mob(id) => Some(id), - Who::Player => None, + Who::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.kind.id.clone()), + Who::Player => Some("minecraft:player".to_owned()), }; - let amount = self.shot_damage(&mut trident, victim); + let amount = self.shot_damage(&mut trident, victim.as_deref()); let hurt = match who { Who::Player => self.mob_hits_player( amount, From 1fe0f5fcb9690f3dd3886153960ada3a63c6635e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:59:39 +0100 Subject: [PATCH 103/132] Sound options: Music Frequency starts its own row, as in SoundOptionsScreen Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/options_ui.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 50eb50f6f..f599176db 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -1424,7 +1424,10 @@ impl OptionsUi { let mut rows = vec![Row::Big(Opt::Volume(0))]; let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); rows.extend(pairs(&others)); - rows.extend(pairs(&[Opt::ShowSubtitles, Opt::MusicFrequency])); + rows.extend(pairs(&[Opt::ShowSubtitles])); + // SoundOptionsScreen: Music Frequency starts the next row (with + // Music Toast, not in Horizon yet). + rows.extend(pairs(&[Opt::MusicFrequency])); rows } Page::Controls => { From 3f0e70882c8f6be6aa73c8700e70d9eb98457acc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:58:14 +0100 Subject: [PATCH 104/132] Death messages: no fallback for a message with no entity behind it DamageSource.getLocalizedDeathMessage sends the one-argument message, and TranslatableContents.decompose shows a template it cannot fill as written. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/combat.rs | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 22d5c7d8f..2d6b75902 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -1,7 +1,7 @@ //! The player's `CombatTracker`: the damage taken lately, who dealt it and //! where the player fell from, turned into the vanilla death message. use super::{Game, chat::PLAYER_NAME}; -use horizon_client::{health::HealthEvent, lang, motion::MotionEvent, text::Text}; +use horizon_client::{health::HealthEvent, motion::MotionEvent, text::Text}; struct Entry { damage_type: String, @@ -287,19 +287,8 @@ impl Game<'_> { { return Text::translate(&format!("{key}.player"), &[me, name.clone()]); } - killerless_message(&key, me) + // No entity at all: the one-argument message, as vanilla sends it (a + // template that names a killer then shows as written). + Text::translate(&key, &[me]) } } -/// A death message with no entity behind it. One that names a second actor -/// (`%2$s`) has nobody to name here, so it falls back to its plain sibling -/// (`indirectMagic` to `magic`, anything else to `generic`) instead of -/// showing the raw template. -fn killerless_message(key: &str, me: Text) -> Text { - if key == "death.attack.indirectMagic" { - return Text::translate("death.attack.magic", &[me]); - } - if lang::get(key).contains("%2$s") { - return Text::translate("death.attack.generic", &[me]); - } - Text::translate(key, &[me]) -} From 031f1e58a3984cb9fb793414f4e94ee670d414fe Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:07:12 +0100 Subject: [PATCH 105/132] remote_fireball: a slow fireball, sampled from one ctl process The harness sampled the fireball from a new horizon-ctl process each time, 10-16 ticks apart on a loaded runner: the fireball (~2 blocks a tick) left the cleared corridor or the guest's tracking range before the sixth sample, and the harness failed. It now flies slowly (acceleration_power 0.02, under 0.4 blocks a tick) down a longer corridor, and the guest takes 16 samples in one ctl script (lan_e2e's Game.script returns every reply with every=True). Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 7 ++++--- tools/test_remote_fireball_parity.py | 14 +++++++++----- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index ab3fcde1b..dfa7df454 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -339,8 +339,9 @@ class Game: def wait(self, ticks): self.d('wait', ticks=ticks) - def script(self, lines): - """Keep tick-sensitive input in one ctl process, through the normal control commands.""" + def script(self, lines, every=False): + """Keep tick-sensitive input in one ctl process, through the normal control commands. Returns the last + reply, or with every=True all of them in order.""" result = subprocess.run(self.d.base + ['script'], input='\n'.join(lines) + '\n', cwd=self.work, env=self.d.env, capture_output=True, text=True, timeout=600) @@ -348,7 +349,7 @@ class Game: ticks = [r['ticks'] for r in replies if 'ticks' in r] print(f'[{self.name}] script {lines} -> {replies[-1] if replies else result.stderr[:400]}; ticks={ticks}') assert result.returncode == 0 and replies and not any('error' in r for r in replies), result.stdout - return replies[-1] + return replies if every else replies[-1] def until(self, observe, predicate, ticks=100): """Wait for an observable answer, within the existing tick budget.""" diff --git a/tools/test_remote_fireball_parity.py b/tools/test_remote_fireball_parity.py index 7e60ff30a..d227ed3f7 100644 --- a/tools/test_remote_fireball_parity.py +++ b/tools/test_remote_fireball_parity.py @@ -18,15 +18,19 @@ def check_motion(host, guest, out): for game in (host, guest): game('command', command='gamemode creative') tag = 'remote_fireball_parity' - host('command', command=f'fill {x + 2} {y + 18} {z - 1} {x + 48} {y + 23} {z + 1} minecraft:air') + # A slow fireball (acceleration_power 0.02: under 0.4 blocks a tick, against ~2 by default) stays in the cleared + # corridor and in the guest's tracking range for every sample, however many ticks a loaded host takes to answer. + host('command', command=f'fill {x + 2} {y + 18} {z - 1} {x + 96} {y + 23} {z + 1} minecraft:air') host('command', command=f'summon minecraft:fireball {x + 3.5} {y + 20} {z + 0.5} ' - f'{{Tags:["{tag}"],Motion:[0.1d,0.0d,0.0d]}}') + f'{{Tags:["{tag}"],Motion:[0.1d,0.0d,0.0d],acceleration_power:0.02d}}') samples = [] try: - for _ in range(8): - balls = [p for p in guest('status')['projectiles'] if p['kind'] == 'LargeFireball'] + # One ctl process for all samples: a ctl process per sample took 10-16 ticks on a loaded runner, by + # which time the fireball had left the cleared corridor and exploded. + replies = guest.script(['status', 'wait 1'] * 16, every=True) + for status in (reply for reply in replies if 'projectiles' in reply): + balls = [p for p in status['projectiles'] if p['kind'] == 'LargeFireball'] samples.append(balls[0]['position'][0] if balls else None) - guest.wait(2) finally: host('command', command=f'kill @e[tag={tag}]') seen = [p for p in samples if p is not None] From 8f02822a9aa71d5e008d5f18b68345db7a61abc5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:09:44 +0100 Subject: [PATCH 106/132] remote.sh: stop the command on the host with its caller, and what it leaves running The command ran on after remote.sh was stopped or its connection dropped, holding the name's lock, and a game or daemon it left behind outlived the run. It now runs in a scope named after the run (remote-.scope), stopped when the command ends, when the ssh session ends first, and before the next run under that name. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 2 +- tools/remote.sh | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 7419eef26..50b67c571 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -46,7 +46,7 @@ Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip ### 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. +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. Whatever the command leaves running (a game, a daemon) is stopped when it ends, and stopping `remote.sh` (or losing the connection) stops the command on the host. 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 diff --git a/tools/remote.sh b/tools/remote.sh index 1df21c560..0955666cb 100755 --- a/tools/remote.sh +++ b/tools/remote.sh @@ -15,6 +15,7 @@ # 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/. +# What the command leaves running is stopped when it ends; stopping this script stops the command on the host. # 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, @@ -96,9 +97,22 @@ export HORIZON_HOME=$scratch/game HORIZON_LAUNCHER_HOME=$scratch/launcher XDG_DA 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 +# The command runs in a scope of its own, stopped with everything in it once the command is done (a game or a +# daemon it left behind), when the caller goes away first (the ssh session ends), and before the next run here. +unit=remote-$name.scope +systemctl --user stop "$unit" 2>/dev/null || true +session=$PPID +( while kill -0 "$session" 2>/dev/null; do sleep 2; done; systemctl --user stop "$unit" 2>/dev/null ) \ + < /dev/null > /dev/null 2>&1 9>&- & +watcher=$! status=0 -systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit="remote-$name-$$" \ +systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit="$unit" \ "${pin[@]}" nice -n 10 bash -c "$command" 2>&1 < /dev/null 9>&- | tee "$log" || status=${PIPESTATUS[0]} +kill "$watcher" 2>/dev/null || true +systemctl --user stop "$unit" 2>/dev/null || true exit "$status" REMOTE -} | ssh -o BatchMode=yes "ludovic@$host" bash -s +} | ssh -o BatchMode=yes "ludovic@$host" bash -s & +# Stopping this script ends the session, and the host then stops the command (above). +trap 'kill $! 2>/dev/null' INT TERM HUP +wait $! From cc58083574d857b72c3abc6578254b364e256937 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:14:56 +0100 Subject: [PATCH 107/132] Give the dropped preload's memory back to the OS glibc keeps the pages the preload thread freed in that thread's arena, and macOS keeps them in its zones until memory runs short, so dropping the preload didn't lower the footprint: horizon-threads now asks the allocator to return free pages (malloc_trim, malloc_zone_pressure_relief). Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/world_loading.rs | 1 + crates/horizon-threads/src/lib.rs | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index b16bcffb6..73f1820f2 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -259,6 +259,7 @@ pub(super) fn preload_world_data( horizon_client::vanillagen::forget_shared_data(); horizon_client::structure_blocks::forget_loot_data(); super::lan::forget_sync_data(); + horizon_threads::release_free_memory(); *preload = Preload::Idle; log::info!("Horizon: preloaded world data dropped, no world opened"); } diff --git a/crates/horizon-threads/src/lib.rs b/crates/horizon-threads/src/lib.rs index 90c8d128e..917c3b502 100644 --- a/crates/horizon-threads/src/lib.rs +++ b/crates/horizon-threads/src/lib.rs @@ -126,6 +126,38 @@ fn idle() -> bool { false } +/// Give back to the OS the memory the allocator holds free, after something +/// large was dropped: glibc keeps freed pages in the arena of the thread that +/// allocated them, and macOS in its zones until memory runs short. Nothing +/// elsewhere. +pub fn release_free_memory() { + release(); +} + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +fn release() { + // SAFETY: returns free heap pages of every arena to the OS; no live + // allocation moves. + unsafe { + libc::malloc_trim(0); + } +} + +#[cfg(target_vendor = "apple")] +fn release() { + unsafe extern "C" { + fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize; + } + // SAFETY: a null zone means every zone and a goal of 0 as much as it can; + // it frees only pages no allocation uses. + unsafe { + malloc_zone_pressure_relief(std::ptr::null_mut(), 0); + } +} + +#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_vendor = "apple")))] +fn release() {} + #[cfg(test)] mod tests { /// The hint holds on the platforms that take it. From f8ba6505597ad363b18e8bc0076ccb3610b3ba96 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:25:11 +0100 Subject: [PATCH 108/132] ci: full-parity label runs a pull request's parity job on the desktop A crate split reaches every harness (#2160: 352 harnesses, 71 min on a Mac mini runner) and held the Mac mini's runners while other pull requests' parity jobs queued for over an hour. With the full-parity label, the job runs on the desktop's runner only (8 at a time) and waits for it while the desktop is in use; its timeout is 300 min, since a job under way when someone comes back goes on with 2 threads. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + .github/workflows/parity.yml | 13 +++++++++++-- .github/workflows/run-parity.yml | 1 + docs/release-flow.md | 7 +++++++ 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 39ea920da..b2fd9fa48 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,7 @@ jobs: with: base: ${{ github.event.pull_request.base.sha }} head: ${{ github.event.pull_request.head.sha }} + full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }} # Horizon never downloads the game. These jobs need a self-hosted Linux runner # (label horizon-game) holding the maintainer's own copy: the official launcher's # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index 9f678b43b..b90ad9968 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -13,6 +13,13 @@ on: description: The commit to check out and test type: string required: true + full: + description: >- + The pull request carries the full-parity label (a change every harness reaches, such as a crate split): it + runs on the desktop's runner only, so the Mac mini's runners stay free for the others. While the desktop is + in use the job waits for it. + type: boolean + default: false permissions: contents: read env: @@ -21,8 +28,10 @@ env: jobs: parity: - runs-on: [self-hosted, horizon-game] - timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini + runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "ludodesktop"]') || fromJSON('["self-hosted", "horizon-game"]') }} + # A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini, ~35 min on the desktop, longer if + # someone comes back to the desktop meanwhile (the job then goes on with 2 threads). + timeout-minutes: ${{ inputs.full && 300 || 120 }} steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml index a2b8e3291..9089a9a09 100644 --- a/.github/workflows/run-parity.yml +++ b/.github/workflows/run-parity.yml @@ -22,3 +22,4 @@ jobs: with: base: ${{ github.event.pull_request.base.sha }} head: ${{ github.event.pull_request.head.sha }} + full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }} diff --git a/docs/release-flow.md b/docs/release-flow.md index b0d435c29..8373f2bf6 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -27,6 +27,12 @@ quick steps and finishes in seconds. The job is `.github/workflows/parity.yml`, a reusable workflow: `checks` calls it for pull requests from this repository, `run-parity.yml` for a fork's pull request a maintainer labels `run-parity`. +A pull request every harness reaches (a crate split moves files every probe links: #2160 ran all 352 harnesses, 71 +minutes on a Mac mini runner, while five other pull requests' jobs queued behind it) carries the `full-parity` label: +its job runs on the desktop's runner only (8 harnesses at a time), and waits for it while the desktop is in use +instead of taking a Mac mini runner. Labels don't start `checks`: add it when opening the pull request +(`gh pr create --label full-parity`), or before the next push. + Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own copy is: the Mac mini, his Linux desktop and playhorizon (below). Their runners run as the maintainer's account and keep their checkout between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes @@ -212,6 +218,7 @@ How releases are numbered, and how installs from before 0.2 reach it: [versionin | `release-now` | Releases as soon as main's checks pass, without waiting for merges to settle | | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | +| `full-parity` | Runs the pull request's parity job on the desktop's runner only (a change every harness reaches) | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | | `release-blocker` | On an issue: no game release is published while it is open ([One channel](#one-channel)) | From b0783dac38d9fa238ecd2a38aadc0049936506a2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:54:33 +0100 Subject: [PATCH 109/132] launcher: Sculk's banner at the foot of the sidebar, seen without scrolling On Home it sat under every row, so nobody saw it without scrolling. It now sits small (228 px wide) above the Discord and Website links on every page but Servers, which keeps the large one. Co-Authored-By: Claude Opus 5.5 --- launcher/src/main.rs | 8 ++++++-- launcher/src/partner.rs | 6 +++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 50e62756d..9438f1af0 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1749,6 +1749,11 @@ impl Launcher { } _ => {} } + // Sculk's banner, small, above the links: seen without scrolling, on every page but Servers, which + // shows it large. + if self.page != Page::Servers { + foot = foot.child(partner::banner("partner-side", theme::SIDEBAR - 20., &t).mb(px(8.))); + } if !self.links.discord.is_empty() { foot = foot.child(link( "discord", @@ -2131,8 +2136,7 @@ impl Launcher { if let Some(crash) = self.crash.clone() { page = page.child(self.crash_notice(crash, cx)); } - // Below everything the player needs to start, so it never moves Play. - page.child(partner::banner("partner-home", 560., &t)) + page } /// "Horizon crashed": the report and the logs, and where to report it. diff --git a/launcher/src/partner.rs b/launcher/src/partner.rs index eea1a3524..5e1cdb695 100644 --- a/launcher/src/partner.rs +++ b/launcher/src/partner.rs @@ -1,5 +1,5 @@ -//! Sculk's banner: a server host that sponsors Horizon (Ludovic, 2026-10-26), on the Servers page -//! and under Home's rows. The picture is in the binary, never fetched; a click opens Sculk's page in +//! Sculk's banner: a server host that sponsors Horizon (Ludovic, 2026-10-26), large on the Servers page +//! and small at the foot of the sidebar on the other pages, where it shows without scrolling. The picture is in the binary, never fetched; a click opens Sculk's page in //! the browser. A "Partner" label above it says it is an ad. use crate::theme::Theme; use gpui::{div, img, prelude::*, px, ClickEvent, Div, Image, ImageFormat, Stateful}; @@ -19,7 +19,7 @@ static BANNER: LazyLock> = LazyLock::new(|| { }); /// The banner `width` logical pixels wide, under its label. Hovering lifts it a little and turns the -/// label to ink. The narrowest window (960) leaves the page 648 pixels, so it always fits. +/// label to ink. The narrowest window (960) leaves the page 648 pixels, so the Servers one always fits. pub fn banner(id: &'static str, width: f32, t: &Theme) -> Stateful
{ let t = *t; let el = div() From 12bf15cfd7658e118b29a1f695f64554b140168f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:58:09 +0100 Subject: [PATCH 110/132] launcher: the sidebar's partner banner can be hidden once it has been seen A "Hide" shows beside its label after the banner has been on screen for 3 minutes, counted over every start (settings: partner_seen_secs, saved each minute). Hiding it is kept (partner_hidden); the Servers page keeps its own banner. Co-Authored-By: Claude Opus 5.5 --- launcher/src/backend.rs | 7 +++++ launcher/src/main.rs | 57 ++++++++++++++++++++++++++++++++++++++--- launcher/src/partner.rs | 4 +++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 85818a67c..55a78193a 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -2545,6 +2545,13 @@ pub struct Settings { /// first-run question, or on the Play page once if they answered that before it existed. #[serde(default)] pub ping_notice_seen: bool, + /// Seconds the sidebar's partner banner has been on screen, over every start, up to + /// `partner::SEEN_BEFORE_HIDE`: only then can the player hide it. + #[serde(default)] + pub partner_seen_secs: u64, + /// The player hid the sidebar's partner banner. The Servers page keeps its own. + #[serde(default)] + pub partner_hidden: bool, } impl Settings { diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 9438f1af0..7cc6d0ccd 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -248,6 +248,32 @@ impl Launcher { } }) .detach(); + // Counts the time the sidebar's partner banner is on screen, until it may be hidden. + cx.spawn(async move |this, cx| loop { + cx.background_executor() + .timer(Duration::from_secs(10)) + .await; + let counting = this.update(cx, |this, cx| { + let s = &mut this.settings; + if s.partner_hidden || s.partner_seen_secs >= partner::SEEN_BEFORE_HIDE { + return false; + } + if this.page != Page::Servers { + s.partner_seen_secs += 10; + if s.partner_seen_secs % 60 == 0 + || s.partner_seen_secs >= partner::SEEN_BEFORE_HIDE + { + s.save(); + cx.notify(); + } + } + true + }); + if !matches!(counting, Ok(true)) { + break; + } + }) + .detach(); let mut settings = Settings::load(); if settings.minecraft_dir.is_none() { settings.minecraft_dir = backend::default_minecraft_dir(); @@ -1750,9 +1776,34 @@ impl Launcher { _ => {} } // Sculk's banner, small, above the links: seen without scrolling, on every page but Servers, which - // shows it large. - if self.page != Page::Servers { - foot = foot.child(partner::banner("partner-side", theme::SIDEBAR - 20., &t).mb(px(8.))); + // shows it large. After a while on screen a "Hide" beside its label puts it away for good. + if self.page != Page::Servers && !self.settings.partner_hidden { + let mut side = div().relative().mb(px(8.)).child(partner::banner( + "partner-side", + theme::SIDEBAR - 20., + &t, + )); + if self.settings.partner_seen_secs >= partner::SEEN_BEFORE_HIDE { + let hide = div() + .id("partner-hide") + .absolute() + .top(px(0.)) + .right(px(0.)) + .cursor_pointer() + .child( + text(theme::MICRO) + .text_color(t.muted) + .hover(move |s| s.text_color(t.ink)) + .child("HIDE"), + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.settings.partner_hidden = true; + this.settings.save(); + cx.notify(); + })); + side = side.child(keyboard(hide, &t)); + } + foot = foot.child(side); } if !self.links.discord.is_empty() { foot = foot.child(link( diff --git a/launcher/src/partner.rs b/launcher/src/partner.rs index 5e1cdb695..c4feac7b8 100644 --- a/launcher/src/partner.rs +++ b/launcher/src/partner.rs @@ -7,6 +7,10 @@ use std::sync::{Arc, LazyLock}; pub const URL: &str = "https://my.sculkhosting.com/ref/horizon"; +/// How long the sidebar's banner stays on screen, counted over every start, before a "Hide" shows +/// beside its label: long enough to be seen, then the player may put it away for good. +pub const SEEN_BEFORE_HIDE: u64 = 180; + /// 1200×441: twice the widest it is shown at, for Retina screens. Its transparent edges let the /// characters stand out of the card. const WIDTH: f32 = 1200.; From 266c7a2cd92116965fd379884591ddab373b3f46 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 14:47:04 +0100 Subject: [PATCH 111/132] Worldgen: finalize structure mobs at placement, as vanilla Structure mobs (bastion piglins, brutes and hoglins, ocean ruin drowned, village and mansion mobs, witch huts, monuments) were tagged and finalized at load by the cut-down spawning routine: no STRUCTURE reason (piglin weapons rerolled), no Mob step (follow range bonus, left-handedness), no baby hoglins, no brain memories, no drowned nautilus mounts, and draws from each mob's own random. The decoration region now calls a hook the game installs in the generator workers, which runs mobs::finalize with Reason::Structure, the region random in placement order and the level's difficulty with no inhabited time; jockeys come back as the vehicle with its Passengers. A mob the hook cannot finalize keeps its tag and is finalized on load as before, as are mobs of older saves; other entities drop the tag. The generator gets the level's difficulty as soon as the level opens, so the spawn area's mobs use it too. mob_to_nbt writes Invulnerable and LeftHanded always, IsBaby for zombies and piglins, Age for hoglins, the finalized attributes and memories, and drops the template keys vanilla never saves. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 154 +++++- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/creatures.rs | 6 + crates/horizon-client/src/game/levels.rs | 1 + crates/horizon-client/src/game/persist.rs | 12 +- crates/horizon-client/src/game/raids.rs | 2 +- crates/horizon-client/src/vanillagen.rs | 16 +- .../src/vanillagen/structure_mobs.rs | 446 ++++++++++++++++++ .../horizon-world/src/worldgen/generator.rs | 20 + .../src/worldgen/generator_decoration.rs | 51 +- .../src/worldgen/structure/legacy.rs | 7 +- 11 files changed, 698 insertions(+), 20 deletions(-) create mode 100644 crates/horizon-client/src/vanillagen/structure_mobs.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 161ca12e9..c49af48c9 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -180,7 +180,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ("Silent", m.silent), ("NoGravity", m.no_gravity), ("Glowing", m.glowing), - ("Invulnerable", m.invulnerable_flag), ] { if on { map.insert(key.into(), Tag::Byte(1)); @@ -188,6 +187,26 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&horizon_world::nbt::JavaString::from(key)); } } + map.insert( + "Invulnerable".into(), + Tag::Byte(i8::from(m.invulnerable_flag)), + ); + map.insert( + "LeftHanded".into(), + Tag::Byte(i8::from(m.extra.left_handed)), + ); + // Keys of older formats that structure templates still carry. + for key in [ + "HandItems", + "ArmorItems", + "HandDropChances", + "ArmorDropChances", + "Dimension", + "HurtByTimestamp", + "Leashed", + ] { + map.remove(&horizon_world::nbt::JavaString::from(key)); + } if m.ticks_frozen > 0 { map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen)); } else { @@ -197,7 +216,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))), - ("LeftHanded", Tag::Byte(0)), + ("current_impulse_context_reset_grace_time", Tag::Int(0)), ( "Brain", Tag::compound([("memories", Tag::Compound(Compound::new()))]), @@ -209,7 +228,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { // Only breedable animals have an age; a loaded creature that was saved without // one (a frog) stays without. let aged = raw.is_none_or(|r| r.get("Age").is_some()); - if m.kind.category == "creature" && aged { + if (m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin) && aged { map.insert("Age".into(), Tag::Int(m.extra.age)); map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked))); map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age)); @@ -260,6 +279,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { .or_insert_with(|| string("minecraft:classic")); } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { + // Only Piglin.addAdditionalSaveData writes CannotHunt. + if id == "minecraft:piglin_brute" { + map.remove(&"CannotHunt".into()); + } map.insert( "IsImmuneToZombification".into(), Tag::Byte(i8::from(m.extra.flag2)), @@ -498,8 +521,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { )]) }); } - "minecraft:zombie" => { - map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); + "minecraft:zombie" | "minecraft:husk" | "minecraft:drowned" => { for (key, value) in [ ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1)), @@ -532,6 +554,21 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { Tag::Byte(i8::from(m.extra.can_break_doors)), ); } + if matches!( + id, + "minecraft:zombie" + | "minecraft:husk" + | "minecraft:drowned" + | "minecraft:zombie_villager" + | "minecraft:zombified_piglin" + | "minecraft:piglin" + | "minecraft:zoglin" + ) { + map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); + } + if let Some(a) = m.extra.attributes.as_deref() { + put_attributes(map, m, a); + } crate::mobs::raider::write_nbt(m, map); crate::mobs::riders::write_nbt(m, map); // LivingEntity equipment: what the mob holds now. @@ -614,6 +651,89 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } tag } +/// `AttributeMap.pack` for the attributes with a base or permanent modifier +/// finalizeSpawn set, over the saved list. +fn put_attributes(map: &mut Compound, m: &Mob, a: &crate::mobs::finalize::Attributes) { + use crate::mobs::finalize::{self, Attr, Op}; + let mut list = match map.get(&"attributes".into()) { + Some(Tag::List(l)) => l.clone(), + _ => Vec::new(), + }; + for attr in Attr::ALL { + let modifiers: Vec = a + .modifiers + .iter() + .filter(|x| x.attr == attr) + .map(|x| { + let op = match x.op { + Op::AddValue => "add_value", + Op::AddMultipliedBase => "add_multiplied_base", + Op::AddMultipliedTotal => "add_multiplied_total", + }; + Tag::compound([ + ("id", string(x.id)), + ("amount", Tag::Double(x.amount.to_bits())), + ("operation", string(op)), + ]) + }) + .collect(); + if modifiers.is_empty() && !a.bases.iter().any(|(b, _)| *b == attr) { + continue; + } + let id = format!("minecraft:{}", attr.name()); + let mut entry = vec![ + ("id", string(&id)), + ("base", Tag::Double(finalize::base_value(m, attr).to_bits())), + ]; + if !modifiers.is_empty() { + entry.push(("modifiers", Tag::List(modifiers))); + } + let entry = Tag::compound(entry); + match list + .iter_mut() + .find(|t| text(t.get("id")).as_deref() == Some(id.as_str())) + { + Some(t) => *t = entry, + None => list.push(entry), + } + } + map.insert("attributes".into(), Tag::List(list)); +} +/// `Brain.Packed`: the memories finalizeSpawn set, over the saved ones. +pub fn put_brain(map: &mut Compound, m: &Mob, dimension: &str) { + if m.extra.memories.is_empty() { + return; + } + let mut memories = match map.get(&"Brain".into()).and_then(|b| b.get("memories")) { + Some(Tag::Compound(c)) => c.clone(), + _ => Compound::new(), + }; + for &(name, value, ttl) in &m.extra.memories { + let value = match name { + "hunted_recently" => Tag::Byte(value as i8), + "home" => match m.extra.home { + Some(p) => Tag::compound([ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(p.to_vec())), + ]), + None => continue, + }, + _ => Tag::Int(value as i32), + }; + let mut memory = vec![("value", value)]; + if ttl != i64::MAX { + memory.push(("ttl", Tag::Long(ttl))); + } + memories.insert( + format!("minecraft:{name}").as_str().into(), + Tag::compound(memory), + ); + } + map.insert( + "Brain".into(), + Tag::compound([("memories", Tag::Compound(memories))]), + ); +} /// `CustomName`: a text component saved as a string or a `{text: ..}` compound. fn custom_name(tag: &Tag) -> Option { match tag.get("CustomName")? { @@ -633,6 +753,22 @@ pub fn name_text(tag: &Tag) -> Text { t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), } } +/// Mob.finalizeSpawn's follow range bonus in the saved attributes. +pub(crate) fn spawn_bonus(tag: &Tag) -> Option { + let Some(Tag::List(attrs)) = tag.get("attributes") else { + return None; + }; + let range = attrs + .iter() + .find(|a| text(a.get("id")).as_deref() == Some("minecraft:follow_range"))?; + let Some(Tag::List(modifiers)) = range.get("modifiers") else { + return None; + }; + let bonus = modifiers + .iter() + .find(|x| text(x.get("id")).as_deref() == Some("minecraft:random_spawn_bonus"))?; + float(bonus.get("amount")) +} pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; @@ -658,6 +794,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } } } + if let Some(bonus) = spawn_bonus(tag) { + use crate::mobs::finalize::{Attr, Op, add_modifier}; + let id = "minecraft:random_spawn_bonus"; + add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase); + } m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32); m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; // What it holds (equipment.mainhand / offhand), when saved. @@ -699,7 +840,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); m.custom_name_text = tag.get("CustomName").map(name_text); - if m.kind.category == "creature" { + m.extra.left_handed = flag(tag, "LeftHanded"); + if m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..bf7425027 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4709,6 +4709,7 @@ impl Game<'_> { /// What the tick runs after the local player's own update: effects, the /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { + self.share_spawn_conditions(); self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects(running)); // Player.tick's ItemCooldowns.tick for the window's player (a @@ -8134,6 +8135,7 @@ impl Game<'_> { ); self.session_lock = Some(session_lock); self.end.set_locator(locator); + self.share_spawn_conditions(); self.score = Default::default(); self.fns = Default::default(); self.bosses = Default::default(); @@ -8272,6 +8274,7 @@ impl Game<'_> { seed, )?; self.end.set_locator(locator); + self.share_spawn_conditions(); Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f6961ab13..fa7c6e462 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -430,6 +430,12 @@ impl Game<'_> { ), } } + /// What the generator finalizes this level's structure mobs with. + pub(super) fn share_spawn_conditions(&self) { + if let Some(terrain) = self.end.locator() { + terrain.set_spawn_conditions(self.difficulty_id() as u8, self.world.day_time); + } + } /// `ServerLevel.getCurrentDifficultyAt`. pub(super) fn local_difficulty(&self, at: [f64; 3]) -> spawning::LocalDifficulty { use horizon_world::food::Difficulty; diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 29bf6d511..df4eaed88 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -192,6 +192,7 @@ impl Game<'_> { let mut locator = self.end.locator(); swap(&mut locator, &mut p.locator); self.end.set_locator(locator); + self.share_spawn_conditions(); swap(&mut self.save, &mut p.save); swap(&mut self.block_ticks, &mut p.block_ticks); swap(&mut self.tick_chunks, &mut p.tick_chunks); diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index b5e650e70..9e727d35d 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -357,7 +357,8 @@ impl Game<'_> { pub(super) fn load_mob(&mut self, tag: Tag, mount: Option) -> Option { self.next_entity += 1; let uuid = entity_nbt::uuid(&tag); - // Structure entities placed with finalizeEntities. + // Structure mobs that generation left to finish: saves from before + // they were finalized at placement, or a placement that could not. let mut tag = tag; let mut finalize = false; if let Tag::Compound(c) = &mut tag { @@ -449,7 +450,8 @@ impl Game<'_> { } } /// An entity of a type Horizon does not simulate, kept as its compound. - fn load_other(&mut self, tag: Tag, kind: &str) -> Option { + fn load_other(&mut self, mut tag: Tag, kind: &str) -> Option { + strip_finalize(&mut tag); let position = entity_nbt::position(&tag)?; let rotation = match tag.get("Rotation") { Some(Tag::List(l)) => { @@ -1014,3 +1016,9 @@ impl Game<'_> { self.save.save_entities(chunks) } } +/// Only a mob is finalized; another entity drops the request. +fn strip_finalize(tag: &mut Tag) { + if let Tag::Compound(c) = tag { + c.remove(&"horizon:finalize".into()); + } +} diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 743f02f44..da7c79394 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -235,7 +235,7 @@ impl Game<'_> { } out } - fn difficulty_id(&self) -> i32 { + pub(super) fn difficulty_id(&self) -> i32 { use horizon_world::food::Difficulty; match self.world.health_rules.difficulty { Difficulty::Peaceful => 0, diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 923818a08..76179573e 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -24,7 +24,9 @@ use horizon_world::{ }; use std::{path::Path, sync::Arc}; mod lod; +mod structure_mobs; use lod::VanillaLodSampler; +use structure_mobs::StructureMobFinalizer; pub struct VanillaTerrain { generator: OverworldGenerator, @@ -32,6 +34,7 @@ pub struct VanillaTerrain { biome_map: Vec, /// Loot tables for generated containers. loot: Option>, + structure_mobs: Arc, /// A worker for structure queries from the game thread. query: std::sync::Mutex>, /// Block state id -> block index, the game's block tick type: worldgen @@ -138,6 +141,10 @@ impl VanillaTerrain { generator, biome_map, loot, + structure_mobs: Arc::new(StructureMobFinalizer::new( + dir.parent().unwrap_or(dir).to_owned(), + dimension, + )), query: std::sync::Mutex::new(None), tick_blocks, tick_states, @@ -147,6 +154,11 @@ impl VanillaTerrain { created: std::time::Instant::now(), }) } + /// The difficulty (0 peaceful to 3 hard) and overworld clock structure + /// mobs are finalized with. + pub fn set_spawn_conditions(&self, difficulty: u8, day_time: i64) { + self.structure_mobs.set_conditions(difficulty, day_time); + } /// A proto chunk's blocks, biomes, scheduled ticks and post-processing /// marks as a column. fn column(&self, chunk: &ProtoChunk) -> Chunk { @@ -354,7 +366,9 @@ pub fn shared_data( impl ChunkGenerator for VanillaTerrain { type Worker = GeneratorWorker; fn worker(&self) -> GeneratorWorker { - self.generator.worker() + let mut worker = self.generator.worker(); + worker.set_structure_mobs(self.structure_mobs.clone()); + worker } fn lod_sampler(self: Arc) -> Box { Box::new(VanillaLodSampler::new(self)) diff --git a/crates/horizon-client/src/vanillagen/structure_mobs.rs b/crates/horizon-client/src/vanillagen/structure_mobs.rs new file mode 100644 index 000000000..dec5aa92b --- /dev/null +++ b/crates/horizon-client/src/vanillagen/structure_mobs.rs @@ -0,0 +1,446 @@ +//! `Mob.finalizeSpawn(level, level.getCurrentDifficultyAt(pos), STRUCTURE, null)` +//! of the mobs structures place (StructureTemplate.placeEntities with +//! finalizeEntities, ocean ruin drowned, mansion illagers, witch huts, +//! monuments), run as decoration places them, with the WorldGenRegion's random. +use crate::{ + enchant::Enchantments, + entity_nbt, + items::Items, + mobs::{ + Mob, MobType, MobTypes, + finalize::{self, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries}, + spawning::{LocalDifficulty, MOON_BRIGHTNESS}, + }, +}; +use chrono::Datelike; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + nbt::{Compound, Tag}, + worldgen::{generator::StructureMobs, structure::legacy::PieceRandom}, +}; +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::{ + Arc, OnceLock, + atomic::{AtomicI64, AtomicU8, Ordering}, + }, +}; + +struct Data { + types: HashMap>, + biome_tags: HashMap>, + registries: SpawnRegistries, + enchantments: Enchantments, + items: Items, + camel_husk: (f32, f32), +} +fn load(root: &std::path::Path) -> Option { + let types = MobTypes::load(root).ok()?.types; + let camel = types.get("minecraft:camel_husk")?; + let camel_husk = (camel.width as f32, camel.height as f32); + Some(Data { + types: types.into_iter().map(|(k, t)| (k, Arc::new(t))).collect(), + biome_tags: crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(), + registries: SpawnRegistries::load(root), + enchantments: Enchantments::load(root), + items: Items::tags_only(root).ok()?, + camel_husk, + }) +} + +pub struct StructureMobFinalizer { + root: PathBuf, + dimension: String, + data: OnceLock>, + /// The level's difficulty (0 peaceful to 3 hard) and overworld clock. + difficulty: AtomicU8, + day_time: AtomicI64, +} +impl StructureMobFinalizer { + pub fn new(root: PathBuf, dimension: &str) -> Self { + Self { + root, + dimension: dimension.to_owned(), + data: OnceLock::new(), + difficulty: AtomicU8::new(2), + day_time: AtomicI64::new(0), + } + } + pub fn set_conditions(&self, difficulty: u8, day_time: i64) { + self.difficulty.store(difficulty, Ordering::Relaxed); + self.day_time.store(day_time, Ordering::Relaxed); + } +} + +struct Level<'a> { + data: &'a Data, + biome: &'a str, + structures: &'a [String], + difficulty: u8, + day_time: i64, + next_id: u32, +} +impl FinalizeLevel for Level<'_> { + fn biome(&self, _: [i32; 3]) -> String { + self.biome.to_owned() + } + fn biome_tag(&self, tag: &str, _: [i32; 3]) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|b| b.contains(self.biome)) + } + fn structures_with_piece_at(&self, _: [i32; 3]) -> Vec { + self.structures.to_vec() + } + fn moon_phase(&self, _: [i32; 3]) -> usize { + self.day_time.div_euclid(24000).rem_euclid(8) as usize + } + fn spawning_monsters(&self) -> bool { + self.difficulty != 0 + } + // No block collision: only a husk's camel asks, and no structure places husks. + fn no_collision(&self, _: Aabb) -> bool { + true + } + // WorldGenRegion holds no entities. + fn free_chicken(&self, _: Aabb) -> Option { + None + } + fn ride_chicken(&mut self, _: u32, _: u32) {} + fn game_time(&self) -> i64 { + self.day_time + } + fn halloween(&self) -> bool { + let today = chrono::Local::now(); + (today.month(), today.day()) == (10, 31) + } + fn create(&mut self, kind: &str, _: Reason) -> Option { + if self.difficulty == 0 && !finalize::allowed_in_peaceful(kind) { + return None; + } + let t = self.data.types.get(kind)?.clone(); + self.next_id += 1; + Some(Mob::new(self.next_id, t, Vec3::ZERO, 0.0)) + } +} + +fn run( + level: &mut Level<'_>, + random: &mut R, + difficulty: LocalDifficulty, + data: &SpawnData<'_>, + m: &mut Mob, +) -> Vec { + let mut cx = Ctx { + level, + random, + difficulty, + data, + created: Vec::new(), + }; + cx.finalize(m, Reason::Structure, None); + cx.created +} + +/// The saved compound of mob `i` with the mobs riding it under `Passengers`. +fn tree(mobs: &[(Mob, Option)], i: usize, dimension: &str) -> Compound { + let (m, raw) = &mobs[i]; + let Tag::Compound(mut c) = entity_nbt::mob_to_nbt(m, [0; 4], raw.as_ref()) else { + return Compound::new(); + }; + c.remove(&"UUID".into()); + entity_nbt::put_brain(&mut c, m, dimension); + let riders: Vec = (0..mobs.len()) + .filter(|&j| mobs[j].0.extra.mount == Some(m.id)) + .map(|j| Tag::Compound(tree(mobs, j, dimension))) + .collect(); + if !riders.is_empty() { + c.insert("Passengers".into(), Tag::List(riders)); + } + c +} + +impl StructureMobs for StructureMobFinalizer { + fn finalize( + &self, + nbt: &mut Compound, + biome: &str, + structures: &[String], + random: &mut dyn PieceRandom, + ) -> bool { + let Some(data) = self.data.get_or_init(|| { + let data = load(&self.root); + if data.is_none() { + log::error!("Horizon: no mob data, structure mobs are finalized when loaded"); + } + data + }) else { + return false; + }; + let mut raw = Tag::Compound(nbt.clone()); + if let Tag::Compound(c) = &mut raw { + c.remove(&"horizon:finalize".into()); + } + let Some(mut m) = entity_nbt::mob_from_nbt(&raw, &data.types, 1) else { + // Not a mob: vanilla finalizes only Mob instances. + return true; + }; + let base = self.difficulty.load(Ordering::Relaxed); + let day_time = self.day_time.load(Ordering::Relaxed); + let mut level = Level { + data, + biome, + structures, + difficulty: base, + day_time, + next_id: 1, + }; + let moon = MOON_BRIGHTNESS[level.moon_phase([0; 3])]; + // WorldGenRegion.getCurrentDifficultyAt: no inhabited time. + let difficulty = LocalDifficulty::new(base, day_time, 0, moon); + let spawn = SpawnData { + registries: &data.registries, + enchantments: &data.enchantments, + items: &data.items, + camel_husk_size: data.camel_husk, + }; + let any = random.as_any(); + let created = if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else { + log::error!("Horizon: unknown region random, structure mobs are finalized when loaded"); + return false; + }; + let mut mobs = vec![(m, Some(raw))]; + mobs.extend(created.into_iter().map(|c| (c, None))); + let root = mobs + .iter() + .position(|(m, _)| m.extra.mount.is_none()) + .unwrap_or(0); + *nbt = tree(&mobs, root, &self.dimension); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The bastion's crossbow piglin keeps its crossbow (STRUCTURE skips + /// createSpawnWeapon) and saves what Piglin.addAdditionalSaveData writes. + #[test] + fn bastion_crossbow_piglin_finalizes_as_structure() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let file = root.join("worldgen/structure/minecraft/bastion/mobs/crossbow_piglin.nbt"); + let mut bytes = Vec::new(); + std::io::Read::read_to_end( + &mut flate2::read::GzDecoder::new(std::fs::File::open(file).unwrap()), + &mut bytes, + ) + .unwrap(); + let limits = horizon_world::nbt::Limits::templates(); + let template = horizon_world::nbt::read_named(&bytes, limits) + .unwrap() + .0 + .tag; + let Some(Tag::List(entities)) = template.get("entities") else { + panic!("no entities"); + }; + let Some(Tag::Compound(mut nbt)) = entities[0].get("nbt").cloned() else { + panic!("no nbt"); + }; + nbt.remove(&"UUID".into()); + let hook = StructureMobFinalizer::new(root, "minecraft:the_nether"); + let mut random = LegacyRandom::new(12345); + hook.finalize(&mut nbt, "minecraft:nether_wastes", &[], &mut random); + let keys: Vec = { + let mut k: Vec = nbt.keys().map(|k| k.to_string_lossy()).collect(); + k.sort(); + k + }; + assert_eq!( + keys, + [ + "AbsorptionAmount", + "Air", + "Brain", + "CanPickUpLoot", + "CannotHunt", + "DeathTime", + "FallFlying", + "Fire", + "Health", + "HurtTime", + "Inventory", + "Invulnerable", + "IsBaby", + "IsImmuneToZombification", + "LeftHanded", + "Motion", + "OnGround", + "PersistenceRequired", + "PortalCooldown", + "Pos", + "Rotation", + "TimeInOverworld", + "attributes", + "current_impulse_context_reset_grace_time", + "equipment", + "fall_distance", + "id", + ] + ); + let tag = Tag::Compound(nbt); + let held = tag.get("equipment").and_then(|e| e.get("mainhand")); + assert!( + matches!(held.and_then(|h| h.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:crossbow") + ); + let hunted = tag + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")); + assert!(matches!( + hunted.and_then(|h| h.get("ttl")), + Some(Tag::Long(600..=2400)) + )); + let Some(Tag::List(attributes)) = tag.get("attributes") else { + panic!("no attributes"); + }; + assert!(attributes.iter().any(|a| { + matches!(a.get("id"), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:follow_range") + && matches!(a.get("modifiers"), Some(Tag::List(m)) if m.len() == 1) + })); + } + + fn id(t: Option<&Tag>) -> String { + match t.and_then(|t| t.get("id")) { + Some(Tag::String(s)) => s.to_string_lossy().trim_start_matches("minecraft:").into(), + _ => "-".into(), + } + } + /// What a vanilla world saves of a structure mob that finalizeSpawn decides. + fn describe(mob: &Tag) -> String { + let eq = mob.get("equipment"); + let gear: Vec = ["mainhand", "head", "chest", "legs", "feet"] + .iter() + .map(|slot| id(eq.and_then(|e| e.get(slot)))) + .collect(); + let ttl = match mob + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")) + .and_then(|h| h.get("ttl")) + { + Some(Tag::Long(t)) => t.to_string(), + _ => "-".into(), + }; + let bonus = crate::entity_nbt::spawn_bonus(mob).unwrap_or(f64::NAN); + let flag = |k: &str| matches!(mob.get(k), Some(Tag::Byte(1))); + let riders = match mob.get("Passengers") { + Some(Tag::List(p)) => format!( + " [{}]", + p.iter().map(describe).collect::>().join("; ") + ), + _ => String::new(), + }; + format!( + "{} {} ttl={ttl} bonus={bonus:.6} left={} baby={}{riders}", + id(Some(mob)), + gear.join(","), + flag("LeftHanded"), + flag("IsBaby") || matches!(mob.get("Age"), Some(Tag::Int(a)) if *a < 0), + ) + } + /// The described entities of chunk (x, z) after decorating the 3x3 around it. + fn chunk_mobs( + root: &std::path::Path, + seed: i64, + dimension: &str, + x: i32, + z: i32, + ) -> Vec { + use crate::streaming::{ChunkGenerator, Proto}; + let assets = crate::assets::Assets::load(root).unwrap(); + let biomes = crate::biome::Biomes::load(root).unwrap(); + let terrain = super::super::VanillaTerrain::for_dimension( + &root.join("worldgen"), + assets.registry, + &biomes, + seed, + dimension, + ) + .unwrap(); + let mut worker = terrain.worker(); + let mut region: [Proto; 9] = std::array::from_fn(|i| { + terrain.proto(&mut worker, x + i as i32 % 3 - 1, z + i as i32 / 3 - 1) + }); + terrain.decorate(&mut worker, &mut region); + let center = std::mem::replace(&mut region[4], Box::new(())); + let mut got: Vec = terrain + .finish(center) + .entities + .iter() + .map(describe) + .collect(); + got.sort(); + got + } + /// Seed 12345's bastion at chunk (-21, 8): the mobs of chunk (-23, 8) as two + /// vanilla 26.3 runs saved them (weapons and armour, hunting memory, follow + /// range bonus, handedness), from the region random of that chunk. The + /// memories are as placed: vanilla saved them 13 brain ticks later. + #[test] + fn bastion_chunk_mobs_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:the_nether", -23, 8); + let mut expected = [ + "piglin golden_sword,-,golden_chestplate,-,- ttl=1760 bonus=0.013784", + "piglin crossbow,-,-,-,- ttl=806 bonus=-0.011458", + "piglin golden_sword,-,-,-,- ttl=1315 bonus=-0.084585", + "piglin golden_sword,-,-,-,- ttl=1489 bonus=-0.038292", + "piglin_brute golden_axe,-,-,-,- ttl=- bonus=-0.020574", + "piglin crossbow,-,-,-,- ttl=1620 bonus=-0.079135", + "hoglin -,-,-,-,- ttl=- bonus=-0.012052", + "piglin golden_sword,-,-,-,- ttl=783 bonus=-0.077071", + "piglin crossbow,-,-,golden_leggings,- ttl=1431 bonus=0.007058", + ] + .map(|e| format!("{e} left=false baby=false")); + expected.sort(); + assert_eq!(got, expected); + } + + /// Seed 12345's ocean ruin at (53, 39, 424): Drowned.finalizeSpawn mounts the + /// trident drowned on a zombie nautilus, as vanilla saved chunk (3, 26). + #[test] + fn ocean_ruin_drowned_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:overworld", 3, 26); + let d = |gear: &str, bonus: &str| { + format!("drowned {gear},-,-,-,- ttl=- bonus={bonus} left=false baby=false") + }; + let mut expected = vec![ + d("-", "0.001996"), + format!( + "zombie_nautilus -,-,-,-,- ttl=- bonus=-0.044983 left=false baby=false [{}]", + d("trident", "-0.045604") + ), + d("fishing_rod", "-0.059079"), + d("-", "0.021658"), + ]; + expected.sort(); + assert_eq!(got, expected); + } +} diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7a38608be..3bf0e86b3 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1648,6 +1648,22 @@ pub(super) struct WorkerState { heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). pub(super) structures_only: bool, + pub(super) structure_mobs: Option>, +} +/// `Mob.finalizeSpawn(level, difficulty, STRUCTURE, null)` of the entities a +/// structure places with finalizeEntities, run by the game, which owns mobs. +pub trait StructureMobs: Send + Sync { + /// Finalizes the entity in `nbt` if it is a mob, drawing from the + /// region's random. `biome` is the biome at its block, `structures` the + /// structures with a piece there. False when it could not: the entity + /// keeps its `horizon:finalize` for the game to finish on load. + fn finalize( + &self, + nbt: &mut crate::nbt::Compound, + biome: &str, + structures: &[String], + random: &mut dyn super::structure::legacy::PieceRandom, + ) -> bool; } trait SeededPipeline: Send + Sync { @@ -2464,6 +2480,7 @@ impl OverworldGenerator { carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, + structure_mobs: None, heights: HashMap::new(), }, } @@ -2590,6 +2607,9 @@ impl GeneratorWorker { pub fn set_structures_only(&mut self, only: bool) { self.state.structures_only = only; } + pub fn set_structure_mobs(&mut self, mobs: Arc) { + self.state.structure_mobs = Some(mobs); + } } #[cfg(test)] diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc1cd8bcf..08611a325 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -310,6 +310,7 @@ impl Decoration { Err(e) => return Err(resource(e.to_string())), }; let structures_only = worker.structures_only; + let references = region[4].structure_starts.clone(); let mut block_entities = Vec::new(); for chunk in region.iter_mut() { block_entities.append(&mut chunk.block_entities); @@ -318,6 +319,9 @@ impl Decoration { block_entities, entities: Vec::new(), level_random, + structure_mobs: worker.structure_mobs.clone(), + starts: references.clone(), + biome_names: data.biome_names(), blocks: data .feature_resources .as_ref() @@ -334,7 +338,6 @@ impl Decoration { }; let mut stats = DecorateStats::default(); let blocks = self.blocks; - let references = region[4].structure_starts.clone(); // ChunkGenerator.getWritableArea: the chunk's minimum Y + 1 to its maximum Y. let chunk_box = BoundingBox::new( [center.x * 16, min_y + 1, center.z * 16], @@ -419,15 +422,11 @@ impl Decoration { } // WorldGenRegion.addFreshEntity: into the chunk holding the position. for nbt in std::mem::take(&mut world.entities) { - let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + let Some(at) = block_of(&nbt) else { continue; }; - let coord = |i: usize| match p.get(i) { - Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }; - let index = ((coord(2) >> 4).wrapping_sub(center.z) + 1) * 3 - + (coord(0) >> 4).wrapping_sub(center.x) + let index = ((at[2] >> 4).wrapping_sub(center.z) + 1) * 3 + + (at[0] >> 4).wrapping_sub(center.x) + 1; if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { chunk.entities.push(nbt); @@ -454,6 +453,9 @@ struct World<'a> { block_entities: Vec<([i32; 3], crate::nbt::Compound)>, entities: Vec, level_random: &'a mut dyn super::structure::legacy::PieceRandom, + structure_mobs: Option>, + starts: Vec>, + biome_names: &'a [Arc], blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, biomes: BiomeRegion, @@ -847,7 +849,27 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } - fn add_entity(&mut self, nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + fn add_entity(&mut self, mut nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + if let Some(mobs) = self.structure_mobs.clone() + && nbt.contains_key(&"horizon:finalize".into()) + { + let at = block_of(&nbt).unwrap_or([0; 3]); + let biome = self + .biome_identity(at) + .ok() + .and_then(|b| self.biome_names.get(b.0 as usize)) + .map_or("", |n| &**n) + .to_owned(); + let structures: Vec = self + .starts + .iter() + .filter(|s| s.pieces.iter().any(|p| p.bounding_box().is_inside(at))) + .map(|s| s.name.clone()) + .collect(); + if mobs.finalize(&mut nbt, &biome, &structures, self.level_random) { + nbt.remove(&"horizon:finalize".into()); + } + } self.entities.push(nbt); Ok(()) } @@ -1167,3 +1189,14 @@ impl PlacementContext for World<'_> { Ok(Some(false)) } } + +/// The block an entity's `Pos` is in. +fn block_of(nbt: &crate::nbt::Compound) -> Option<[i32; 3]> { + let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + return None; + }; + Some(std::array::from_fn(|i| match p.get(i) { + Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, + _ => 0, + })) +} diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index 785b5fb2e..19d121718 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -31,14 +31,19 @@ pub type Markers = Vec<(String, [i32; 3])>; pub trait PieceRandom: ProcessorRandom { fn boolean(&mut self) -> bool; fn double(&mut self) -> f64; + /// The concrete random, for callers that need all of `RandomSource`. + fn as_any(&mut self) -> &mut dyn std::any::Any; } -impl PieceRandom for R { +impl PieceRandom for R { fn boolean(&mut self) -> bool { self.next_boolean() } fn double(&mut self) -> f64 { self.next_double() } + fn as_any(&mut self) -> &mut dyn std::any::Any { + self + } } /// Object-safe world access for piece post-processing. From a891037c9f7ee4dbd3b12b6d971305bce3d8ccbb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:24:54 +0100 Subject: [PATCH 112/132] parity: harnesses build horizon-client in the fast profile only Under parity.py the release and fast profiles have identical settings (PROFILE: no LTO, 16 codegen units, incremental), yet 38 harnesses built horizon-client in release and 16 others in fast: every run where the client changed compiled it twice. They all use fast now. Release stays for horizon-world's probes, which no fast harness builds. Measured on playhorizon (4 CPUs), all 13 probe builds after 78 merges: 1578 s, of which the release client (bin + client_probe) took 485 s. Co-Authored-By: Claude Opus 5.5 --- tools/test_block_removal_parity.py | 4 ++-- tools/test_command_exec_parity.py | 4 ++-- tools/test_command_parse_parity.py | 4 ++-- tools/test_composter_parity.py | 4 ++-- tools/test_crafter_parity.py | 4 ++-- tools/test_dedicated_server_parity.py | 4 ++-- tools/test_dispenser_parity.py | 4 ++-- tools/test_enchanting_parity.py | 4 ++-- tools/test_entity_death_loot_parity.py | 4 ++-- tools/test_finalize_spawn_parity.py | 4 ++-- tools/test_locator_bar_parity.py | 4 ++-- tools/test_mace_parity.py | 4 ++-- tools/test_mob_ai_parity.py | 4 ++-- tools/test_mob_attributes_parity.py | 4 ++-- tools/test_natural_spawn_parity.py | 4 ++-- tools/test_online_mode_parity.py | 4 ++-- tools/test_raid_parity.py | 4 ++-- tools/test_scoreboard_parity.py | 4 ++-- tools/test_sculk_parity.py | 4 ++-- tools/test_secure_chat_parity.py | 4 ++-- tools/test_server_dimension_players_parity.py | 4 ++-- tools/test_server_dragon_parity.py | 4 ++-- tools/test_server_entities_parity.py | 4 ++-- tools/test_server_knockback_parity.py | 4 ++-- tools/test_server_ops_feedback_parity.py | 4 ++-- tools/test_server_player_targets_parity.py | 4 ++-- tools/test_server_resource_pack_parity.py | 4 ++-- tools/test_server_world_gen_parity.py | 4 ++-- tools/test_spawn_rules_parity.py | 4 ++-- tools/test_spawner_parity.py | 4 ++-- tools/test_subtitle_parity.py | 4 ++-- tools/test_team_rules_parity.py | 4 ++-- tools/test_trading_parity.py | 4 ++-- tools/test_trial_spawner_parity.py | 4 ++-- tools/test_use_item_on_parity.py | 4 ++-- tools/test_user_cache_parity.py | 4 ++-- tools/test_vault_parity.py | 4 ++-- tools/test_world_spawn_parity.py | 8 ++++---- 38 files changed, 78 insertions(+), 78 deletions(-) diff --git a/tools/test_block_removal_parity.py b/tools/test_block_removal_parity.py index 3185bd4bb..169806f6e 100755 --- a/tools/test_block_removal_parity.py +++ b/tools/test_block_removal_parity.py @@ -180,9 +180,9 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) - d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work, env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) # Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared. ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) diff --git a/tools/test_command_exec_parity.py b/tools/test_command_exec_parity.py index 7993a93a7..230e72890 100644 --- a/tools/test_command_exec_parity.py +++ b/tools/test_command_exec_parity.py @@ -79,9 +79,9 @@ def main(): run(['java', '-Xmx3G', '-Duser.timezone=UTC', '-cp', os.pathsep.join([str(classes), str(jars['server']), dependency_path]), 'dev.horizonlab.parity.VanillaCommandExecOracle', vanilla_dir / 'universe', script_path, build / 'vanilla.jsonl', SEED], 'java', cwd=vanilla_dir) - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], 'compile-rust', cwd=lab.ROOT) + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], 'compile-rust', cwd=lab.ROOT) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') rust_dir = build / 'rust' shutil.rmtree(rust_dir, ignore_errors=True) rust_dir.mkdir() diff --git a/tools/test_command_parse_parity.py b/tools/test_command_parse_parity.py index 620fb548d..8d8007d0d 100644 --- a/tools/test_command_parse_parity.py +++ b/tools/test_command_parse_parity.py @@ -64,9 +64,9 @@ def main(): registries = json.loads((build / 'registries.json').read_text()) corpus = corpus_module.corpus(tree, registries) (build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') resources = lab.RESOURCES total_failures = 0 summary = [] diff --git a/tools/test_composter_parity.py b/tools/test_composter_parity.py index 074b227a8..83b99e9b5 100644 --- a/tools/test_composter_parity.py +++ b/tools/test_composter_parity.py @@ -122,9 +122,9 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) - d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work, env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/test_crafter_parity.py b/tools/test_crafter_parity.py index b9c343d4d..dcb5cd127 100644 --- a/tools/test_crafter_parity.py +++ b/tools/test_crafter_parity.py @@ -242,9 +242,9 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) - d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work, env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 7572ee3e2..9d7080c7f 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -424,11 +424,11 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], build, 'compile-java') - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build, 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.RESOURCES, '--dedicated', '--nogui'] diff --git a/tools/test_dispenser_parity.py b/tools/test_dispenser_parity.py index a2c6ba036..729d8e8b7 100644 --- a/tools/test_dispenser_parity.py +++ b/tools/test_dispenser_parity.py @@ -417,9 +417,9 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) - run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work, env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) # Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared. ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) diff --git a/tools/test_enchanting_parity.py b/tools/test_enchanting_parity.py index 35f0777c8..9e070c3cb 100644 --- a/tools/test_enchanting_parity.py +++ b/tools/test_enchanting_parity.py @@ -56,9 +56,9 @@ def main(): with (build / (name + '.log')).open('w', encoding='utf-8') as log: base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'enchanting_fixture',resources, inputs, build / 'rust.txt'], 'rust') references = [] for side in ['server']: diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py index 07c77b0b8..2bb53ebbb 100644 --- a/tools/test_entity_death_loot_parity.py +++ b/tools/test_entity_death_loot_parity.py @@ -139,9 +139,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'entity_death_loot_fixture', resources, inputs, build / 'rust.txt'], 'rust') errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] if errors: diff --git a/tools/test_finalize_spawn_parity.py b/tools/test_finalize_spawn_parity.py index 7d581fefc..0e889598c 100644 --- a/tools/test_finalize_spawn_parity.py +++ b/tools/test_finalize_spawn_parity.py @@ -148,9 +148,9 @@ def main(): print(f'{len(vanilla)} oracle lines') return halloween = vanilla[0].split()[1] - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'finalize_spawn_fixture', resources, inputs, build / 'rust.txt', halloween], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] diff --git a/tools/test_locator_bar_parity.py b/tools/test_locator_bar_parity.py index 6574af76e..05f479461 100644 --- a/tools/test_locator_bar_parity.py +++ b/tools/test_locator_bar_parity.py @@ -258,12 +258,12 @@ def sides(name): subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] diff --git a/tools/test_mace_parity.py b/tools/test_mace_parity.py index 578e9e6ee..2ff560b8d 100644 --- a/tools/test_mace_parity.py +++ b/tools/test_mace_parity.py @@ -167,9 +167,9 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) - d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work, env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 133deca2d..9d88ca18d 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -525,7 +525,7 @@ def main(): 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world], build, 'vanilla', timeout=3600) if not args.java_only: - command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'client_probe'] + command = ['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'] target, env = lab.cargo_target(), None if args.trace: target = lab.LOCAL / 'mob-ai-trace-target' @@ -533,7 +533,7 @@ def main(): env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only', CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16') oracle_harness.run_logged(command, build, 'compile-rust', env=env) - binary = target / 'release/examples/client_probe' + binary = target / 'fast/examples/client_probe' oracle_harness.run_logged([binary, 'mob_ai_probe', lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') if args.java_only: return diff --git a/tools/test_mob_attributes_parity.py b/tools/test_mob_attributes_parity.py index 7fa1df5e6..27f2b238b 100755 --- a/tools/test_mob_attributes_parity.py +++ b/tools/test_mob_attributes_parity.py @@ -62,8 +62,8 @@ def main(): subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/client_probe' + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + binary = lab.cargo_target() / 'fast/examples/client_probe' resources = lab.RESOURCES run([binary, 'mob_attributes_fixture', resources, build / 'rust.txt'], 'rust') vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt') diff --git a/tools/test_natural_spawn_parity.py b/tools/test_natural_spawn_parity.py index 50781eca7..bd3eb2540 100644 --- a/tools/test_natural_spawn_parity.py +++ b/tools/test_natural_spawn_parity.py @@ -568,9 +568,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py index 8096efd80..002516896 100644 --- a/tools/test_online_mode_parity.py +++ b/tools/test_online_mode_parity.py @@ -351,11 +351,11 @@ def main(): build.mkdir(parents=True, exist_ok=True) report = build / 'report.json' report.unlink(missing_ok=True) - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build, 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) services = Services() diff --git a/tools/test_raid_parity.py b/tools/test_raid_parity.py index 4928c9715..6beadf52b 100644 --- a/tools/test_raid_parity.py +++ b/tools/test_raid_parity.py @@ -335,9 +335,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaRaidOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'raid_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_scoreboard_parity.py b/tools/test_scoreboard_parity.py index b38dfb301..8098ae681 100644 --- a/tools/test_scoreboard_parity.py +++ b/tools/test_scoreboard_parity.py @@ -250,9 +250,9 @@ def main(): inputs = build / 'inputs.jsonl' inputs.write_text(''.join(json.dumps(c, ensure_ascii=False) + '\n' for c in chosen), encoding='utf-8') run([*oracle, 'run', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'scoreboard_fixture',build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') read = lambda p: [json.loads(l) for l in p.read_text(encoding='utf-8').splitlines()] vanilla, rust = read(build / 'vanilla.jsonl'), read(build / 'rust.jsonl') diff --git a/tools/test_sculk_parity.py b/tools/test_sculk_parity.py index bff5ad5ba..b4195e5c3 100644 --- a/tools/test_sculk_parity.py +++ b/tools/test_sculk_parity.py @@ -336,9 +336,9 @@ def main(): 'dev.horizonlab.parity.VanillaSculkOracle', inputs, build / 'vanilla.txt'], build, 'vanilla', timeout=3600) if not args.java_only: - oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], + oracle_harness.run_logged(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build, 'compile-rust') - oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon', + oracle_harness.run_logged([lab.cargo_target() / 'fast/horizon-client', '--resources', resources], build, 'horizon', env=lab.game_env(HORIZON_SCULK_FIXTURE=f'{inputs},{build / "horizon.txt"}')) if args.java_only: return diff --git a/tools/test_secure_chat_parity.py b/tools/test_secure_chat_parity.py index b9062568a..a4f77470f 100644 --- a/tools/test_secure_chat_parity.py +++ b/tools/test_secure_chat_parity.py @@ -254,11 +254,11 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], build, 'compile-java') - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build, 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') java = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.SecureChatClient'] oh.run_logged([*java, 'keys', build], build, 'keys') diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index ea026a509..887ebb2d7 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -118,12 +118,12 @@ def main(): subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] diff --git a/tools/test_server_dragon_parity.py b/tools/test_server_dragon_parity.py index dc58e851d..563ac788a 100644 --- a/tools/test_server_dragon_parity.py +++ b/tools/test_server_dragon_parity.py @@ -101,12 +101,12 @@ def main(): # SERVER_DRAGON_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript. sides = [s for s in os.environ.get('SERVER_DRAGON_SIDES', 'vanilla,horizon').split(',') if s] if 'horizon' in sides: - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, diff --git a/tools/test_server_entities_parity.py b/tools/test_server_entities_parity.py index fba196c72..b8c5a7def 100644 --- a/tools/test_server_entities_parity.py +++ b/tools/test_server_entities_parity.py @@ -157,12 +157,12 @@ def main(): # SERVER_ENTITIES_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript. sides = [s for s in os.environ.get('SERVER_ENTITIES_SIDES', 'vanilla,horizon').split(',') if s] if 'horizon' in sides: - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py index 66b75946e..b3c4355ea 100644 --- a/tools/test_server_knockback_parity.py +++ b/tools/test_server_knockback_parity.py @@ -334,12 +334,12 @@ def main(): subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.KnockbackClient'] diff --git a/tools/test_server_ops_feedback_parity.py b/tools/test_server_ops_feedback_parity.py index 91854fac6..eb7788545 100644 --- a/tools/test_server_ops_feedback_parity.py +++ b/tools/test_server_ops_feedback_parity.py @@ -118,12 +118,12 @@ def main(): subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index 263aa4a59..321a39f06 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -169,12 +169,12 @@ def main(): subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) import json metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] diff --git a/tools/test_server_resource_pack_parity.py b/tools/test_server_resource_pack_parity.py index 0f5d258c6..10965d273 100644 --- a/tools/test_server_resource_pack_parity.py +++ b/tools/test_server_resource_pack_parity.py @@ -134,9 +134,9 @@ def main(): subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) - binary = lab.cargo_target() / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = lab.cargo_target() / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.ServerPackClient'] diff --git a/tools/test_server_world_gen_parity.py b/tools/test_server_world_gen_parity.py index f55e55809..14da72a6d 100644 --- a/tools/test_server_world_gen_parity.py +++ b/tools/test_server_world_gen_parity.py @@ -130,11 +130,11 @@ def main(): build.mkdir(parents=True, exist_ok=True) report = build / 'report.json' report.unlink(missing_ok=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py index 7f9ac07ce..01196b355 100644 --- a/tools/test_spawn_rules_parity.py +++ b/tools/test_spawn_rules_parity.py @@ -155,9 +155,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'spawn_rules_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py index 187e211b7..34f6ec726 100644 --- a/tools/test_spawner_parity.py +++ b/tools/test_spawner_parity.py @@ -249,9 +249,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_subtitle_parity.py b/tools/test_subtitle_parity.py index 6baf25570..17c856550 100644 --- a/tools/test_subtitle_parity.py +++ b/tools/test_subtitle_parity.py @@ -133,9 +133,9 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityFont', 'VanillaSubtitleOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSubtitleOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'subtitle_fixture',resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text(encoding='utf-8').splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text(encoding='utf-8').splitlines()] diff --git a/tools/test_team_rules_parity.py b/tools/test_team_rules_parity.py index ac66a412b..9d12075ec 100644 --- a/tools/test_team_rules_parity.py +++ b/tools/test_team_rules_parity.py @@ -84,9 +84,9 @@ def main(): PARITY / 'VanillaTeamRulesOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTeamRulesOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe') run([binary, 'team_rules_fixture',inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] diff --git a/tools/test_trading_parity.py b/tools/test_trading_parity.py index 46e81f928..9b5581f3b 100644 --- a/tools/test_trading_parity.py +++ b/tools/test_trading_parity.py @@ -219,8 +219,8 @@ def main(): if args.java_only: print(f'{len(vanilla)} oracle lines') return - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/client_probe' + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + binary = lab.cargo_target() / 'fast/examples/client_probe' run([binary, 'trading_fixture', resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] diff --git a/tools/test_trial_spawner_parity.py b/tools/test_trial_spawner_parity.py index 7b2412eaa..43d26338a 100644 --- a/tools/test_trial_spawner_parity.py +++ b/tools/test_trial_spawner_parity.py @@ -214,9 +214,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index eabdd04eb..35e1c5515 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -405,9 +405,9 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) - d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work, env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/test_user_cache_parity.py b/tools/test_user_cache_parity.py index 621514cc8..34a7af1f3 100644 --- a/tools/test_user_cache_parity.py +++ b/tools/test_user_cache_parity.py @@ -205,11 +205,11 @@ def main(): build.mkdir(parents=True, exist_ok=True) report = build / 'report.json' report.unlink(missing_ok=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, check=True, capture_output=True) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') services = Services() discovery = services.url + '/minecraft/client' dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py index 5741320d3..00e6422f5 100644 --- a/tools/test_vault_parity.py +++ b/tools/test_vault_parity.py @@ -190,9 +190,9 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') + run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/client_probe' + binary = Path(metadata['target_directory']) / 'fast/examples/client_probe' run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 00c390005..33bdd4c65 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -69,10 +69,10 @@ def seeds(count): return SEEDS + [rng.randrange(-2**63, 2**63) for _ in range(count)] -def target_dir(): +def target_dir(profile='release'): metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - return Path(metadata['target_directory']) / 'release' + return Path(metadata['target_directory']) / profile def origins(build, classes, dependencies, all_seeds): @@ -134,9 +134,9 @@ def main(): if args.origins_only: sys.exit(1 if origin_diffs else 0) - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build, 'compile-rust', timeout=3600) - binary = target_dir() / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + binary = target_dir('fast') / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') # One worker thread: the chunks decorated in a fixed order (see above). vanilla_server = ['java', '-Xmx2g', '-Dmax.bg.threads=1', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui'] From 1b1571ed6a731d574a30e0bfef224b8e6c5d1fc3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:30:59 +0100 Subject: [PATCH 113/132] parity: a crate split's manifest changes don't select every harness Cargo.lock is a shared input and every harness depends on its crates' Cargo.toml, so a crate split (#2160) selected all 352 harnesses although its moved code reaches 123. With --changed, Cargo.lock and Cargo.toml changes that only add, remove or move workspace crates (no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) are left out; the moved code counts through its own sources. Any other manifest change still counts, as before. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 2 +- tests/test_parity_runner.py | 41 ++++++++++++++++++++++++++ tools/parity.py | 58 ++++++++++++++++++++++++++++++++++++- 3 files changed, 99 insertions(+), 2 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 50b67c571..4d20d32be 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -64,7 +64,7 @@ A harness can declare, at the top level of its script: ### Which harnesses a change affects -`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. +`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. With `--changed`, `Cargo.lock` and `Cargo.toml` changes that only add, remove or move workspace crates (a crate split: no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) don't count: the moved code counts through its sources. #2160's split went from 352 harnesses to 123 this way (its own changes to the runner still select them all). On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. ## The gate diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 49a88f0b1..20b3b1efb 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -401,3 +401,44 @@ class KnownFlakyTests(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class WorkspaceManifestTests(unittest.TestCase): + """A crate split's Cargo.toml and Cargo.lock changes don't select every harness; a dependency change still does.""" + CLIENT = '[package]\nname = "horizon-client"\n\n[dependencies]\nserde = "1"\nwgpu = { version = "27", features = ["x"] }\n' + LOCK = ('version = 4\n\n[[package]]\nname = "horizon-client"\nversion = "0.1.0"\ndependencies = [\n "serde",\n]\n\n' + '[[package]]\nname = "serde"\nversion = "1.0.1"\nsource = "registry+https://github.com/rust-lang/crates.io-index"\n') + + def verdict(self, base, head): + """base, head: {path: text or None}; the manifests workspace_only_manifests leaves out.""" + with tempfile.TemporaryDirectory() as temp, \ + mock.patch.object(parity, "ROOT", Path(temp)), \ + mock.patch.object(parity, "git_show", lambda _base, path: base.get(path)): + for path, text in head.items(): + if text is not None: + Path(temp, path).parent.mkdir(parents=True, exist_ok=True) + Path(temp, path).write_text(text) + return parity.workspace_only_manifests(set(head) | set(base), "base") + + def test_a_crate_split_is_left_out(self): + command = '[package]\nname = "horizon-command"\n\n[dependencies]\nserde = "1"\nhorizon-core = { path = "../horizon-core" }\n' + client = self.CLIENT + 'horizon-command = { path = "../horizon-command" }\n' + lock = self.LOCK.replace('[[package]]\nname = "serde"', '[[package]]\nname = "horizon-command"\nversion = "0.1.0"\n\n' + '[[package]]\nname = "serde"') + base = {"Cargo.toml": '[workspace]\nmembers = ["crates/horizon-client"]\nresolver = "2"\n', + "crates/horizon-client/Cargo.toml": self.CLIENT, "Cargo.lock": self.LOCK} + head = {"Cargo.toml": '[workspace]\nmembers = ["crates/horizon-client", "crates/horizon-command"]\nresolver = "2"\n', + "crates/horizon-client/Cargo.toml": client, "crates/horizon-command/Cargo.toml": command, "Cargo.lock": lock} + self.assertEqual(self.verdict(base, head), set(head)) + + def test_a_dependency_change_still_counts(self): + base = {"crates/horizon-client/Cargo.toml": self.CLIENT, "Cargo.lock": self.LOCK} + bumped = {"crates/horizon-client/Cargo.toml": self.CLIENT, "Cargo.lock": self.LOCK.replace("1.0.1", "1.0.2")} + self.assertEqual(self.verdict(base, bumped), set()) + feature = {"crates/horizon-client/Cargo.toml": self.CLIENT.replace('["x"]', '["x", "y"]')} + self.assertEqual(self.verdict({"crates/horizon-client/Cargo.toml": self.CLIENT}, feature), set()) + resolver = {"Cargo.toml": '[workspace]\nmembers = ["a"]\nresolver = "3"\n'} + self.assertEqual(self.verdict({"Cargo.toml": '[workspace]\nmembers = ["a"]\nresolver = "2"\n'}, resolver), set()) + + def test_without_a_base_everything_counts(self): + self.assertEqual(parity.workspace_only_manifests({"Cargo.lock"}, None), set()) diff --git a/tools/parity.py b/tools/parity.py index a5f7f2db1..76da59b4c 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -1246,6 +1246,58 @@ def trace_main(output, script, arguments): # Files every harness's result depends on (part of environment_key): a change to one affects them all. SHARED_INPUTS = {"research-lock.json", "Cargo.lock"} +# Manifest sections that say what a crate is and where its targets are, not what it builds with. +MANIFEST_SECTION_KEPT = re.compile(r"\[\[?(?:package|lib|bin|example|test|bench|lints|badges)\b[^\]]*\]\]?$") +# A workspace crate named as a dependency (by path, or from the workspace's own table), or listed as a member. +WORKSPACE_LINE = re.compile(r'(?:horizon[\w-]*|cargo-horizon-mod|xtask)\s*=\s*(?:\{[^}]*\b(?:path|workspace)\s*=[^}]*\}|true)' + r'|(?:horizon[\w-]*|cargo-horizon-mod|xtask)\.workspace\s*=\s*true|"crates/[^"]+",?') + + +def git_show(base, path): + """path's content at commit base, or None where it didn't exist.""" + result = subprocess.run(["git", "show", f"{base}:{path}"], cwd=ROOT, capture_output=True, text=True) + return result.stdout if result.returncode == 0 else None + + +def manifest_lines(text): + """A Cargo.toml's lines that decide what is built: (section, line) pairs, without its package's identity and + targets, comments, or workspace crates (whose code counts through its own sources).""" + lines, section = set(), "" + for raw in (text or "").splitlines(): + line = re.sub(r"\s+", " ", raw.split("#", 1)[0]).strip() + if not line: + continue + if line.startswith("["): + section = line + continue + if MANIFEST_SECTION_KEPT.match(section) or WORKSPACE_LINE.fullmatch(line) or \ + section == "[workspace]" and (line.startswith("members =") or line.startswith('"') or line == "]"): + continue + lines.add((section, line)) + return lines + + +def lock_packages(text): + """Cargo.lock's packages from a registry or git (with their versions and checksums); workspace crates' entries + only list what their manifests say.""" + return {block.strip() for block in (text or "").split("[[package]]") if "\nsource = " in block} + + +def workspace_only_manifests(changed, base): + """The changed Cargo.lock and Cargo.toml files whose changes only add, remove or move workspace crates (a crate + split): no external package, version, feature, or build setting changed across them. Their crates' code counts + through its own sources, so these files don't make every harness linking the crates rerun.""" + manifests = sorted(path for path in changed if path == "Cargo.lock" or path.endswith("Cargo.toml")) + if not manifests or base is None: + return set() + if "Cargo.lock" in manifests and \ + lock_packages(git_show(base, "Cargo.lock")) != lock_packages((ROOT / "Cargo.lock").read_text(encoding="utf-8")): + return set() + tomls = [path for path in manifests if path != "Cargo.lock"] + before = set().union(*(manifest_lines(git_show(base, path)) for path in tomls)) if tomls else set() + after = set().union(*(manifest_lines((ROOT / path).read_text(encoding="utf-8") if (ROOT / path).exists() else None) + for path in tomls)) if tomls else set() + return set(manifests) if before == after else set() def changed_files(ref): @@ -1449,7 +1501,11 @@ def main(): if args.changed: merge_base = subprocess.run(["git", "merge-base", "HEAD", args.changed], cwd=ROOT, capture_output=True, text=True) base = merge_base.stdout.strip() or None - affected = affected_harnesses(found, records, changed, reach=not args.by_crate, base=base) + moved = workspace_only_manifests(changed, base) if not args.by_crate else set() + if moved: + print(f"{', '.join(sorted(moved))}: only workspace crates added, removed or moved; their sources count " + "instead", flush=True) + affected = affected_harnesses(found, records, changed - moved, reach=not args.by_crate, base=base) chosen = [name for name in found if name in affected and stale(name, state, hasher, environment)] print(f"{len(changed)} files changed{since}: {len(affected)} harnesses " f"depend on them, {len(chosen)} without a pass for their current inputs.", flush=True) From 9555f375d459e7da0fb4d5ce497985e4f8df310b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:31:29 +0100 Subject: [PATCH 114/132] parity: remote_fireball is no longer known flaky (#2499) Co-Authored-By: Claude Opus 5.5 --- tools/parity_hosts.json | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 29027f87f..60e6205e8 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": { - "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)" } } From 111db2827b9b797baf1ce83548ffaa5e38c1ffbd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:46:29 +0100 Subject: [PATCH 115/132] ci: full-parity and PR parity jobs on playhorizon, not the desktop The maintainer asked that CI stop using his desktop (2026-10-26). playhorizon's runner now carries horizon-game and the desktop's runner none of the job labels; full-parity jobs go to playhorizon only, with a 6 h timeout on its 4 CPUs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parity-main.yml | 4 ++-- .github/workflows/parity.yml | 16 ++++++++-------- docs/release-flow.md | 25 +++++++++++++++---------- 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml index 70fb33796..4840b98be 100644 --- a/.github/workflows/parity-main.yml +++ b/.github/workflows/parity-main.yml @@ -25,8 +25,8 @@ jobs: parity-main: # A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs # this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited - # behind the next run. PR parity jobs have ludovics-mac-mini and the desktop. Not the desktop: a job slowed down - # because the maintainer came back could time out, and a failure here bisects and comments on merges. + # behind the next run. PR parity jobs have ludovics-mac-mini and playhorizon. Not playhorizon: its 4 CPUs + # make a core-crate run several times longer, and a failure here bisects and comments on merges. runs-on: [self-hosted, macOS, horizon-parity-main] timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures steps: diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index b90ad9968..c850c17aa 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -1,6 +1,6 @@ name: parity -# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the maintainer's -# own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository +# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner or playhorizon's, which hold the +# maintainer's own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository # and by run-parity.yml when a maintainer labels a fork's pull request run-parity. See docs/release-flow.md. on: workflow_call: @@ -16,8 +16,8 @@ on: full: description: >- The pull request carries the full-parity label (a change every harness reaches, such as a crate split): it - runs on the desktop's runner only, so the Mac mini's runners stay free for the others. While the desktop is - in use the job waits for it. + runs on playhorizon's runner only, so the Mac mini's runners stay free for the others. While that runner is + busy the job waits for it. type: boolean default: false permissions: @@ -28,10 +28,10 @@ env: jobs: parity: - runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "ludodesktop"]') || fromJSON('["self-hosted", "horizon-game"]') }} - # A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini, ~35 min on the desktop, longer if - # someone comes back to the desktop meanwhile (the job then goes on with 2 threads). - timeout-minutes: ${{ inputs.full && 300 || 120 }} + runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "playhorizon"]') || fromJSON('["self-hosted", "horizon-game"]') }} + # A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini; on playhorizon (4 of its 8 vCPUs, 4 + # harnesses at a time) up to a few hours, and any pull request's job may land there. + timeout-minutes: ${{ inputs.full && 360 || 180 }} steps: - uses: actions/checkout@v4 with: diff --git a/docs/release-flow.md b/docs/release-flow.md index 8373f2bf6..ed7be2418 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -13,7 +13,7 @@ reopened; labels never start it): | Job | Runs on | What | Time | | --- | --- | --- | --- | | `verify` | GitHub `ubuntu-latest` | Public-tree check, Python tests, rustfmt, clippy with warnings denied, Rust tests. Dependencies and the workspace build come from a cache saved by main's runs | ~4 min cold, less warm | -| `parity / parity` | A runner with the label `horizon-game`: the Mac mini's two, and the desktop's while nobody uses it (below) | Only for a change to a harness, an oracle, a probe or the runner (or the `run-parity` label): the vanilla harnesses the change can affect (`tools/parity.py --changed `). Other pull requests skip it: [parity-main](#parity-on-main) checks them on main | seconds when nothing is affected; minutes per affected harness | +| `parity / parity` | A runner with the label `horizon-game`: the Mac mini's and playhorizon's (below) | Only for a change to a harness, an oracle, a probe or the runner (or the `run-parity` label): the vanilla harnesses the change can affect (`tools/parity.py --changed `). Other pull requests skip it: [parity-main](#parity-on-main) checks them on main | seconds when nothing is affected; minutes per affected harness | Pushes to main run `verify` only; the nightly audit covers main's harnesses. @@ -29,12 +29,12 @@ repository, `run-parity.yml` for a fork's pull request a maintainer labels `run- A pull request every harness reaches (a crate split moves files every probe links: #2160 ran all 352 harnesses, 71 minutes on a Mac mini runner, while five other pull requests' jobs queued behind it) carries the `full-parity` label: -its job runs on the desktop's runner only (8 harnesses at a time), and waits for it while the desktop is in use -instead of taking a Mac mini runner. Labels don't start `checks`: add it when opening the pull request +its job runs on playhorizon's runner only (4 harnesses at a time), and waits for it while that runner is busy +instead of taking the Mac mini's. Labels don't start `checks`: add it when opening the pull request (`gh pr create --label full-parity`), or before the next push. Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own -copy is: the Mac mini, his Linux desktop and playhorizon (below). Their runners run as the maintainer's account and keep their checkout +copy is: the Mac mini and playhorizon (below). Their runners run as the maintainer's account and keep their checkout between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes stand. @@ -83,8 +83,9 @@ release's macOS build back. Each keeps its own checkout, `target/` and Rust inst `_work/horizon/shared-local` links to the first's, so they share the vanilla data, the preparations (one at a time, under a lock) and the parity passes and slots. -**The desktop's runner.** `ludodesktop-horizon` (labels `self-hosted`, `Linux`, `X64`, `ludodesktop`, and -`horizon-game` once a full trial has passed there) runs on the maintainer's Linux desktop while nobody uses it: its +**The desktop's runner (retired).** On 2026-10-26 the maintainer asked that CI stop using his desktop: its services are +stopped and `ludodesktop-horizon` has no label a job asks for (only `self-hosted`, `Linux`, `X64`), so nothing waits for +it. What follows describes it as it ran. It ran on the maintainer's Linux desktop while nobody used it: its screen locked, or untouched for 15 minutes (his rule, 2026-10-26). `tools/ci/linux-runner.sh install`, run there as him, registers it and installs two systemd user services: `horizon-runner` (the runner, in `~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O weight 20, half the threads (on all of @@ -105,12 +106,16 @@ and its failures bisect and comment on merges. **playhorizon's runner.** `playhorizon-horizon` runs on a server a hosting partner lends the project (Ubuntu, 8 AMD EPYC threads, 30 GB, in Detroit; reachable only through the maintainer's tailnet). Nobody sits at it, so the -watcher never pauses it except by hand, and it gets the machine: `RUNNER_CPUS=7 RUNNER_MEMORY=24 RUNNER_JOBS=6`. +watcher never pauses it except by hand. It gets half the machine: `RUNNER_MEMORY=24`, `CARGO_BUILD_JOBS` and the +harness slots at 4, and a drop-in (`~/.config/systemd/user/horizon-runner.service.d/cpus.conf`) that starts it under +`taskset -c 4-7`, so CPUs 0-3 stay free for benchmarks pinned there (the user slice can't set `AllowedCPUs`: systemd +doesn't delegate the cpuset controller to it). Without Nix, `linux-runner.sh` takes the build libraries, the JDK, sccache, Xvfb and Mesa's software Vulkan (lavapipe; there is no GPU) from apt, and Python 3.13 from uv. The partner can reach the machine, so gh is not logged in there: the registration token comes from another machine (`RUNNER_TOKEN`), and no job with secrets may -run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 6 jobs). Like -the desktop's, it gets the `horizon-game` label only once a full trial has passed there. +run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 6 jobs). Since +2026-10-26 it has the `horizon-game` label: pull requests' parity jobs run there or on the Mac mini, and `full-parity` +ones only there. ## Merging @@ -218,7 +223,7 @@ How releases are numbered, and how installs from before 0.2 reach it: [versionin | `release-now` | Releases as soon as main's checks pass, without waiting for merges to settle | | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | -| `full-parity` | Runs the pull request's parity job on the desktop's runner only (a change every harness reaches) | +| `full-parity` | Runs the pull request's parity job on playhorizon's runner only (a change every harness reaches) | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | | `release-blocker` | On an issue: no game release is published while it is open ([One channel](#one-channel)) | From 0db65d7a6192b6700d871cf3579edb63018343c2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:06:57 +0100 Subject: [PATCH 116/132] Cargo.toml: one workspace member per line Each new crate then adds one line instead of rewriting the whole list, so PRs that add crates at the same time stop conflicting (the crate split's #2160 conflicted on it three times). Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index f0529d098..f256fff20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,43 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "crates/horizon-mod-sdk/examples/beacons", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask", "mods/official/recipes"] +members = [ + "crates/horizon-core", + "crates/horizon-dualsense", + "crates/horizon-threads", + "crates/horizon-hdr", + "crates/horizon-world", + "crates/horizon-client", + "crates/horizon-server-files", + "crates/horizon-server", + "crates/horizon-bots", + "crates/horizon-assets", + "crates/horizon-protocol", + "crates/horizon-theme", + "crates/horizon-prepare", + "crates/horizon-telemetry", + "crates/horizon-bench", + "crates/horizon-friends", + "crates/horizon-relay", + "crates/horizon-mod-sdk", + "crates/horizon-mods", + "crates/horizon-mods/tests/guest", + "crates/horizon-mods/tests/ui_guest", + "crates/cargo-horizon-mod", + "crates/horizon-port-pack", + "crates/horizon-shaders", + "crates/horizon-shader-api", + "crates/horizon-release-sign", + "crates/horizon-mod-sdk/examples/coords-hud", + "crates/horizon-mod-sdk/examples/predator-missile", + "crates/horizon-mod-sdk/examples/welcome", + "crates/horizon-mod-sdk/examples/beacons", + "mods/official/fps-overlay", + "mods/official/keystrokes", + "mods/official/minimap", + "mods/official/zoom", + "xtask", + "mods/official/recipes", +] resolver = "2" [workspace.package] From bedba4a3d9a4bf2d3fe5e873ca49f8b6a1009c2c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:08:50 +0100 Subject: [PATCH 117/132] lan_e2e fireworks: count newly red pixels, take the later shots 4 ticks after the burst On playhorizon (frames drawn on the CPU) a screenshot takes ~0.6 s: with a 16-tick wait the later shots came after the sparks' lifetime, and the setup's own red chat lines, gone by then, made the host's count negative. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 03e0e888f..fe76b288b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -2971,13 +2971,15 @@ def check_fireworks(host, guest, out): game('command', command=f'tp @s {x + dx + 0.5} {y} {z + 0.5}') game.raw('look-at', x + 0.5, y + 1.5, z + 3.5) - def red(path): + def reds(path): + """The red pixels' positions, above the hotbar.""" rows, bpp = png_rows(path) - # Exclude the hotbar and chat at the bottom of the view. - return sum(row[i] > 80 and row[i] > 2 * row[i + 1] and row[i] > 2 * row[i + 2] - for row in rows[:len(rows) * 3 // 4] for i in range(0, len(row), bpp)) + return {(y, i) for y, row in enumerate(rows[:len(rows) * 3 // 4]) for i in range(0, len(row), bpp) + if row[i] > 80 and row[i] > 2 * row[i + 1] and row[i] > 2 * row[i + 2]} - baseline = {g.name: red(g.shot(out, 'fireworks-before')) for g in (host, guest)} + # Red where the view had none: the setup's own red chat lines (a fill that changed nothing) are in the + # baseline, and fade out before the later shots, which a plain count difference would take as missing sparks. + baseline = {g.name: reds(g.shot(out, 'fireworks-before')) for g in (host, guest)} before = {g.name: made(g, 'flash') for g in (host, guest)} host('command', command='item replace entity @s weapon.mainhand with minecraft:firework_rocket' '[fireworks={flight_duration:0,explosions:[{shape:"large_ball",colors:[I;16711680],has_trail:true}]}]') @@ -2990,12 +2992,14 @@ def check_fireworks(host, guest, out): break flashes = {g.name: made(g, 'flash') - before[g.name] for g in (host, guest)} assert all(n == 1 for n in flashes.values()), f'configured burst missing or duplicated: {flashes}' - # Capture both views before decoding PNGs: decoding must not consume the sparks' lifetime. + # Capture both views before decoding PNGs: decoding must not consume the sparks' lifetime (48-59 ticks). A + # screenshot takes ~0.6 s where the frame is drawn on the CPU (lavapipe), so the later shots come 4 ticks after + # the burst's, not more: by then the tracked rocket is gone. burst_shots = {g.name: g.shot(out, 'fireworks-burst') for g in (host, guest)} - host.wait(16) + host.wait(4) trail_shots = {g.name: g.shot(out, 'fireworks-trail-fade') for g in (host, guest)} - burst = {name: red(path) - baseline[name] for name, path in burst_shots.items()} - trails = {name: red(path) - baseline[name] for name, path in trail_shots.items()} + burst = {name: len(reds(path) - baseline[name]) for name, path in burst_shots.items()} + trails = {name: len(reds(path) - baseline[name]) for name, path in trail_shots.items()} rockets = {g.name: g('status')['rockets'] for g in (host, guest)} assert not any(rockets.values()), f'exploded rocket remains: {rockets}' assert all(n > 20 for n in burst.values()), f'no red burst: {burst}' From 1af4d0e432dda2c68c295d3eb00411cb316b1d64 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:10:36 +0100 Subject: [PATCH 118/132] parity: a workspace crate's features count through the sources they gate A manifest line defining or turning on a workspace crate's feature no longer makes the manifests count, if every source naming the feature (or one it turns on) changed too, as in a split, where the new crate's files are all new. #2215 (horizon-items with a test-support feature) now selects 209 harnesses instead of 354. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_runner.py | 21 +++++++++++++++ tools/parity.py | 53 +++++++++++++++++++++++++++++++++---- 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 20b3b1efb..39d3cc783 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -440,5 +440,26 @@ class WorkspaceManifestTests(unittest.TestCase): resolver = {"Cargo.toml": '[workspace]\nmembers = ["a"]\nresolver = "3"\n'} self.assertEqual(self.verdict({"Cargo.toml": '[workspace]\nmembers = ["a"]\nresolver = "2"\n'}, resolver), set()) + def test_a_feature_of_a_workspace_crate_counts_through_its_sources(self): + items = '[package]\nname = "horizon-items"\n\n[features]\ntest-support = []\n' + client = self.CLIENT + '\n[dev-dependencies]\nhorizon-items = { path = "../horizon-items", features = ["test-support"] }\n' + head = {"crates/horizon-items/Cargo.toml": items, "crates/horizon-client/Cargo.toml": client, + "crates/horizon-items/src/lib.rs": '#[cfg(feature = "test-support")]\npub fn for_tests() {}\n'} + base = {"crates/horizon-client/Cargo.toml": self.CLIENT} + # The new crate's files are all changed, the code the feature gates with them. + self.assertEqual(self.verdict(base, head), {"crates/horizon-items/Cargo.toml", "crates/horizon-client/Cargo.toml"}) + # Turning on a feature of a crate whose gated code didn't change selects as before. + world = '[package]\nname = "horizon-world"\n\n[features]\nextra = ["more"]\nmore = []\n' + with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)): + Path(temp, "crates/horizon-world/src").mkdir(parents=True) + Path(temp, "crates/horizon-world/Cargo.toml").write_text(world) + Path(temp, "crates/horizon-world/src/lib.rs").write_text('#[cfg(feature = "more")]\nfn x() {}\n') + self.assertFalse(parity.feature_sources_changed("horizon-world", "extra", {"crates/horizon-client/Cargo.toml"})) + self.assertTrue(parity.feature_sources_changed("horizon-world", "extra", {"crates/horizon-world/src/lib.rs"})) + self.assertFalse(parity.feature_sources_changed("horizon-nothing", "extra", set())) + # A feature that reaches an external package counts. + optional = {"crates/horizon-client/Cargo.toml": self.CLIENT + '\n[features]\nfast = ["wgpu/x"]\n'} + self.assertEqual(self.verdict({"crates/horizon-client/Cargo.toml": self.CLIENT}, optional), set()) + def test_without_a_base_everything_counts(self): self.assertEqual(parity.workspace_only_manifests({"Cargo.lock"}, None), set()) diff --git a/tools/parity.py b/tools/parity.py index 76da59b4c..e79da823f 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -1248,9 +1248,14 @@ def trace_main(output, script, arguments): SHARED_INPUTS = {"research-lock.json", "Cargo.lock"} # Manifest sections that say what a crate is and where its targets are, not what it builds with. MANIFEST_SECTION_KEPT = re.compile(r"\[\[?(?:package|lib|bin|example|test|bench|lints|badges)\b[^\]]*\]\]?$") -# A workspace crate named as a dependency (by path, or from the workspace's own table), or listed as a member. -WORKSPACE_LINE = re.compile(r'(?:horizon[\w-]*|cargo-horizon-mod|xtask)\s*=\s*(?:\{[^}]*\b(?:path|workspace)\s*=[^}]*\}|true)' - r'|(?:horizon[\w-]*|cargo-horizon-mod|xtask)\.workspace\s*=\s*true|"crates/[^"]+",?') +WORKSPACE_CRATE = r"(horizon[\w-]*|cargo-horizon-mod|xtask)" +# A workspace crate named as a dependency (by path, or from the workspace's own table) without choosing its features, +# or listed as a member. +WORKSPACE_LINE = re.compile(WORKSPACE_CRATE + r'\s*=\s*(?:\{(?![^}]*\bfeatures\b)[^}]*\b(?:path|workspace)\s*=[^}]*\}|true)' + r'|' + WORKSPACE_CRATE + r'\.workspace\s*=\s*true|"crates/[^"]+",?') +# A workspace crate named as a dependency with some of its features turned on. +WORKSPACE_FEATURES = re.compile(WORKSPACE_CRATE + r'\s*=\s*\{(?=[^}]*\b(?:path|workspace)\s*=)(?![^}]*default-features)' + r'[^}]*\bfeatures\s*=\s*\[([^\]]*)\][^}]*\}') def git_show(base, path): @@ -1263,12 +1268,14 @@ def manifest_lines(text): """A Cargo.toml's lines that decide what is built: (section, line) pairs, without its package's identity and targets, comments, or workspace crates (whose code counts through its own sources).""" lines, section = set(), "" + name = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', text or "", re.M | re.S) for raw in (text or "").splitlines(): line = re.sub(r"\s+", " ", raw.split("#", 1)[0]).strip() if not line: continue if line.startswith("["): - section = line + # A crate's features are its own: the same line in two crates means two things. + section = f"[features] of {name.group(1) if name else '?'}" if line == "[features]" else line continue if MANIFEST_SECTION_KEPT.match(section) or WORKSPACE_LINE.fullmatch(line) or \ section == "[workspace]" and (line.startswith("members =") or line.startswith('"') or line == "]"): @@ -1297,7 +1304,43 @@ def workspace_only_manifests(changed, base): before = set().union(*(manifest_lines(git_show(base, path)) for path in tomls)) if tomls else set() after = set().union(*(manifest_lines((ROOT / path).read_text(encoding="utf-8") if (ROOT / path).exists() else None) for path in tomls)) if tomls else set() - return set(manifests) if before == after else set() + # Workspace crates' features that a changed line defines or turns on: they change what compiles of that crate's + # sources, which is fine only where every source naming them changed too (a split: the crate's files are new). + gated = set() + for section, line in before ^ after: + wanted = WORKSPACE_FEATURES.fullmatch(line) + if wanted: + gated |= {(wanted.group(1), feature) for feature in re.findall(r'"([^"]+)"', wanted.group(2))} + elif section.startswith("[features] of ") and re.fullmatch(r'[\w-]+ = \[(?: ?"[\w-]+",?)*\s*\]', line): + gated.add((section[len("[features] of "):], line.split(" ", 1)[0])) + else: + return set() # an external package, a feature reaching one ("dep:", "crate/feature"), a build setting + return set(manifests) if all(feature_sources_changed(crate, feature, changed) for crate, feature in gated) else set() + + +def feature_sources_changed(crate, feature, changed): + """Whether every Rust source of workspace crate `crate` that names `feature`, or a feature it turns on, is in + changed (False where the crate isn't found).""" + listed = subprocess.run(["git", "ls-files", "*Cargo.toml"], cwd=ROOT, capture_output=True, text=True) + manifests = [ROOT / path for path in listed.stdout.split()] if listed.returncode == 0 else list(ROOT.rglob("Cargo.toml")) + for manifest in manifests: + text = manifest.read_text(encoding="utf-8") if manifest.exists() else "" + if re.search(r'^\[package\][^\[]*?^name\s*=\s*"' + re.escape(crate) + '"', text, re.M | re.S): + break + else: + return False + table = re.search(r"^\[features\]\n(.*?)(?=^\[|\Z)", text, re.M | re.S) + implies = {name: re.findall(r'"([^"]+)"', value) for name, value in + re.findall(r'^([\w-]+)\s*=\s*\[([^\]]*)\]', table.group(1) if table else "", re.M)} + names, todo = set(), [feature] + while todo: + name = todo.pop() + if name not in names: + names.add(name) + todo += [implied for implied in implies.get(name, []) if "/" not in implied and ":" not in implied] + named = re.compile(r'feature\s*=\s*"(?:' + "|".join(map(re.escape, sorted(names))) + r')"') + return all(path.relative_to(ROOT).as_posix() in changed for path in manifest.parent.rglob("*.rs") + if named.search(path.read_text(encoding="utf-8", errors="replace"))) def changed_files(ref): From 844441874a8b77d3a4185024650c293f49674a5d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:11:27 +0100 Subject: [PATCH 119/132] docs: workspace crate features in a split Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 4d20d32be..6cb235c3c 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -64,7 +64,7 @@ A harness can declare, at the top level of its script: ### Which harnesses a change affects -`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. With `--changed`, `Cargo.lock` and `Cargo.toml` changes that only add, remove or move workspace crates (a crate split: no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) don't count: the moved code counts through its sources. #2160's split went from 352 harnesses to 123 this way (its own changes to the runner still select them all). On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. +`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. With `--changed`, `Cargo.lock` and `Cargo.toml` changes that only add, remove or move workspace crates (a crate split: no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) don't count: the moved code counts through its sources. A workspace crate's feature that such a change defines or turns on is allowed only where every source naming it changed too (the new crate's own files). #2160's split went from 352 harnesses to 123 this way (its own changes to the runner still select them all). On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. ## The gate From 1d0d827f3aa2ce9199c17c8872122abf48ebdfd9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:13:35 +0100 Subject: [PATCH 120/132] Launcher: instances, each with its own game folder The game's folder stays the default instance, "Horizon", where it is; imported and registry modpacks are listed as instances in their own folders; new ones go to instances// in the game's folder, empty (the player's options and offline name) or a copy of another (never sessions, logs or telemetry). Names, icons and groups live in the launcher's instances.json, so nothing moves. Play, `play --instance` and MCP play start the selected instance, which follows the launcher's data collection answer and No AI. Crash reports are read from the run's own folder. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 63 ++++ launcher/README.md | 14 +- launcher/src/backend.rs | 10 +- launcher/src/browser/horizon/pack.rs | 2 +- launcher/src/cli.rs | 97 +++++++ launcher/src/instances.rs | 414 +++++++++++++++++++++++++++ launcher/src/instances/tests.rs | 203 +++++++++++++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 18 +- launcher/src/mcp.rs | 7 + launcher/src/modpacks.rs | 6 +- 11 files changed, 823 insertions(+), 12 deletions(-) create mode 100644 launcher/src/instances.rs create mode 100644 launcher/src/instances/tests.rs diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 1e9fb7722..e233cc9a9 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -50,6 +50,7 @@ Start the client. horizon-launcher play +- `--instance`: The instance to play (its name or id; default: the selected one) - `--world`: Open or create this world (a folder under saves) at once - `--creative`: Creative mode for a new world - `--join`: Join a friend's world with its invite code @@ -257,6 +258,68 @@ Upload a benchmark report (docs/benchmark-report.md); it is printed first. MCP: `data_benchmark`, only when the player asks. +## `horizon-launcher instance list` + +The instances, each with its game folder (* = the one Play starts). + + horizon-launcher instance list + +MCP: `instance_list`. + +## `horizon-launcher instance create` + +Make an instance: empty but for your options and name, or a copy of another one's worlds, options and packs. + + horizon-launcher instance create + +- `NAME` +- `--copy`: The instance to copy (its name or id) + +MCP: `instance_create`. + +## `horizon-launcher instance rename` + +Rename an instance (its folder stays). + + horizon-launcher instance rename + +- `INSTANCE` +- `NAME` + +MCP: `instance_rename`. + +## `horizon-launcher instance icon` + +Set an instance's icon: a block or item name from your prepared files (grass_block), a colour (#3fa7d6), or none. + + horizon-launcher instance icon + +- `INSTANCE` +- `ICON` + +MCP: `instance_icon`. + +## `horizon-launcher instance group` + +Put an instance in a sidebar group, or take it out with no group. + + horizon-launcher instance group [GROUP] + +- `INSTANCE` +- `GROUP` + +MCP: `instance_group`. + +## `horizon-launcher instance select` + +Make Play start this instance. + + horizon-launcher instance select + +- `INSTANCE` + +MCP: `instance_select`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). diff --git a/launcher/README.md b/launcher/README.md index 9c6f3a9d9..89df726d1 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -69,6 +69,14 @@ The opening, then Play ([clip](docs/opening.webm)): access controls, one click changes them so friends you share with reach only the server's port (Remove the limit undoes it); custom access controls are never rewritten, the page gives the rule to add instead. Horizon never turns on Funnel. +- **Instances**: separate game folders, each with its own worlds, options and packs. The game's + folder stays the first one, "Horizon", exactly where it was; imported and registry modpacks are + instances too, in their own folders as before; new ones go to `instances//` in the game's + folder, empty but for the player's options and name, or a copy of another instance (never its + sign-in sessions, logs or data collection state). Names, icons (a block or item texture from the + player's prepared files, or a colour) and groups are kept in `instances.json` in the launcher's + data folder, so renaming moves nothing. Every instance follows the launcher's data collection + answer and No AI. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, @@ -152,7 +160,7 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code horizon-launcher install horizon-launcher remove horizon-launcher prepare [--minecraft ] [--version ] - horizon-launcher play [--version ] [--arg ]... start the client; --arg passes an extra argument through (repeatable) + horizon-launcher play [--version ] [--instance ] [--arg ]... start the client; --arg passes an extra argument through (repeatable) horizon-launcher server [--dir ] [--version ] [--accept-eula] horizon-launcher notes [] patch notes as plain text horizon-launcher links the Discord, sponsor and website links @@ -164,6 +172,10 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code horizon-launcher account sign-out horizon-launcher account select play as this account horizon-launcher account offline play without an account + horizon-launcher instance [list] the instances and their game folders (* = Play starts it) + horizon-launcher instance create [--copy ] empty, or a copy of one's worlds, options and packs + horizon-launcher instance rename|icon|group icon: a block or item name, #rrggbb or none + horizon-launcher instance select make Play start it horizon-launcher modpack [list] the imported packs and their coverage horizon-launcher modpack import a .mrpack, CurseForge zip or instance folder horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 55a78193a..dbd54aeee 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1585,9 +1585,10 @@ pub fn newest_crash_report() -> Option { crash_reports_in(&crash_reports_dir()).pop() } -/// The newest crash report written at or after `since` (one from the run that started then). -pub fn crash_report_since(since: std::time::SystemTime) -> Option { - crash_report_in_since(&crash_reports_dir(), since) +/// The newest crash report the game playing in `home` wrote at or after `since` (one from the +/// run that started then). +pub fn crash_report_since(home: &Path, since: std::time::SystemTime) -> Option { + crash_report_in_since(&home.join("crash-reports"), since) } fn crash_report_in_since(dir: &Path, since: std::time::SystemTime) -> Option { @@ -2517,6 +2518,9 @@ pub enum Appearance { #[derive(Default, serde::Serialize, serde::Deserialize)] pub struct Settings { pub selected: Option, + /// The instance Play starts (`instances`), by id. Unset means Horizon, the game's home. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instance: Option, pub minecraft_dir: Option, pub server_dir: Option, /// Unset means on: only a player who turned it off has `false` here. 0.1.1 wrote its diff --git a/launcher/src/browser/horizon/pack.rs b/launcher/src/browser/horizon/pack.rs index 95235a505..2b8e2db9e 100644 --- a/launcher/src/browser/horizon/pack.rs +++ b/launcher/src/browser/horizon/pack.rs @@ -37,7 +37,7 @@ pub fn list() -> Vec { list_in(&packs_dir()) } -fn list_in(dir: &Path) -> Vec { +pub(crate) fn list_in(dir: &Path) -> Vec { let mut packs: Vec = fs::read_dir(dir) .into_iter() .flatten() diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 7d6ff7514..22a850c02 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -3,6 +3,7 @@ use clap::{Parser, Subcommand}; use horizon_launcher::account::{self, Accounts}; use horizon_launcher::backend::{self, Release}; +use horizon_launcher::instances; use std::io::{IsTerminal, Write}; use std::path::PathBuf; use std::process::Command; @@ -155,6 +156,32 @@ enum ModpackCmd { Remove { pack: String }, } +#[derive(Subcommand)] +enum InstanceCmd { + /// The instances, each with its game folder (* = the one Play starts) + List, + /// Make an instance: empty but for your options and name, or a copy of another one's + /// worlds, options and packs + Create { + name: String, + /// The instance to copy (its name or id) + #[arg(long)] + copy: Option, + }, + /// Rename an instance (its folder stays) + Rename { instance: String, name: String }, + /// Set an instance's icon: a block or item name from your prepared files (grass_block), + /// a colour (#3fa7d6), or none + Icon { instance: String, icon: String }, + /// Put an instance in a sidebar group, or take it out with no group + Group { + instance: String, + group: Option, + }, + /// Make Play start this instance + Select { instance: String }, +} + #[derive(Subcommand)] enum ModsCmd { /// What the browser installed (the default) @@ -261,6 +288,9 @@ enum Cmd { Play { #[arg(long)] version: Option, + /// The instance to play (its name or id; default: the selected one) + #[arg(long)] + instance: Option, /// Open or create this world (a folder under saves) at once #[arg(long)] world: Option, @@ -341,6 +371,11 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// Instances: separate game folders, each with its own worlds, options and packs + Instance { + #[command(subcommand)] + action: Option, + }, /// Modpacks: import a Java pack, see its coverage report, port what this computer can and /// play it as its own profile (docs/modpacks.md) Modpack { @@ -606,12 +641,18 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } Cmd::Play { version, + instance, world, creative, join, arg, } => { let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; + let instance = match instance { + Some(name) => instances::find(&name)?, + None => instances::selected(), + }; + instances::apply(&mut cmd, &instance)?; if let Some(code) = join { backend::join_friend(&mut cmd, &code)?; } @@ -784,6 +825,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("Horizon is in the applications menu."); } } + Cmd::Instance { action } => instance(action.unwrap_or(InstanceCmd::List), as_json)?, Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?, Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?, @@ -1337,6 +1379,61 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { Ok(()) } +fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { + use instances::Icon; + let value = |i: &instances::Instance, selected: bool| { + serde_json::json!({ + "id": i.id, "name": i.name, "kind": format!("{:?}", i.kind).to_lowercase(), + "home": i.home, "icon": i.icon, "group": i.group, "selected": selected, + }) + }; + let line = |i: &instances::Instance, selected: bool| { + let mark = if selected { "*" } else { " " }; + let group = i + .group + .as_ref() + .map(|g| format!(" [{g}]")) + .unwrap_or_default(); + println!( + "{mark} {} ({}){group}\n {}", + i.name, + i.id, + i.home.display() + ); + }; + let changed = |i: instances::Instance| { + let selected = i.id == instances::selected().id; + match as_json { + true => json(value(&i, selected)), + false => line(&i, selected), + } + }; + match action { + InstanceCmd::List => { + let selected = instances::selected().id; + let all = instances::list(); + if as_json { + json(all.iter().map(|i| value(i, i.id == selected)).collect()); + } else { + all.iter().for_each(|i| line(i, i.id == selected)); + } + } + InstanceCmd::Create { name, copy } => changed(instances::create(&name, copy.as_deref())?), + InstanceCmd::Rename { instance, name } => { + changed(instances::edit(&instance, |m| m.name = Some(name))?) + } + InstanceCmd::Icon { instance, icon } => { + let icon = (icon != "none").then(|| Icon::parse(&icon)).transpose()?; + changed(instances::edit(&instance, |m| m.icon = icon)?) + } + InstanceCmd::Group { instance, group } => { + changed(instances::edit(&instance, |m| m.group = group)?) + } + InstanceCmd::Select { instance } => changed(instances::select(&instance)?), + } + Ok(()) +} + fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { use horizon_launcher::browser::horizon; use horizon_launcher::modpacks::{self, Imported}; diff --git a/launcher/src/instances.rs b/launcher/src/instances.rs new file mode 100644 index 000000000..d2e74dde1 --- /dev/null +++ b/launcher/src/instances.rs @@ -0,0 +1,414 @@ +//! Instances: separate game folders, each with its own worlds, options and packs. +//! +//! Nothing that exists moves. The game's home (`backend::game_home`) stays the default instance, +//! "Horizon", with its saves and options where they are. Imported modpacks (`ports//home/`) +//! and registry modpacks (`horizon-packs//home/`) are instances too, played from their own +//! folders as before. New instances get `instances//` in the game's home. What the player +//! chooses about an instance (its name, icon, group) is kept in `instances.json` in the +//! launcher's data folder, so renaming one never moves a folder. +use crate::backend; +use crate::browser::horizon::pack as registry_pack; +use crate::modpacks; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// The default instance's id: the game's home itself. +pub const DEFAULT: &str = "horizon"; +const FILE: &str = "instances.json"; +/// Where new instances live, in the game's home. +const OWN: &str = "instances"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// The game's home: what every player had before instances. + Default, + /// Made in the launcher: `instances//`. + Own, + /// An imported Java modpack (modpacks.rs). + Port, + /// A modpack from Horizon's registry. + Pack, +} + +/// What an instance shows in the sidebar: a block or item texture from the player's prepared +/// files (never shipped), or a colour. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Icon { + /// A texture name: `grass_block` (block/ is looked in first, then item/). + Texture(String), + /// `#rrggbb`. + Colour(String), +} + +impl Icon { + /// `#3fa7d6` is a colour; a texture's name is lowercase letters, digits and `_`. + pub fn parse(text: &str) -> Result { + let text = text.trim(); + if let Some(hex) = text.strip_prefix('#') { + if hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit()) { + return Ok(Icon::Colour(format!("#{}", hex.to_ascii_lowercase()))); + } + } else if !text.is_empty() + && text + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') + { + return Ok(Icon::Texture(text.into())); + } + Err(format!( + "{text}: give a block or item name (grass_block) or a colour (#3fa7d6)" + )) + } + + /// The texture's file in prepared resources, if it is a texture they hold. + pub fn texture(&self, resources: &Path) -> Option { + let Icon::Texture(name) = self else { + return None; + }; + let textures = resources.join("assets/minecraft/textures"); + ["block", "item"] + .iter() + .map(|kind| textures.join(kind).join(format!("{name}.png"))) + .find(|p| p.is_file()) + } +} + +/// The player's choices about one instance. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Meta { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option, +} + +/// `instances.json`: each instance's choices, by id. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +struct Store { + #[serde(default)] + instances: BTreeMap, +} + +impl Store { + fn load(data: &Path) -> Store { + fs::read_to_string(data.join(FILE)) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + fn save(&self, data: &Path) -> Result<(), String> { + fs::create_dir_all(data).map_err(|e| format!("{}: {e}", data.display()))?; + let text = serde_json::to_string_pretty(self).unwrap(); + fs::write(data.join(FILE), text).map_err(|e| format!("{FILE}: {e}")) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Instance { + /// `horizon`, an own instance's folder name, `port:` or `pack:`. + pub id: String, + pub name: String, + pub kind: Kind, + /// The folder the pack's tools work in: the game's home for Default and Own instances. + pub work: PathBuf, + /// The game folder it plays in: saves, options.txt, packs. + pub home: PathBuf, + pub icon: Option, + pub group: Option, +} + +/// The instances, by the default game home and the launcher's data folder: Horizon first, then +/// by group and name. +pub fn list() -> Vec { + list_in(&backend::game_home(), &backend::data_dir()) +} + +fn list_in(game_home: &Path, data: &Path) -> Vec { + let store = Store::load(data); + let mut found = vec![( + DEFAULT.to_string(), + "Horizon".to_string(), + Kind::Default, + game_home.to_path_buf(), + game_home.to_path_buf(), + )]; + let mut own: Vec<_> = fs::read_dir(game_home.join(OWN)) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.path().is_dir()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); + own.sort(); + for slug in own { + let dir = game_home.join(OWN).join(&slug); + found.push((slug.clone(), slug, Kind::Own, dir.clone(), dir)); + } + for p in modpacks::list_in(&game_home.join("ports")) { + let home = modpacks::profile_home(&p.work); + found.push(( + format!("port:{}", p.slug), + p.title().into(), + Kind::Port, + p.work, + home, + )); + } + for p in registry_pack::list_in(&game_home.join("horizon-packs")) { + let home = registry_pack::home(&p.work); + found.push((format!("pack:{}", p.id), p.name, Kind::Pack, p.work, home)); + } + let mut out: Vec = found + .into_iter() + .map(|(id, name, kind, work, home)| { + let meta = store.instances.get(&id).cloned().unwrap_or_default(); + Instance { + name: meta.name.unwrap_or(name), + icon: meta.icon, + group: meta.group, + id, + kind, + work, + home, + } + }) + .collect(); + out[1..].sort_by_key(|i| (i.group.clone(), i.name.to_lowercase())); + out +} + +/// The instance an id, a name (any case) or a pack's folder name names. +pub fn find(query: &str) -> Result { + find_in(&list(), query) +} + +fn find_in(all: &[Instance], query: &str) -> Result { + let q = query.trim(); + let bare = |id: &str| id.split_once(':').map_or(id, |(_, rest)| rest).to_string(); + all.iter() + .find(|i| i.id == q) + .or_else(|| all.iter().find(|i| i.name.eq_ignore_ascii_case(q))) + .or_else(|| all.iter().find(|i| bare(&i.id) == q)) + .cloned() + .ok_or_else(|| format!("No instance {q}: horizon-launcher instance list shows them")) +} + +/// The instance Play starts: the one picked in the launcher, else Horizon. +pub fn selected() -> Instance { + let all = list(); + backend::Settings::load() + .instance + .and_then(|id| all.iter().find(|i| i.id == id).cloned()) + .unwrap_or_else(|| all[0].clone()) +} + +pub fn select(query: &str) -> Result { + let instance = find(query)?; + let mut settings = backend::Settings::load(); + settings.instance = (instance.kind != Kind::Default).then(|| instance.id.clone()); + settings.save(); + Ok(instance) +} + +/// What a copy of a game folder leaves out: other instances and packs, logs and crash reports, +/// caches, data collection's state, and sign-in sessions (a session never leaves its folder). +const NOT_COPIED: &[&str] = &[ + OWN, + "ports", + "horizon-packs", + "logs", + "crash-reports", + "sessions", + "telemetry", + "mod-browser", + ".horizon-cache", +]; + +/// Files of the player, not of one instance, that a new instance starts with: the keys and video +/// settings, and the offline name (so the player stays the same player in its worlds). +const PLAYER_FILES: &[&str] = &["options.txt", "horizon-player.txt"]; + +/// Creates an instance named `name`: empty but for the player's options and offline name, or a +/// copy of `from`'s game folder (its worlds, options and packs). Nothing of `from` changes. +pub fn create(name: &str, from: Option<&str>) -> Result { + let from = from.map(find).transpose()?; + create_in( + &backend::game_home(), + &backend::data_dir(), + name, + from.as_ref(), + ) +} + +fn create_in( + game_home: &Path, + data: &Path, + name: &str, + from: Option<&Instance>, +) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err("An instance needs a name.".into()); + } + let all = list_in(game_home, data); + if all.iter().any(|i| i.name.eq_ignore_ascii_case(name)) { + return Err(format!("There is already an instance called {name}.")); + } + if let Some(from) = from.filter(|f| matches!(f.kind, Kind::Port | Kind::Pack)) { + return Err(format!( + "{} plays its pack's mods: import the pack again for a second copy.", + from.name + )); + } + let base = modpacks::slug(name); + let taken = |s: &str| s == DEFAULT || game_home.join(OWN).join(s).exists(); + let slug = (1..) + .map(|n| { + if n == 1 { + base.clone() + } else { + format!("{base}-{n}") + } + }) + .find(|s| !taken(s)) + .unwrap(); + let dir = game_home.join(OWN).join(&slug); + let made = match from { + Some(from) => copy_home(&from.home, &dir), + None => fs::create_dir_all(&dir).and_then(|()| { + for f in PLAYER_FILES { + let own = game_home.join(f); + if own.is_file() { + fs::copy(own, dir.join(f))?; + } + } + Ok(()) + }), + }; + if let Err(e) = made { + let _ = fs::remove_dir_all(&dir); + return Err(format!("Could not make {}: {e}", dir.display())); + } + let mut store = Store::load(data); + let meta = store.instances.entry(slug.clone()).or_default(); + meta.name = (name != slug).then(|| name.to_string()); + meta.icon = from.and_then(|f| f.icon.clone()); + meta.group = from.and_then(|f| f.group.clone()); + store.save(data)?; + find_in(&list_in(game_home, data), &slug) +} + +fn copy_home(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let name = entry.file_name(); + if NOT_COPIED.iter().any(|n| name == *n) { + continue; + } + let path = entry.path(); + if entry.file_type()?.is_dir() { + copy_dir(&path, &to.join(&name))?; + } else { + fs::copy(&path, to.join(&name))?; + } + } + Ok(()) +} + +fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let target = to.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_dir(&entry.path(), &target)?; + } else { + fs::copy(entry.path(), target)?; + } + } + Ok(()) +} + +/// Changes what the player chose about an instance: its name, icon or group. No folder moves. +pub fn edit(query: &str, change: impl FnOnce(&mut Meta)) -> Result { + edit_in(&backend::game_home(), &backend::data_dir(), query, change) +} + +fn edit_in( + game_home: &Path, + data: &Path, + query: &str, + change: impl FnOnce(&mut Meta), +) -> Result { + let all = list_in(game_home, data); + let instance = find_in(&all, query)?; + let mut store = Store::load(data); + let meta = store.instances.entry(instance.id.clone()).or_default(); + change(meta); + meta.name = meta.name.take().map(|n| n.trim().to_string()); + meta.group = meta + .group + .take() + .map(|g| g.trim().to_string()) + .filter(|g| !g.is_empty()); + if let Some(name) = &meta.name { + if name.is_empty() { + return Err("An instance needs a name.".into()); + } + if all + .iter() + .any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name)) + { + return Err(format!("There is already an instance called {name}.")); + } + } + store.save(data)?; + find_in(&list_in(game_home, data), &instance.id) +} + +/// Turns the game's command into this instance: its own game folder, and a pack's mods. The +/// player's answers that hold everywhere follow it in: data collection and No AI as the +/// launcher has them, and options.txt and the offline name when it has none yet. +pub fn apply(cmd: &mut Command, instance: &Instance) -> Result<(), String> { + match instance.kind { + Kind::Default => return Ok(()), + Kind::Own => { + fs::create_dir_all(&instance.home) + .map_err(|e| format!("{}: {e}", instance.home.display()))?; + cmd.current_dir(&instance.home) + .env("HORIZON_HOME", &instance.home); + } + Kind::Port | Kind::Pack => modpacks::apply_profile(cmd, &instance.work)?, + } + follow_player(&backend::game_home(), &instance.home); + Ok(()) +} + +fn follow_player(game_home: &Path, home: &Path) { + for f in PLAYER_FILES { + if !home.join(f).exists() && game_home.join(f).is_file() { + let _ = fs::copy(game_home.join(f), home.join(f)); + } + } + let consent = horizon_telemetry::consent::Consent::path(game_home); + if consent.is_file() { + let to = horizon_telemetry::consent::Consent::path(home); + let _ = fs::create_dir_all(to.parent().unwrap()); + let _ = fs::copy(consent, to); + } + let no_ai = horizon_core::no_ai::is_on(game_home); + if horizon_core::no_ai::is_on(home) != no_ai { + let _ = horizon_core::no_ai::set(home, no_ai); + } +} + +#[cfg(test)] +#[path = "instances/tests.rs"] +mod tests; diff --git a/launcher/src/instances/tests.rs b/launcher/src/instances/tests.rs new file mode 100644 index 000000000..586b620b3 --- /dev/null +++ b/launcher/src/instances/tests.rs @@ -0,0 +1,203 @@ +use super::*; +use std::collections::BTreeMap; + +fn scratch(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!( + "horizon-launcher-instances-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root +} + +fn put(path: &Path, text: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); +} + +/// Every file under `dir`, relative, with its bytes. +fn files(dir: &Path) -> BTreeMap> { + fn walk(root: &Path, dir: &Path, out: &mut BTreeMap>) { + for e in fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + walk(root, &p, out); + } else { + out.insert(p.strip_prefix(root).unwrap().into(), fs::read(&p).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, dir, &mut out); + out +} + +/// A game home as a player has it before instances: worlds, options, packs, a session, an +/// imported modpack and a registry modpack with their own worlds. +fn player_home(home: &Path) { + put(&home.join("saves/World/level.dat"), "world"); + put(&home.join("saves/World/region/r.0.0.mca"), "region"); + put(&home.join("saves/Other/level.dat"), "other"); + put(&home.join("options.txt"), "fov:90\n"); + put(&home.join("horizon-player.txt"), "name:Player123\n"); + put(&home.join("resourcepacks/faithful.zip"), "pack"); + put(&home.join("logs/latest.log"), "log"); + put(&home.join("sessions/a.json"), "token"); + put(&home.join("telemetry/consent.json"), "{}"); + let pack = horizon_port_pack::import::Pack { + name: "Small Pack".into(), + ..Default::default() + }; + put( + &home.join("ports/small-pack/pack.json"), + &serde_json::to_string(&pack).unwrap(), + ); + put( + &home.join("ports/small-pack/home/saves/Modded/level.dat"), + "modded", + ); + put( + &home.join("horizon-packs/cozy/pack.json"), + r#"{"id":"cozy","name":"Cozy","version":"1.0.0","sha256":"00","mods":[]}"#, + ); + put( + &home.join("horizon-packs/cozy/home/saves/Cozy/level.dat"), + "cozy", + ); +} + +#[test] +fn existing_worlds_stay_where_they_are_and_every_folder_becomes_an_instance() { + let root = scratch("migrate"); + let (home, data) = (root.join("horizon"), root.join("launcher")); + player_home(&home); + let before = files(&home); + + // A launcher with instances, on a player's existing folders: no instances.json yet. + let all = list_in(&home, &data); + let ids: Vec<&str> = all.iter().map(|i| i.id.as_str()).collect(); + assert_eq!(ids, [DEFAULT, "pack:cozy", "port:small-pack"]); + assert_eq!(all[0].name, "Horizon"); + assert_eq!(all[0].home, home); + assert_eq!(all[1].home, home.join("horizon-packs/cozy/home")); + assert_eq!(all[2].name, "Small Pack"); + assert_eq!(all[2].home, home.join("ports/small-pack/home")); + + // Everything the player can do with instances, then not one byte of theirs has moved. + let empty = create_in(&home, &data, "Survival", None).unwrap(); + let copy = create_in(&home, &data, "My copy", Some(&all[0])).unwrap(); + edit_in(&home, &data, DEFAULT, |m| m.name = Some("Main".into())).unwrap(); + edit_in(&home, &data, "Small Pack", |m| { + m.icon = Some(Icon::Texture("diamond".into())); + m.group = Some("Modded".into()); + }) + .unwrap(); + let after = files(&home); + for (path, bytes) in &before { + assert_eq!(after.get(path), Some(bytes), "{} changed", path.display()); + } + assert!(!data.join("settings.json").exists()); + + // The empty one has only the player's options and name; the copy has the worlds and + // packs, never the sessions, logs, data collection or other instances. + assert_eq!(empty.home, home.join("instances/survival")); + let empty_files: Vec = files(&empty.home).into_keys().collect(); + assert_eq!( + empty_files, + [PathBuf::from("horizon-player.txt"), "options.txt".into()] + ); + let copied = files(©.home); + for kept in [ + "saves/World/region/r.0.0.mca", + "saves/Other/level.dat", + "resourcepacks/faithful.zip", + ] { + assert_eq!(copied[Path::new(kept)], before[Path::new(kept)]); + } + assert!(copied.keys().all(|p| { + let top = p.components().next().unwrap().as_os_str().to_str().unwrap(); + !NOT_COPIED.contains(&top) + })); + + let all = list_in(&home, &data); + assert_eq!(all[0].name, "Main"); + let port = find_in(&all, "port:small-pack").unwrap(); + assert_eq!(port.group.as_deref(), Some("Modded")); + assert_eq!(port.home, home.join("ports/small-pack/home")); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn names_stay_unique_and_packs_are_not_copied() { + let root = scratch("names"); + let (home, data) = (root.join("horizon"), root.join("launcher")); + player_home(&home); + create_in(&home, &data, "Survival", None).unwrap(); + assert!(create_in(&home, &data, "survival", None).is_err()); + assert!(create_in(&home, &data, " ", None).is_err()); + // Another name with the same folder name gets the next free folder. + let second = create_in(&home, &data, "Survival!", None).unwrap(); + assert_eq!(second.id, "survival-2"); + assert_eq!(second.name, "Survival!"); + assert!(edit_in(&home, &data, "survival-2", |m| m.name = + Some("SURVIVAL".into())) + .is_err()); + let port = find_in(&list_in(&home, &data), "small-pack").unwrap(); + assert!(create_in(&home, &data, "Pack copy", Some(&port)).is_err()); + assert!(!home.join("instances/pack-copy").exists()); + // An empty group is no group. + let grouped = edit_in(&home, &data, "Survival", |m| m.group = Some(" ".into())).unwrap(); + assert_eq!(grouped.group, None); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn an_instance_follows_the_players_answers() { + let root = scratch("follow"); + let (main, own) = (root.join("main"), root.join("own")); + put(&main.join("options.txt"), "fov:90\n"); + put(&main.join("horizon-player.txt"), "name:Player123\n"); + put(&main.join("telemetry/consent.json"), r#"{"version":1}"#); + horizon_core::no_ai::set(&main, true).unwrap(); + put(&own.join("options.txt"), "fov:70\n"); + follow_player(&main, &own); + assert_eq!( + fs::read_to_string(own.join("options.txt")).unwrap(), + "fov:70\n" + ); + assert_eq!( + fs::read_to_string(own.join("horizon-player.txt")).unwrap(), + "name:Player123\n" + ); + assert_eq!( + fs::read_to_string(own.join("telemetry/consent.json")).unwrap(), + r#"{"version":1}"# + ); + assert!(horizon_core::no_ai::is_on(&own)); + horizon_core::no_ai::set(&main, false).unwrap(); + follow_player(&main, &own); + assert!(!horizon_core::no_ai::is_on(&own)); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn icons_are_a_texture_name_or_a_colour() { + assert_eq!(Icon::parse("#3FA7D6"), Ok(Icon::Colour("#3fa7d6".into()))); + assert_eq!( + Icon::parse("grass_block"), + Ok(Icon::Texture("grass_block".into())) + ); + for bad in ["#12345", "../x", "Grass", "", "#zzzzzz"] { + assert!(Icon::parse(bad).is_err(), "{bad}"); + } + let root = scratch("icon"); + put( + &root.join("assets/minecraft/textures/item/diamond.png"), + "png", + ); + let diamond = Icon::Texture("diamond".into()).texture(&root).unwrap(); + assert!(diamond.ends_with("item/diamond.png")); + assert_eq!(Icon::Texture("stone".into()).texture(&root), None); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 3cba3ed10..f1779c332 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -7,6 +7,7 @@ pub mod desktop; #[cfg(unix)] pub mod game_app; pub mod heads; +pub mod instances; pub mod modpacks; pub mod mojang; pub mod process; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 7cc6d0ccd..4003f5725 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -33,6 +33,7 @@ use gpui::{ }; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; +use horizon_launcher::instances; use horizon_launcher::telemetry; use scrollbar::Scrollbar; use std::borrow::Cow; @@ -535,13 +536,16 @@ impl Launcher { Err(e) => self.client_error = Some(format!("Playing offline: {e}")), } self.accounts = Accounts::load(); - if let Some(work) = self.starting_pack.take() { - if let Err(e) = + // A pack's Play button plays that pack; Play plays the selected instance. + let profile = match self.starting_pack.take() { + Some(work) => { horizon_launcher::modpacks::apply_profile(&mut cmd, &work) - { - self.client_error = Some(e); - continue; } + None => instances::apply(&mut cmd, &instances::selected()), + }; + if let Err(e) = profile { + self.client_error = Some(e); + continue; } if let Some(code) = self.joining.take() { if let Err(e) = backend::join_friend(&mut cmd, &code) { @@ -668,10 +672,12 @@ impl Launcher { } Job::Client => { self.client = None; + // The run's own game folder: an instance's or a pack's keeps its reports. + let home = self.client_home.clone().unwrap_or_else(backend::game_home); let report = self .client_started .take() - .and_then(backend::crash_report_since); + .and_then(|since| backend::crash_report_since(&home, since)); if error.is_some() && report.is_none() && self.switched_to_dx12() { self.client_error = Some( "Horizon's Vulkan renderer crashed while starting on this \ diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 8aff5aa13..cb4636429 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -6,6 +6,7 @@ use crate::cli_tools; use crate::game_tools::{self, GameTools}; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Logged}; +use horizon_launcher::instances; use serde_json::{json, Value}; use std::io::{BufRead, Write}; use std::path::PathBuf; @@ -29,6 +30,7 @@ fn session_tools() -> Value { json!([ { "name": "play", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world. CLI: horizon-launcher play", "inputSchema": { "type": "object", "properties": { "version": version, + "instance": { "type": "string", "description": "The instance to play, by name or id (instance_list). Default: the selected one." }, "world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." }, "creative": { "type": "boolean", "description": "Creative mode for a new world." }, "join": { "type": "string", "description": "Join a friend's world with its invite code. Only when the player asks." }, @@ -68,6 +70,11 @@ impl Session { } let tag = backend::resolve_version(arg_str(args, "version"))?; let mut cmd = backend::client(&tag)?; + let instance = match arg_str(args, "instance") { + Some(name) => instances::find(name)?, + None => instances::selected(), + }; + instances::apply(&mut cmd, &instance)?; cmd.args(game_tools::control_args()); if let Some(world) = arg_str(args, "world") { cmd.arg("--world").arg(world); diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs index acd8241a5..3b8e9451f 100644 --- a/launcher/src/modpacks.rs +++ b/launcher/src/modpacks.rs @@ -135,7 +135,11 @@ pub fn load(work: &Path) -> Result { /// Every imported pack, by name. pub fn list() -> Vec { - let mut packs: Vec = fs::read_dir(ports_dir()) + list_in(&ports_dir()) +} + +pub(crate) fn list_in(ports: &Path) -> Vec { + let mut packs: Vec = fs::read_dir(ports) .into_iter() .flatten() .flatten() From 6087b01f667ec9ca453b95fee6ae2658eb67fc9c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:21:06 +0100 Subject: [PATCH 121/132] test_friends: put the guest on cleared, flat ground before it walks Since #2501 a player new to the world spawns at a random free spot near the world spawn, as vanilla's PlayerSpawnFinder does. The guest often stood against a hill, so walking forward moved it less than a block, or terrain hid the block it had to aim at: friends_integration failed on every run on the Mac mini. The host now clears a floor beside itself and teleports the guest there before the movement checks, and the block check waits for the guest to stand still. Co-Authored-By: Claude Opus 5.5 --- tools/test_friends.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tools/test_friends.py b/tools/test_friends.py index fd3d626a9..763b0b220 100644 --- a/tools/test_friends.py +++ b/tools/test_friends.py @@ -137,6 +137,24 @@ def guest_pos(host, name): return next(g['position'] for g in guests if g['name'] == name) +def open_ground(host, guest, name): + """Puts the guest on a cleared, flat floor beside the host and returns where it stands. + + A player new to the world spawns at a random free spot near the world spawn, as in vanilla + (`PlayerSpawnFinder`), often against a hill: walking and aiming need known, open ground. + Commands, not the control socket: the server has the last word on where the guest stands. + """ + hp = host('status')['player']['position'] + x, y, z = math.floor(hp[0]) - 6, math.floor(hp[1]), math.floor(hp[2]) + host(f'command fill {x - 2} {y - 1} {z - 2} {x + 4} {y - 1} {z + 8} minecraft:stone') + host(f'command fill {x - 2} {y} {z - 2} {x + 4} {y + 3} {z + 8} minecraft:air') + spot = [x + 0.5, float(y), z + 0.5] + host(f'command tp {name} {spot[0]} {spot[1]} {spot[2]} 0 0') + guest.wait('status', lambda v: math.dist(v['player']['position'], spot) < 0.01 and v['player']['on_ground'], 20, + 'the guest on its ground') + return spot + + def play_together(host, guest, name, round_index): """Chat, movement and blocks seen from both sides.""" host.wait('lan status', lambda v: any(g['name'] == name and g['placed'] for g in v['guests']), 60, @@ -150,6 +168,7 @@ def play_together(host, guest, name, round_index): guest.wait('status', lambda v: any(f'hello from the host {round_index}' in l for l in v['server']['chat']), 30, 'host chat on the guest') # The guest walks; the host sees it move. + open_ground(host, guest, name) before = guest_pos(host, name) guest('look 0 0') guest('key w down') @@ -167,7 +186,8 @@ def play_together(host, guest, name, round_index): guest.wait('status', lambda v: any(math.dist(p, target) < 0.6 for p in v['server']['player_positions']), 20, 'host movement on the guest') # A block the host places, which the guest sees and then breaks. - gp = guest('status')['player']['position'] + gp = guest.wait('status', lambda v: v['player']['on_ground'] and math.hypot(v['player']['velocity'][0], + v['player']['velocity'][2]) < 1e-3, 10, 'the guest standing still')['player']['position'] feet = [math.floor(gp[0]), math.floor(gp[1]), math.floor(gp[2])] block = [feet[0] + 2, feet[1] + 1, feet[2]] # Clear the line of sight (the test terrain has hills), then the block at eye level. From a76456b036df5f1e654dec863a8b5116c6e945e2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:21:56 +0100 Subject: [PATCH 122/132] Launcher: instances in the sidebar, and a dialog to make and edit them The sidebar lists the instances by group with their icons (a texture from the player's prepared files, drawn as pixels, or a colour); clicking one selects it for Play. + makes one, empty or a copy of the selected one (copied in the background); Home's Instance row edits its name, group and icon, copies it, and opens its folder. The dialog's name and group are the launcher's shared text fields. Co-Authored-By: Claude Opus 5.5 --- launcher/README.md | 4 +- launcher/src/instances_page.rs | 583 +++++++++++++++++++++++++++++++++ launcher/src/main.rs | 90 ++--- launcher/src/modpacks_page.rs | 1 + launcher/src/servers_page.rs | 14 +- 5 files changed, 621 insertions(+), 71 deletions(-) create mode 100644 launcher/src/instances_page.rs diff --git a/launcher/README.md b/launcher/README.md index 89df726d1..50ca6829c 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -76,7 +76,9 @@ The opening, then Play ([clip](docs/opening.webm)): sign-in sessions, logs or data collection state). Names, icons (a block or item texture from the player's prepared files, or a colour) and groups are kept in `instances.json` in the launcher's data folder, so renaming moves nothing. Every instance follows the launcher's data collection - answer and No AI. + answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by + group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and + Open folder. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, diff --git a/launcher/src/instances_page.rs b/launcher/src/instances_page.rs new file mode 100644 index 000000000..ce6c1d42e --- /dev/null +++ b/launcher/src/instances_page.rs @@ -0,0 +1,583 @@ +//! Instances in the window (`horizon_launcher::instances`): the sidebar's list, by group, and the +//! dialog that makes one (empty, or a copy of the selected one) or changes its name, group and +//! icon. +use super::*; +use gpui::RenderImage; +use horizon_launcher::instances::{self, Icon, Instance, Kind as InstanceKind}; +use servers_page::Field; +use std::collections::HashMap; +use std::sync::Arc; + +/// Textures offered as icons, when the player's prepared files hold them: block faces and items +/// that read well at sidebar size. +const TEXTURES: [&str; 24] = [ + "grass_block_side", + "oak_planks", + "oak_log", + "cobblestone", + "bricks", + "bookshelf", + "crafting_table_front", + "tnt_side", + "sand", + "snow", + "ice", + "obsidian", + "netherrack", + "end_stone", + "glowstone", + "diamond_ore", + "diamond", + "emerald", + "apple", + "ender_pearl", + "iron_pickaxe", + "diamond_sword", + "bow", + "book", +]; + +/// Colours offered as icons: Horizon's accent and a few that sit beside it in both themes. +const COLOURS: [&str; 8] = [ + "#5b3fd6", "#3f7fd6", "#2f9e8f", "#4f9e2f", "#c9a227", "#d9732f", "#c4405a", "#7d7591", +]; + +/// The dialog: a new instance (`editing` None) or one being changed. Its name and group are the +/// text fields `Field::InstanceName` and `Field::InstanceGroup`. +pub(super) struct InstanceDialog { + editing: Option, + /// A new instance copies the selected one's worlds, options and packs. + copy: bool, + icon: Option, + error: Option, + busy: bool, +} + +/// The instances and their icons as images, kept between frames. +#[derive(Default)] +pub(super) struct Instances { + pub(super) list: Vec, + pub(super) dialog: Option, + icons: HashMap<(String, u32), Option>>, +} + +impl Launcher { + pub(super) fn reload_instances(&mut self) { + self.instances.list = instances::list(); + } + + /// The instance Play starts. + pub(super) fn selected_instance(&self) -> Option<&Instance> { + let id = self + .settings + .instance + .as_deref() + .unwrap_or(instances::DEFAULT); + let list = &self.instances.list; + list.iter().find(|i| i.id == id).or(list.first()) + } + + fn select_instance(&mut self, instance: &Instance) { + self.settings.instance = + (instance.kind != InstanceKind::Default).then(|| instance.id.clone()); + self.settings.save(); + } + + /// A texture from the selected version's prepared files, its first frame, drawn as pixels. + fn texture_image(&mut self, name: &str, size: f32) -> Option> { + let tag = self.selected().filter(|t| backend::is_prepared(t))?.clone(); + let scale = self.scale; + self.instances + .icons + .entry((name.to_string(), (size * scale) as u32)) + .or_insert_with(|| { + let path = Icon::Texture(name.into()).texture(&backend::resources(&tag))?; + let png = image::open(path).ok()?.to_rgba8(); + let w = png.width() as usize; + // An animated texture is its frames one under another: the first is square. + let texels: Vec<[u8; 4]> = png.pixels().take(w * w).map(|p| p.0).collect(); + Some(art::bake(&texels, w, w, size / w as f32, scale)) + }) + .clone() + } + + /// An instance's icon, `size` points square. + pub(super) fn instance_icon(&mut self, instance: &Instance, size: f32) -> AnyElement { + let t = self.theme; + let framed = |d: Div| { + d.flex() + .flex_none() + .items_center() + .justify_center() + .size(px(size)) + .border_2() + .border_color(t.outline) + }; + match &instance.icon { + Some(Icon::Colour(hex)) => { + let rgb = u32::from_str_radix(&hex[1..], 16).unwrap_or(0); + return framed(div().bg(gpui::rgb(rgb))) + .child( + blocks::pixel((size * 0.42).round(), FontWeight::BOLD) + .text_color(gpui::white()) + .child(initial(&instance.name)), + ) + .into_any_element(); + } + Some(Icon::Texture(name)) => { + if let Some(image) = self.texture_image(name, size - 8.) { + return framed(div().bg(t.well)) + .child(gpui::img(image).size(px(size - 8.))) + .into_any_element(); + } + } + None if instance.kind == InstanceKind::Default => { + if let Some(grass) = self.vanilla_icon() { + return div() + .flex() + .items_center() + .justify_center() + .size(px(size)) + .child(gpui::img(grass).size(px(size - 4.))) + .into_any_element(); + } + } + None => {} + } + blocks::slot(None, &instance.name, size, &t).into_any_element() + } + + /// The sidebar's instances: those without a group, then each group under its name. + pub(super) fn instance_items( + &mut self, + heading: impl Fn(String) -> Div, + cx: &mut Context, + ) -> Vec { + let t = self.theme; + let tag = self.selected().cloned(); + let prepared = tag.as_deref().is_some_and(backend::is_prepared); + let status = if tag.is_none() { + "No version installed" + } else if prepared { + "Ready" + } else { + "Needs preparing" + }; + let selected = self.selected_instance().map(|i| i.id.clone()); + let on_packs = self.page == Page::Mods && self.mods.on_modpacks(); + let mut out = Vec::new(); + let mut group = None; + for i in self.instances.list.clone() { + if i.group != group { + group = i.group.clone(); + if let Some(g) = &group { + out.push(heading(g.to_uppercase()).into_any_element()); + } + } + let (open, sub) = match i.kind { + InstanceKind::Default | InstanceKind::Own => ( + self.page == Page::Play && selected.as_ref() == Some(&i.id), + status.to_string(), + ), + InstanceKind::Port => { + let slug = &i.id["port:".len()..]; + let summary = self.packs.iter().find(|p| p.slug == slug); + ( + on_packs && self.pack_open.as_deref() == Some(slug), + summary.map_or_else(|| "Modpack".into(), |p| p.summary()), + ) + } + InstanceKind::Pack => (false, "From Horizon's registry".into()), + }; + let dot = matches!(i.kind, InstanceKind::Default | InstanceKind::Own).then(|| { + div() + .absolute() + .left(px(42.)) + .top(px(42.)) + .size(px(10.)) + .bg(if prepared { t.success } else { t.warn }) + .border_2() + .border_color(t.side) + }); + let icon = self.instance_icon(&i, 44.); + let clicked = i.clone(); + out.push( + blocks::side_item(format!("side-instance-{}", i.id).into(), open, &t) + .child(icon) + .children(dot) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child( + blocks::pixel(15., FontWeight::MEDIUM) + .text_color(t.ink) + .truncate() + .child(i.name.clone()), + ) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .truncate() + .child(sub), + ), + ) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + match clicked.kind { + InstanceKind::Default | InstanceKind::Own => { + this.select_instance(&clicked); + this.go(Page::Play); + } + InstanceKind::Port => { + this.show_modpack(Some(clicked.id["port:".len()..].into())) + } + InstanceKind::Pack => this.show_modpack(None), + } + cx.notify(); + })) + .into_any_element(), + ); + } + out + } + + /// Opens the dialog for a new instance, or for changing `editing`. + pub(super) fn open_instance_dialog(&mut self, editing: Option) { + let (name, group) = editing + .as_ref() + .map(|i| (i.name.clone(), i.group.clone().unwrap_or_default())) + .unwrap_or_default(); + *self.servers.text(Field::InstanceName) = name; + *self.servers.text(Field::InstanceGroup) = group; + self.servers.focus_soon = Some(Field::InstanceName); + self.instances.dialog = Some(InstanceDialog { + icon: editing.as_ref().and_then(|i| i.icon.clone()), + editing: editing.map(|i| i.id), + copy: false, + error: None, + busy: false, + }); + } + + /// Escape closes the dialog. Whether it did. + pub(super) fn instance_escape(&mut self) -> bool { + if self.instances.dialog.as_ref().is_some_and(|d| !d.busy) { + self.instances.dialog = None; + return true; + } + false + } + + /// Creates or changes the instance as the dialog says. A copy can be gigabytes of worlds, so + /// the work runs in the background. + pub(super) fn save_instance(&mut self, cx: &mut Context) { + let selected = self.selected_instance().map(|i| i.id.clone()); + let name = self.servers.value(Field::InstanceName).trim().to_string(); + let group = Some(self.servers.value(Field::InstanceGroup).to_string()); + let Some(d) = self.instances.dialog.as_mut().filter(|d| !d.busy) else { + return; + }; + let icon = d.icon.clone(); + let editing = d.editing.clone(); + let copy = selected.filter(|_| d.copy); + d.busy = true; + d.error = None; + let task = cx.background_executor().spawn(async move { + let id = match editing { + Some(id) => id, + None => instances::create(&name, copy.as_deref())?.id, + }; + instances::edit(&id, |m| { + m.name = Some(name); + m.group = group; + m.icon = icon; + }) + }); + cx.spawn(async move |this, cx| { + let result = task.await; + let _ = this.update(cx, |this, cx| { + match result { + Ok(instance) => { + this.instances.dialog = None; + this.select_instance(&instance); + this.reload_instances(); + if matches!(instance.kind, InstanceKind::Default | InstanceKind::Own) { + this.go(Page::Play); + } + } + Err(e) => { + if let Some(d) = &mut this.instances.dialog { + d.busy = false; + d.error = Some(e); + } + } + } + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn instance_dialog(&mut self, cx: &mut Context) -> Option> { + let t = self.theme; + let d = self.instances.dialog.as_ref()?; + let (editing, copy, icon, error, busy) = ( + d.editing.is_some(), + d.copy, + d.icon.clone(), + d.error.clone(), + d.busy, + ); + let from = self + .selected_instance() + .map_or_else(|| "Horizon".into(), |i| i.name.clone()); + let row = |label: &'static str, control: AnyElement| { + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(caps(label).text_color(t.muted)) + .child(control) + }; + let mut body = div() + .flex() + .flex_col() + .gap(px(20.)) + .p(px(24.)) + .child( + blocks::pixel(22., FontWeight::MEDIUM) + .text_color(t.ink) + .child(if editing { + "Edit instance" + } else { + "New instance" + }), + ) + .child(row( + "Name", + self.field(Field::InstanceName, "My instance", 400., cx) + .into_any_element(), + )); + if !editing { + let weak = cx.entity().downgrade(); + body = body.child(row( + "Start from", + segments( + "instance-from", + &[(false, "Empty"), (true, "A copy of the selected one")], + copy, + &t, + move |copy, _, cx| { + let _ = weak.update(cx, |this, cx| { + if let Some(d) = &mut this.instances.dialog { + d.copy = copy; + } + cx.notify(); + }); + }, + ) + .into_any_element(), + )); + body = body.child(text(theme::CAPTION).text_color(t.muted).child(if copy { + format!("{from}'s worlds, options and packs are copied; {from} stays as it is.") + } else { + "Its own worlds and packs; your options and player name come along.".to_string() + })); + } + body = body.child(row( + "Group", + self.field(Field::InstanceGroup, "No group", 400., cx) + .into_any_element(), + )); + let mut tiles = div().flex().flex_wrap().gap(px(6.)); + let tile = |id: String, chosen: bool| { + div() + .id(SharedString::from(id)) + .flex() + .items_center() + .justify_center() + .size(px(40.)) + .border_2() + .border_color(if chosen { t.accent } else { t.rule }) + .cursor_pointer() + .hover(move |s| s.border_color(t.outline)) + }; + let none = icon.is_none(); + tiles = tiles.child( + tile("instance-icon-none".into(), none) + .child(text(theme::MICRO).text_color(t.muted).child("NONE")) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some(d) = &mut this.instances.dialog { + d.icon = None; + } + cx.notify(); + })), + ); + for name in TEXTURES { + let Some(image) = self.texture_image(name, 28.) else { + continue; + }; + let chosen = icon == Some(Icon::Texture(name.into())); + tiles = tiles.child( + tile(format!("instance-icon-{name}"), chosen) + .bg(t.well) + .child(gpui::img(image).size(px(28.))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(d) = &mut this.instances.dialog { + d.icon = Some(Icon::Texture(name.into())); + } + cx.notify(); + })), + ); + } + for hex in COLOURS { + let chosen = icon == Some(Icon::Colour(hex.into())); + let rgb = u32::from_str_radix(&hex[1..], 16).unwrap_or(0); + tiles = tiles.child( + tile(format!("instance-icon-{hex}"), chosen) + .child(div().size(px(28.)).bg(gpui::rgb(rgb))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(d) = &mut this.instances.dialog { + d.icon = Some(Icon::Colour(hex.into())); + } + cx.notify(); + })), + ); + } + body = body.child(row("Icon", tiles.into_any_element())); + if self.selected().is_none_or(|t| !backend::is_prepared(t)) { + body = body.child( + text(theme::CAPTION) + .text_color(t.muted) + .child("Block and item icons come from your prepared game files: prepare a version to see them."), + ); + } + if let Some(e) = error { + body = body.child(text(theme::CAPTION).text_color(t.danger).child(e)); + } + let cancel = button("instance-cancel", "Cancel", Kind::Secondary, &t); + let label = match (editing, busy, copy) { + (_, true, true) => "Copying…", + (true, false, _) => "Save", + _ => "Create", + }; + let save = button("instance-save", label, Kind::Primary, &t); + // A modpack becomes an instance by being imported, on the Mods page. + let import = (!editing && !busy).then(|| { + button("instance-import", "Import a modpack…", Kind::Ghost, &t) + .mr_auto() + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.instances.dialog = None; + this.show_modpack(None); + cx.notify(); + })) + }); + let foot = div() + .flex() + .justify_end() + .gap(px(8.)) + .px(px(24.)) + .py(px(16.)) + .border_t_1() + .border_color(t.rule) + .children(import); + let foot = if busy { + foot.child(disabled(cancel)).child(disabled(save)) + } else { + foot.child(cancel.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.instances.dialog = None; + cx.notify(); + }))) + .child(save.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.save_instance(cx); + cx.notify(); + }))) + }; + let card = plate(&t) + .flex() + .flex_col() + .w_full() + .max_w(px(560.)) + .bg(t.page) + .border_1() + .border_color(t.rule) + .child(body) + .child(foot); + Some( + div() + .id("instance-dialog") + .absolute() + .top_0() + .left_0() + .size_full() + .flex() + .flex_col() + .items_center() + .px(px(32.)) + .py(px(24.)) + .bg(t.page.opacity(0.92)) + .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) + .occlude() + .child(card), + ) + } + + /// The Play page's row for the selected instance: its folder, and changing or copying it. + pub(super) fn instance_row(&mut self, n: usize, cx: &mut Context) -> Option
{ + let t = self.theme; + let instance = self.selected_instance()?.clone(); + let (home, edit, name) = ( + instance.home.clone(), + instance.clone(), + instance.name.clone(), + ); + let actions = div() + .flex() + .gap(px(8.)) + .child( + button("instance-edit", "Edit…", Kind::Ghost, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.open_instance_dialog(Some(edit.clone())); + cx.notify(); + }, + )), + ) + .child( + button("instance-copy", "Copy…", Kind::Ghost, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.open_instance_dialog(None); + *this.servers.text(Field::InstanceName) = format!("{name} copy"); + if let Some(d) = &mut this.instances.dialog { + d.copy = true; + } + cx.notify(); + }, + )), + ) + .child( + button("instance-folder", "Open folder", Kind::Ghost, &t).on_click( + move |_, _, cx| { + let _ = std::fs::create_dir_all(&home); + cx.open_with_system(&home); + }, + ), + ); + Some(index_row( + n, + "Instance", + Some(div().child(instance.name.clone()).into_any_element()), + Some(actions.into_any_element()), + &t, + )) + } +} + +/// The first letter or digit of a name, for an icon without a picture. +fn initial(name: &str) -> String { + name.chars() + .find(|c| c.is_alphanumeric()) + .unwrap_or('?') + .to_uppercase() + .to_string() +} diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 4003f5725..b9f556d69 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -12,6 +12,7 @@ mod collection; mod console; mod cull; mod game_tools; +mod instances_page; mod internet; mod markdown; mod mcp; @@ -223,6 +224,8 @@ struct Launcher { starting_pack: Option, /// The Mods page: the browser's search, installs and updates (`mods_page.rs`). mods: mods_page::Mods, + /// The instances, for the sidebar and Play, and their dialog (`instances_page.rs`). + instances: instances_page::Instances, /// The name the game made up for an offline player (`horizon-player.txt`), for the top bar. offline_name: Option, /// The player's servers, for the sidebar until the Servers page has read them. @@ -379,11 +382,13 @@ impl Launcher { pack_error: None, starting_pack: None, mods: mods_page::Mods::new(cx), + instances: instances_page::Instances::default(), offline_name: offline_name(), side_servers: horizon_launcher::servers::list(), art: art::Art::default(), scale: window.scale_factor(), }; + this.reload_instances(); if this.bench.is_some() { this.perf.keep_local_log(false); } @@ -1575,7 +1580,7 @@ impl Launcher { fn sidebar(&mut self, cx: &mut Context) -> Stateful
{ let t = self.theme; self.load_packs(); - let heading = |label: &'static str| { + let heading = |label: String| { div() .flex() .items_center() @@ -1606,7 +1611,7 @@ impl Launcher { .border_2() .border_color(t.side) }; - let add = keyboard(div().id("add-pack"), &t) + let add = keyboard(div().id("add-instance"), &t) .flex() .items_center() .justify_center() @@ -1618,79 +1623,23 @@ impl Launcher { .hover(move |s| s.bg(t.raised)) .child(blocks::icon("plus", 14., t.ink_soft)) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.show_modpack(None); + this.open_instance_dialog(None); cx.notify(); })); - let mut list = div() + let list = div() .flex() .flex_col() .gap(px(4.)) - .child(heading("INSTANCES").child(add)); - // Horizon itself, with a grass block from the player's own prepared files. - let tag = self.selected().cloned(); - let prepared = tag.as_deref().is_some_and(backend::is_prepared); - let grass = self.vanilla_icon(); - let on_play = self.page == Page::Play; - list = list.child( - blocks::side_item("side-horizon".into(), on_play, &t) - .child(match grass { - Some(g) => div() - .flex() - .items_center() - .justify_center() - .size(px(44.)) - .child(gpui::img(g).size(px(40.))), - None => blocks::slot(None, "Horizon", 44., &t), - }) - .child(dot(if prepared { t.success } else { t.warn })) - .child( - div() - .flex() - .flex_col() - .min_w_0() - .child(title("Horizon".into())) - .child(sub(if tag.is_none() { - "No version installed" - } else if prepared { - "Vanilla · ready" - } else { - "Needs preparing" - } - .into())), - ) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.go(Page::Play); - cx.notify(); - })), - ); - let on_packs = self.page == Page::Mods && self.mods.on_modpacks(); - for p in &self.packs { - let slug = p.slug.clone(); - let open = on_packs && self.pack_open.as_ref() == Some(&p.slug); - list = list.child( - blocks::side_item(format!("side-pack-{slug}").into(), open, &t) - .child(blocks::slot(None, p.title(), 44., &t)) - .child( - div() - .flex() - .flex_col() - .min_w_0() - .child(title(p.title().to_string())) - .child(sub(p.summary())), - ) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.show_modpack(Some(slug.clone())); - cx.notify(); - })), - ); - } + .child(heading("INSTANCES".into()).child(add)) + .children(self.instance_items(heading, cx)); let servers: Vec<_> = self .servers .sidebar_list() .map(<[_]>::to_vec) .unwrap_or_else(|| self.side_servers.clone()); + let mut list = list; if !servers.is_empty() { - list = list.child(heading("SERVERS")); + list = list.child(heading("SERVERS".into())); } for e in servers { let up = self.servers.is_up(&e.dir); @@ -2074,15 +2023,16 @@ impl Launcher { .flex() .flex_col() .child(section_title("Ready to play", "check", &t).mb(px(12.))) + .children(self.instance_row(1, cx)) .child(index_row( - 1, + 2, "Resources", Some(div().child(resources_value).into_any_element()), Some(prepare.into_any_element()), &t, )) .child(index_row( - 2, + 3, "Minecraft folder", Some(minecraft), Some( @@ -2098,7 +2048,7 @@ impl Launcher { // offline, in a build that can sign in. if self.accounts.selected().is_none() && account::client_id().is_some() { rows = rows.child(index_row( - 4, + 5, "Playing offline", Some( div() @@ -3064,7 +3014,7 @@ impl Launcher { join = disabled(join); } index_row( - 3, + 4, "Join a friend", Some( div() @@ -3523,6 +3473,7 @@ impl Render for Launcher { } } "escape" if this.servers_escape() => {} + "escape" if this.instance_escape() => {} _ => return, } cx.stop_propagation(); @@ -3583,6 +3534,9 @@ impl Render for Launcher { root = root.child(dialog); } } + if let Some(dialog) = self.instance_dialog(cx) { + root = root.child(dialog); + } if self.asking_consent() { root = root.child(self.consent_screen(cx)); } diff --git a/launcher/src/modpacks_page.rs b/launcher/src/modpacks_page.rs index 25df3966f..2f10b2773 100644 --- a/launcher/src/modpacks_page.rs +++ b/launcher/src/modpacks_page.rs @@ -132,6 +132,7 @@ impl Launcher { self.mods.report_list.reset(); self.packs = modpacks::list(); self.registry_packs = horizon_pack::list(); + self.reload_instances(); if self.pack_open.is_none() { self.pack_open = self.packs.first().map(|p| p.slug.clone()); } diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index 0a5618768..0237f34f9 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -32,10 +32,13 @@ pub(super) enum Field { Port, Token, Email, + /// The instance dialog's (`instances_page.rs`). + InstanceName, + InstanceGroup, } impl Field { - const ALL: [Field; 9] = [ + const ALL: [Field; 11] = [ Field::Name, Field::Seed, Field::Players, @@ -45,6 +48,8 @@ impl Field { Field::Port, Field::Token, Field::Email, + Field::InstanceName, + Field::InstanceGroup, ]; } @@ -163,7 +168,7 @@ pub(super) struct Servers { focus: HashMap, focused: Option, /// The field to put the keyboard in on the next frame. - focus_soon: Option, + pub(super) focus_soon: Option, /// A suggested value shown selected: the first key typed replaces it. selected: Option, /// A field whose value was refused, and why: shown under it until it's edited. @@ -961,11 +966,15 @@ impl Launcher { command, ); match typed { + Key::Enter if matches!(f, Field::InstanceName | Field::InstanceGroup) => { + this.save_instance(cx) + } Key::Enter => this.field_enter(f), Key::Escape => { if this.servers.create.is_some() && !this.servers.creating { this.servers.create = None; } + this.instance_escape(); window.blur(); } Key::Paste => { @@ -1017,6 +1026,7 @@ impl Launcher { Field::Port => self.save_port(), Field::Token => self.save_token(), Field::Email => self.invite_friend(), + Field::InstanceName | Field::InstanceGroup => {} } } From 90f27552459e7868afad4a8527149eb790db6c0c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:25:31 +0100 Subject: [PATCH 123/132] Launcher: a Horizon version per instance An instance plays the launcher's version, which follows updates, unless it is kept on another installed one: the Play page's picker pins the selected instance (picking the version marked "follows updates" unpins it), and `instance version ` does it from the CLI. play, `play --instance` and MCP play use the pin; a pack's Play uses its instance's. The sidebar shows a pinned instance's version, or that it is not installed. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 10 +++++++++ launcher/README.md | 5 ++++- launcher/src/cli.rs | 19 +++++++++++++++-- launcher/src/instances.rs | 24 +++++++++++++++++++++ launcher/src/instances/tests.rs | 23 ++++++++++++++++++++ launcher/src/instances_page.rs | 38 ++++++++++++++++++++++++--------- launcher/src/main.rs | 32 +++++++++++++++++++++------ launcher/src/mcp.rs | 6 +++--- launcher/src/modpacks_page.rs | 8 ++++++- 9 files changed, 142 insertions(+), 23 deletions(-) diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index e233cc9a9..6faaeed74 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -320,6 +320,16 @@ Make Play start this instance. MCP: `instance_select`. +## `horizon-launcher instance version` + +Keep an instance on one installed Horizon version, or "latest" to follow updates again. + + horizon-launcher instance version + +- `INSTANCE` + +MCP: `instance_version`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). diff --git a/launcher/README.md b/launcher/README.md index 50ca6829c..ea4ebc39c 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -78,7 +78,9 @@ The opening, then Play ([clip](docs/opening.webm)): data folder, so renaming moves nothing. Every instance follows the launcher's data collection answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and - Open folder. + Open folder. Each instance plays the launcher's version, which follows updates, unless the Play + page's version picker keeps it on another installed one (to keep an old world on the version + it was made with); picking the version marked "follows updates" lets it follow again. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, @@ -178,6 +180,7 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code horizon-launcher instance create [--copy ] empty, or a copy of one's worlds, options and packs horizon-launcher instance rename|icon|group icon: a block or item name, #rrggbb or none horizon-launcher instance select make Play start it + horizon-launcher instance version keep it on one installed version, or follow updates horizon-launcher modpack [list] the imported packs and their coverage horizon-launcher modpack import a .mrpack, CurseForge zip or instance folder horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 22a850c02..8addbd191 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -180,6 +180,8 @@ enum InstanceCmd { }, /// Make Play start this instance Select { instance: String }, + /// Keep an instance on one installed Horizon version, or "latest" to follow updates again + Version { instance: String, version: String }, } #[derive(Subcommand)] @@ -647,11 +649,11 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { join, arg, } => { - let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; let instance = match instance { Some(name) => instances::find(&name)?, None => instances::selected(), }; + let mut cmd = backend::client(&instance.resolve_version(version.as_deref())?)?; instances::apply(&mut cmd, &instance)?; if let Some(code) = join { backend::join_friend(&mut cmd, &code)?; @@ -1385,6 +1387,7 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { serde_json::json!({ "id": i.id, "name": i.name, "kind": format!("{:?}", i.kind).to_lowercase(), "home": i.home, "icon": i.icon, "group": i.group, "selected": selected, + "version": i.version, }) }; let line = |i: &instances::Instance, selected: bool| { @@ -1394,8 +1397,13 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { .as_ref() .map(|g| format!(" [{g}]")) .unwrap_or_default(); + let pinned = i + .version + .as_ref() + .map(|v| format!(" {v}")) + .unwrap_or_default(); println!( - "{mark} {} ({}){group}\n {}", + "{mark} {} ({}){pinned}{group}\n {}", i.name, i.id, i.home.display() @@ -1430,6 +1438,13 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { changed(instances::edit(&instance, |m| m.group = group)?) } InstanceCmd::Select { instance } => changed(instances::select(&instance)?), + InstanceCmd::Version { instance, version } => { + let pin = match version.as_str() { + "latest" => None, + tag => Some(backend::resolve_version(Some(tag))?), + }; + changed(instances::edit(&instance, |m| m.version = pin)?) + } } Ok(()) } diff --git a/launcher/src/instances.rs b/launcher/src/instances.rs index d2e74dde1..4945ba813 100644 --- a/launcher/src/instances.rs +++ b/launcher/src/instances.rs @@ -86,6 +86,10 @@ pub struct Meta { pub icon: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub group: Option, + /// The Horizon version this instance plays, kept when newer ones are installed. None: the + /// launcher's own version, which follows updates. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, } /// `instances.json`: each instance's choices, by id. @@ -121,6 +125,25 @@ pub struct Instance { pub home: PathBuf, pub icon: Option, pub group: Option, + /// Its pinned Horizon version, if any (`Meta::version`). + pub version: Option, +} + +impl Instance { + /// The installed version this instance plays: its pinned one, else `requested` (the + /// command line's `--version`) or the launcher's (`backend::resolve_version`). + pub fn resolve_version(&self, requested: Option<&str>) -> Result { + match (requested, &self.version) { + (None, Some(pinned)) => backend::resolve_version(Some(pinned)).map_err(|_| { + format!( + "{} plays {pinned}, which is not installed: install it, or horizon-launcher \ + instance version \"{}\" latest", + self.name, self.name + ) + }), + _ => backend::resolve_version(requested), + } + } } /// The instances, by the default game home and the launcher's data folder: Horizon first, then @@ -172,6 +195,7 @@ fn list_in(game_home: &Path, data: &Path) -> Vec { name: meta.name.unwrap_or(name), icon: meta.icon, group: meta.group, + version: meta.version, id, kind, work, diff --git a/launcher/src/instances/tests.rs b/launcher/src/instances/tests.rs index 586b620b3..f1c94f5b8 100644 --- a/launcher/src/instances/tests.rs +++ b/launcher/src/instances/tests.rs @@ -201,3 +201,26 @@ fn icons_are_a_texture_name_or_a_colour() { assert_eq!(Icon::Texture("stone".into()).texture(&root), None); fs::remove_dir_all(&root).unwrap(); } + +#[test] +fn an_instance_keeps_its_own_version_until_it_follows_updates_again() { + let root = scratch("version"); + let (home, data) = (root.join("horizon"), root.join("launcher")); + player_home(&home); + create_in(&home, &data, "Old world", None).unwrap(); + let pinned = edit_in(&home, &data, "Old world", |m| { + m.version = Some("v0.1.0".into()) + }) + .unwrap(); + assert_eq!(pinned.version.as_deref(), Some("v0.1.0")); + // Renaming keeps it; the other instances follow the launcher's version. + let renamed = edit_in(&home, &data, "old-world", |m| m.name = Some("Older".into())).unwrap(); + assert_eq!(renamed.version.as_deref(), Some("v0.1.0")); + assert!(list_in(&home, &data) + .iter() + .filter(|i| i.id != "old-world") + .all(|i| i.version.is_none())); + let follows = edit_in(&home, &data, "Older", |m| m.version = None).unwrap(); + assert_eq!(follows.version, None); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/launcher/src/instances_page.rs b/launcher/src/instances_page.rs index ce6c1d42e..a414ca227 100644 --- a/launcher/src/instances_page.rs +++ b/launcher/src/instances_page.rs @@ -77,6 +77,25 @@ impl Launcher { list.iter().find(|i| i.id == id).or(list.first()) } + /// The installed version `instance` plays: its own, else the launcher's. + pub(super) fn version_of(&self, instance: &Instance) -> Option<&String> { + match &instance.version { + Some(own) => self.installed.iter().find(|t| *t == own), + None => self.launcher_version(), + } + } + + /// Keeps the selected instance on `tag`, or lets it follow the launcher's version. + pub(super) fn pin_version(&mut self, tag: Option) { + let Some(id) = self.selected_instance().map(|i| i.id.clone()) else { + return; + }; + match instances::edit(&id, |m| m.version = tag) { + Ok(_) => self.reload_instances(), + Err(e) => self.client_error = Some(e), + } + } + fn select_instance(&mut self, instance: &Instance) { self.settings.instance = (instance.kind != InstanceKind::Default).then(|| instance.id.clone()); @@ -154,15 +173,6 @@ impl Launcher { cx: &mut Context, ) -> Vec { let t = self.theme; - let tag = self.selected().cloned(); - let prepared = tag.as_deref().is_some_and(backend::is_prepared); - let status = if tag.is_none() { - "No version installed" - } else if prepared { - "Ready" - } else { - "Needs preparing" - }; let selected = self.selected_instance().map(|i| i.id.clone()); let on_packs = self.page == Page::Mods && self.mods.on_modpacks(); let mut out = Vec::new(); @@ -174,10 +184,18 @@ impl Launcher { out.push(heading(g.to_uppercase()).into_any_element()); } } + let tag = self.version_of(&i).cloned(); + let prepared = tag.as_deref().is_some_and(backend::is_prepared); let (open, sub) = match i.kind { InstanceKind::Default | InstanceKind::Own => ( self.page == Page::Play && selected.as_ref() == Some(&i.id), - status.to_string(), + match (&tag, &i.version) { + (None, Some(own)) => format!("{own} is not installed"), + (None, None) => "No version installed".into(), + (Some(_), _) if !prepared => "Needs preparing".into(), + (Some(tag), Some(_)) => format!("Ready · {tag}"), + (Some(_), None) => "Ready".into(), + }, ), InstanceKind::Port => { let slug = &i.id["port:".len()..]; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index b9f556d69..de87ceecc 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -764,7 +764,15 @@ impl Launcher { switched } + /// The version Play starts: the selected instance's own, else the launcher's. fn selected(&self) -> Option<&String> { + self.selected_instance() + .and_then(|i| self.version_of(i)) + .or_else(|| self.launcher_version()) + } + + /// The launcher's version: what instances without one of their own play. + fn launcher_version(&self) -> Option<&String> { self.settings .selected .as_ref() @@ -1850,16 +1858,20 @@ impl Launcher { .absolute() .top(px(66.)) .right_0() - .w(px(240.)) + .w(px(300.)) .p(px(6.)) .border_2() .border_color(t.outline) .bg(t.surface) .flex() .flex_col(); + // Picking a version keeps the selected instance on it; the launcher's own version + // (newest unless chosen otherwise on Versions) follows updates. + let follows = self.launcher_version().cloned(); for tag in &self.installed { let selected = self.selected() == Some(tag); let tag = tag.clone(); + let latest = follows.as_ref() == Some(&tag); menu = menu.child( div() .id(SharedString::from(format!("pick-{tag}"))) @@ -1875,12 +1887,20 @@ impl Launcher { .cursor_pointer() .hover(move |s| s.bg(t.plate_soft)) .child(tag.clone()) - .when(selected, |d| { - d.child(div().size(px(6.)).rounded_full().bg(t.accent)) - }) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .when(latest, |d| { + d.child(caps("follows updates").text_color(t.muted)) + }) + .when(selected, |d| { + d.child(div().size(px(6.)).rounded_full().bg(t.accent)) + }), + ) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.settings.selected = Some(tag.clone()); - this.settings.save(); + this.pin_version((!latest).then(|| tag.clone())); this.picker_open = false; cx.notify(); })), diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index cb4636429..d03f3d567 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -25,7 +25,7 @@ struct Session { /// The tools the session runs itself, under their CLI names: they keep a process (the game, a /// server) or a sign-in going between calls. Every other CLI command is generated (cli_tools.rs). fn session_tools() -> Value { - let version = json!({ "type": "string", "description": "An installed version tag such as v2026.10.13. Default: the selected version." }); + let version = json!({ "type": "string", "description": "An installed version tag such as v2026.10.13. Default: the selected version (play: the instance's own first)." }); let none = json!({ "type": "object", "properties": {} }); json!([ { "name": "play", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world. CLI: horizon-launcher play", @@ -68,12 +68,12 @@ impl Session { if self.client.as_ref().is_some_and(|c| c.finished().is_none()) { return Err("The client is already running.".into()); } - let tag = backend::resolve_version(arg_str(args, "version"))?; - let mut cmd = backend::client(&tag)?; let instance = match arg_str(args, "instance") { Some(name) => instances::find(name)?, None => instances::selected(), }; + let tag = instance.resolve_version(arg_str(args, "version"))?; + let mut cmd = backend::client(&tag)?; instances::apply(&mut cmd, &instance)?; cmd.args(game_tools::control_args()); if let Some(world) = arg_str(args, "world") { diff --git a/launcher/src/modpacks_page.rs b/launcher/src/modpacks_page.rs index 2f10b2773..7f1b95ad9 100644 --- a/launcher/src/modpacks_page.rs +++ b/launcher/src/modpacks_page.rs @@ -116,7 +116,13 @@ impl Launcher { } fn play_pack(&mut self, work: PathBuf) { - let Some(tag) = self.selected().cloned() else { + // The pack's instance plays its own version, if it has one. + let pack = self.instances.list.iter().find(|i| i.work == work); + let Some(tag) = pack + .and_then(|i| self.version_of(i)) + .or_else(|| self.launcher_version()) + .cloned() + else { return; }; if self.client.is_some() || self.starting_client.is_some() { From c70e2fae7411ab094c5f5a37d186dab9ee7c1b9e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:37:31 +0100 Subject: [PATCH 124/132] Launcher: worlds of an instance, with backup, copy and delete Home lists the selected instance's worlds from their level.dat (name, mode, version, last played) with their size and picture. Back up zips one into backups/ as vanilla's Make Backup does; Copy makes " (1)" with that name in its level.dat; Delete moves it to the system's trash after a confirmation (the file manager call on macOS, no Finder permission); Open folder. `horizon-launcher worlds list|backup|copy|delete`, and their MCP tools (delete needs confirm). level.dat is read with horizon-world's NBT. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 43 +++++ launcher/Cargo.lock | 225 +++++++++++++++++++++++++- launcher/Cargo.toml | 6 + launcher/README.md | 7 + launcher/src/cli.rs | 100 ++++++++++++ launcher/src/cli_tools.rs | 1 + launcher/src/lib.rs | 1 + launcher/src/main.rs | 9 ++ launcher/src/worlds.rs | 270 +++++++++++++++++++++++++++++++ launcher/src/worlds/tests.rs | 157 ++++++++++++++++++ launcher/src/worlds_page.rs | 298 +++++++++++++++++++++++++++++++++++ 11 files changed, 1111 insertions(+), 6 deletions(-) create mode 100644 launcher/src/worlds.rs create mode 100644 launcher/src/worlds/tests.rs create mode 100644 launcher/src/worlds_page.rs diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 6faaeed74..5d46c10cd 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -330,6 +330,49 @@ Keep an instance on one installed Horizon version, or "latest" to follow updates MCP: `instance_version`. +## `horizon-launcher worlds list` + +The worlds: name, mode, version, last played and size (the default). + + horizon-launcher worlds list + +- `--instance`: The instance (default: the selected one) + +MCP: `worlds_list`. + +## `horizon-launcher worlds backup` + +Zip a world into the instance's backups/ folder, as the game's Make Backup does. + + horizon-launcher worlds backup + +- `WORLD`: Its folder or name +- `--instance` + +MCP: `worlds_backup`. + +## `horizon-launcher worlds copy` + +Copy a world beside it, as " (1)". + + horizon-launcher worlds copy + +- `WORLD` +- `--instance` + +MCP: `worlds_copy`. + +## `horizon-launcher worlds delete` + +Move a world to the system's trash. + + horizon-launcher worlds delete + +- `WORLD` +- `--instance` + +MCP: `worlds_delete`, needs `confirm: true`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index dd9313df6..dbd21a37f 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -70,6 +70,15 @@ dependencies = [ "equator", ] +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anstream" version = "1.0.0" @@ -919,6 +928,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link 0.2.1", +] + [[package]] name = "cipher" version = "0.4.4" @@ -981,6 +1001,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "cocoa" version = "0.25.0" @@ -1635,6 +1664,18 @@ dependencies = [ "winreg", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.42" @@ -2354,7 +2395,7 @@ dependencies = [ "wayland-protocols-plasma", "windows 0.61.3", "windows-core 0.61.2", - "windows-numerics", + "windows-numerics 0.2.0", "windows-registry 0.5.3", "x11-clipboard", "x11rb", @@ -2693,6 +2734,7 @@ dependencies = [ name = "horizon-launcher" version = "0.2.0" dependencies = [ + "chrono", "clap", "dirs 5.0.1", "flate2", @@ -2708,6 +2750,7 @@ dependencies = [ "horizon-release-sign", "horizon-telemetry", "horizon-theme", + "horizon-world", "image", "keyring", "objc2-app-kit", @@ -2720,6 +2763,7 @@ dependencies = [ "sha1", "sha2 0.10.9", "tar", + "trash", "ureq", "winresource", "zip", @@ -2801,6 +2845,21 @@ dependencies = [ name = "horizon-theme" version = "0.1.0" +[[package]] +name = "horizon-world" +version = "0.1.0" +dependencies = [ + "flate2", + "horizon-core", + "libm", + "lz4_flex", + "postcard", + "serde", + "serde_json", + "sha2 0.10.9", + "xxhash-rust", +] + [[package]] name = "http" version = "1.5.0" @@ -2907,6 +2966,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.61.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -3425,6 +3508,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" + [[package]] name = "mac" version = "0.1.1" @@ -4263,6 +4352,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -6187,6 +6288,24 @@ dependencies = [ "once_cell", ] +[[package]] +name = "trash" +version = "5.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317" +dependencies = [ + "chrono", + "libc", + "log", + "objc2", + "objc2-foundation", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows 0.62.2", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -6367,6 +6486,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "usvg" version = "0.45.1" @@ -6820,11 +6945,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -6837,7 +6974,7 @@ dependencies = [ "rayon", "thiserror 2.0.21", "windows 0.61.3", - "windows-future", + "windows-future 0.2.1", ] [[package]] @@ -6849,6 +6986,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.57.0" @@ -6874,6 +7020,19 @@ dependencies = [ "windows-strings 0.4.2", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-future" version = "0.2.1" @@ -6882,7 +7041,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -6951,6 +7121,16 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + [[package]] name = "windows-registry" version = "0.4.0" @@ -6991,6 +7171,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-strings" version = "0.3.1" @@ -7009,6 +7198,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -7111,6 +7309,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -7423,6 +7630,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + [[package]] name = "y4m" version = "0.8.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index a97f128b8..57179380b 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -37,6 +37,12 @@ horizon-mods = { path = "../crates/horizon-mods", features = ["index"] } horizon-release-sign = { path = "../crates/horizon-release-sign" } # Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md). horizon-telemetry = { path = "../crates/horizon-telemetry" } +# level.dat and servers.dat (the worlds and server lists of instances) +horizon-world = { path = "../crates/horizon-world" } +# Deleting a world moves it to the system's trash +trash = "5" +# Backup names carry the local time, as vanilla's do +chrono = { version = "0.4", default-features = false, features = ["clock"] } # The session file's random name. getrandom = "0.3" # Players' heads on the Servers page, from the default skins in the player's own game files (already diff --git a/launcher/README.md b/launcher/README.md index ea4ebc39c..6a8fe7086 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -81,6 +81,11 @@ The opening, then Play ([clip](docs/opening.webm)): Open folder. Each instance plays the launcher's version, which follows updates, unless the Play page's version picker keeps it on another installed one (to keep an old world on the version it was made with); picking the version marked "follows updates" lets it follow again. +- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played, + size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does + (`_