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 001/106] 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 002/106] 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 003/106] 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 004/106] 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 005/106] 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 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 006/106] 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 705e3d10cf00e1fd4e504c6a974432531f5f983a Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 14:11:07 +0100 Subject: [PATCH 007/106] 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 008/106] 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 009/106] 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 010/106] 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 011/106] 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 012/106] 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 818b377c02105e8662225a8ec7072867834ed9ef Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:54:32 +0100 Subject: [PATCH 013/106] 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 014/106] 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 015/106] 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 016/106] 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 017/106] 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 018/106] 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 019/106] 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 020/106] 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 021/106] 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 022/106] 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 29eae3a1afc1f725a69a43cc8da3d44c878c43ff Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:58:51 +0100 Subject: [PATCH 023/106] 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 024/106] 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 025/106] 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 43d1f4b80185a11e405199188a6ba993c520bf42 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:06:26 +0100 Subject: [PATCH 026/106] Draw the swirls of potion effects around players and mobs A client draws the particles of an entity's visible effects itself, from the synched effect particle list (LivingEntity.tickEffects). Horizon drew none and sent no such list: now the window's own player, a server's mobs and players, and the mobs and guests of a game in the frame all swirl. --- .../horizon-client/src/game/client_ambient.rs | 119 +++++++++++++++++- crates/horizon-client/src/game/lan.rs | 11 ++ .../src/game/remote_mob_data.rs | 31 ++++- crates/horizon-client/src/lan/hub.rs | 62 ++++++++- crates/horizon-client/src/mobs.rs | 4 + 5 files changed, 223 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index a10c6da49..48bfc663c 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -5,7 +5,8 @@ //! a server: nothing of them goes over the network. use super::Game; use horizon_client::mobs::{MobEvent, ambient}; -use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType}; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { pub(super) fn tick_client_ambient(&mut self) { @@ -33,5 +34,121 @@ impl Game<'_> { } } self.eye_particles(); + self.effect_swirls(); + } + + /// `LivingEntity.tickEffects` on a client: the swirls around an entity + /// with visible effects, from the particles its synched data lists. The + /// window's player has its own effects, a server's mobs and players the + /// list the server sent, and the mobs and guests of a game in the frame + /// theirs. + fn effect_swirls(&mut self) { + if let Some(p) = self.player.as_ref() { + let effects = &self.potions.effects.list; + let list: Vec<_> = effects + .iter() + .filter(|e| e.visible) + .filter_map(|e| effect_particle(e.id, e.ambient)) + .collect(); + let ambient = effects.iter().filter(|e| e.visible).all(|e| e.ambient); + let invisible = effects.iter().any(|e| e.id == "invisibility"); + let size = ( + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); + swirl( + &mut self.particles, + p.position, + size, + &list, + ambient, + invisible, + ); + } + let guests = self.lan.iter().flat_map(|host| host.models.values()); + for m in self.mobs.iter().chain(guests) { + if !m.alive() { + continue; + } + let size = (f64::from(m.width()), f64::from(m.height())); + let invisible = m.invisible || m.has_effect("minecraft:invisibility"); + if m.extra.effect_particles.is_empty() { + // A mob of this game: its own effects, visible and not ambient. + if m.extra.effects.is_empty() { + continue; + } + let list: Vec<_> = m + .extra + .effects + .iter() + .filter_map(|e| effect_particle(e.0, false)) + .collect(); + swirl( + &mut self.particles, + m.position, + size, + &list, + false, + invisible, + ); + } else { + let list = &m.extra.effect_particles; + let ambient = m.extra.effect_ambient; + swirl( + &mut self.particles, + m.position, + size, + list, + ambient, + invisible, + ); + } + } } } + +/// `MobEffect.particleFactory`: the omens have particles of their own, any +/// other effect an entity effect in its colour, faint when ambient. +pub(super) fn effect_particle(effect: &str, ambient: bool) -> Option { + Some(match effect.trim_start_matches("minecraft:") { + "trial_omen" => ParticleOptions::simple(ParticleType::TrialOmen), + "raid_omen" => ParticleOptions::simple(ParticleType::RaidOmen), + other => { + let color = horizon_client::brewing::effect(other)?.color; + let channel = |shift: u32| ((color >> shift) & 255) as f32 / 255.0; + // MobEffect.AMBIENT_ALPHA is 38 of 255. + let alpha = if ambient { 38.0 / 255.0 } else { 1.0 }; + ParticleOptions::colored( + ParticleType::EntityEffect, + [channel(16), channel(8), channel(0), alpha], + ) + } + }) +} + +/// One tick of `LivingEntity.tickEffects`' client branch: a one in four +/// chance (one in fifteen while invisible, a fifth of either when all the +/// effects are ambient) of one of the particles at a random spot of the box. +fn swirl( + particles: &mut ParticleEngine, + feet: Vec3, + size: (f64, f64), + list: &[ParticleOptions], + ambient: bool, + invisible: bool, +) { + if list.is_empty() { + return; + } + let bound = if invisible { 15 } else { 4 } * if ambient { 5 } else { 1 }; + let r = particles.random(); + let Ok(0) = r.next_int_bound(bound) else { + return; + }; + // Util.getRandom, then getRandomX(0.5), getRandomY and getRandomZ. + let pick = r.next_int_bound(list.len() as i32).unwrap_or_default() as usize; + let x = feet.x + size.0 * (2.0 * r.next_double() - 1.0) * 0.5; + let y = feet.y + size.1 * r.next_double(); + let z = feet.z + size.0 * (2.0 * r.next_double() - 1.0) * 0.5; + particles.add(&list[pick], [x, y, z], [1.0; 3]); +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..a48c30656 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -178,6 +178,11 @@ fn mob_meta( meta.push((9, serializer::FLOAT, Value::Float(health))); } defaults.push((9, serializer::FLOAT, Value::Float(1.0))); + // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: the + // swirls of its effects (the ones a mob has are visible, not ambient). + meta.extend(hub.effect_meta(m.extra.effects.iter().map(|e| (e.0, false)))); + defaults.push((10, serializer::PARTICLES, Value::Particles(Vec::new()))); + defaults.push((11, serializer::BOOLEAN, Value::Bool(false))); // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what // draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised // weapon). @@ -1409,6 +1414,12 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects. + let visible = || g.effects.list.iter().filter(|e| e.visible); + m.extra.effect_particles = visible() + .filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient)) + .collect(); + m.extra.effect_ambient = visible().all(|e| e.ambient); // 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_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..3c7d6fb49 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -5,7 +5,8 @@ use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; use horizon_client::mobs::{Mob, Species, Who, bat, tame}; -use horizon_protocol::entity_data::Value; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_protocol::entity_data::{Particle, ParticleData, Value}; use horizon_protocol::registry::Builtin; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry @@ -34,6 +35,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti // LivingEntity.DATA_HEALTH_ID: the boss bars and the death // animation follow it. (9, Value::Float(health)) => m.health = *health, + // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: + // the swirls of its effects (`tickEffects` draws them). + (10, Value::Particles(list)) => m.extra.effect_particles = swirls(list, builtin), + (11, Value::Bool(ambient)) => m.extra.effect_ambient = *ambient, // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4. // Mob.isAggressive draws the illagers' and skeletons' attack // poses and the vindicator's axe. @@ -100,6 +105,30 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti } } +/// The options of a synched particle list: an entity effect carries its ARGB +/// colour, the omens none. +fn swirls(list: &[Particle], builtin: &Builtin) -> Vec { + let channel = |argb: i32, shift: u32| ((argb >> shift) & 255) as f32 / 255.0; + list.iter() + .filter_map(|p| { + let name = builtin.get("minecraft:particle_type")?.name(p.id)?; + let ty = ParticleType::from_name(name)?; + Some(match p.data { + Some(ParticleData::Color(argb)) => ParticleOptions::colored( + ty, + [ + channel(argb, 16), + channel(argb, 8), + channel(argb, 0), + channel(argb, 24), + ], + ), + _ => ParticleOptions::simple(ty), + }) + }) + .collect() +} + /// VillagerData as the network sends it: the type and the profession by /// their built-in registry ids, then the level. fn villager_data(m: &mut Mob, data: &[i32], builtin: &Builtin) { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..c76404291 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -21,7 +21,7 @@ use crate::{ use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ - entity_data::{Value, serializer}, + entity_data::{Particle, ParticleData, Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; @@ -1500,6 +1500,49 @@ impl Hub { // ---- entities ------------------------------------------------------ + /// `LivingEntity.updateSynchronizedMobEffectParticles`: DATA_EFFECT_PARTICLES + /// (10) and DATA_EFFECT_AMBIENCE_ID (11) for the visible `effects`, as + /// (effect, ambient). The entries are left out when there is nothing to + /// show, which is their default. + pub fn effect_meta<'a>( + &self, + effects: impl IntoIterator, + ) -> Vec<(u8, i32, Value)> { + let mut particles = Vec::new(); + let mut all_ambient = true; + for (effect, ambient) in effects { + let effect = effect.trim_start_matches("minecraft:"); + // MobEffect.particleFactory: the omens have their own particles, + // the others an entity effect in their colour (faint if ambient). + let (name, data) = match effect { + "trial_omen" | "raid_omen" => (effect, None), + _ => { + let Some(def) = crate::brewing::effect(effect) else { + continue; + }; + let alpha = if ambient { 38 } else { 255 }; + let argb = (alpha << 24) | def.color as i32; + ("entity_effect", Some(ParticleData::Color(argb))) + } + }; + let Some(id) = + self.registry_id("minecraft:particle_type", &format!("minecraft:{name}")) + else { + continue; + }; + particles.push(Particle { id, data }); + all_ambient &= ambient; + } + if particles.is_empty() { + return Vec::new(); + } + let mut meta = vec![(10, serializer::PARTICLES, Value::Particles(particles))]; + if all_ambient { + meta.push((11, serializer::BOOLEAN, Value::Bool(true))); + } + meta + } + fn player_state( &self, id: i32, @@ -1514,6 +1557,7 @@ impl Hub { health: f32, equipment: Vec<(u8, Option)>, attributes: Vec, + effects: &[EffectInstance], ) -> EntityState { let (sneaking, sprinting, gliding, sleeping) = flags; let shared = shared_flags(sneaking, sprinting, gliding); @@ -1547,6 +1591,14 @@ impl Hub { if skin != 0 { meta.push((16, serializer::BYTE, Value::Byte(skin as i8))); } + meta.extend( + self.effect_meta( + effects + .iter() + .filter(|e| e.visible) + .map(|e| (e.id, e.ambient)), + ), + ); EntityState { id, uuid, @@ -1559,7 +1611,11 @@ impl Hub { velocity: [0.0; 3], data: 0, meta, - defaults: Vec::new(), + // The effect swirls go back to none. + defaults: vec![ + (10, serializer::PARTICLES, Value::Particles(Vec::new())), + (11, serializer::BOOLEAN, Value::Bool(false)), + ], equipment, attributes, precise: false, @@ -1614,6 +1670,7 @@ impl Hub { h.health, equipment, h.attributes.clone(), + &[], )); } let placed: Vec = (0..self.guests.len()) @@ -1649,6 +1706,7 @@ impl Hub { .as_ref() .map(|m| super::attributes::syncable(&m.attributes)) .unwrap_or_default(), + &g.effects.list, ) }) .collect(); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..0bc37bcc7 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -715,6 +715,10 @@ pub struct Extra { pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, + /// `LivingEntity.DATA_EFFECT_PARTICLES` and `DATA_EFFECT_AMBIENCE_ID` as a + /// server gave them: the swirls around it, and whether they are all faint. + pub effect_particles: Vec, + pub effect_ambient: bool, /// An invisible illusioner's mirror images. pub illusions: Option, /// A villager's claimed bed head and meeting bell. From 18f8a6868bb18d843562663835a5298bfdcae1a9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:09:23 +0100 Subject: [PATCH 027/106] 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 028/106] 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 029/106] 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 030/106] 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 f312aae7dbf6358093ce27906311c4416446c2e1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:29:22 +0100 Subject: [PATCH 031/106] 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 032/106] 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 033/106] 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 034/106] 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 035/106] 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 036/106] 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 037/106] 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 038/106] 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 039/106] 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 040/106] 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 041/106] 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 27b81d9a8f5390a2992385ba67ecc0902bea742a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:35:42 +0100 Subject: [PATCH 042/106] Give /damage on a player its source, knockback and kill credit --- .../src/game/commands/world_cmds.rs | 23 +++++---- crates/horizon-client/src/game/creatures.rs | 50 +++++++++++++------ 2 files changed, 47 insertions(+), 26 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..80145ab0d 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -140,27 +140,30 @@ impl Game<'_> { Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(), _ => None, }; + let cause = match ctx.get("cause") { + Some(Arg::Entity(_)) => self.entities(ctx, "cause", false)?.first().copied(), + _ => None, + }; let from = match ctx.get("location") { Some(Arg::Coords(_)) => self.position_arg(ctx, "location"), _ => by.and_then(|t| self.target_position(t)), }; let hurt = match target { + // The causing mob is the one the hit is credited to and thorns + // answer; the source position gives the knockback its direction. Target::Player => { - if self.creative || self.spectator() { + if self.spectator() { false - } else if let Some(player) = self.player.as_mut() { - match self.motion.health.damage.id(&ty) { - Some(id) => player - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false), - None => false, - } } else { - false + let attacker = match cause.or(by) { + Some(Target::Mob(i)) => Some(Some(i)), + _ => Some(None), + }; + self.hurt_player_from(amount, from, &ty, attacker) } } Target::Mob(id) => { - let attacker = by.and_then(|t| match t { + let attacker = cause.or(by).and_then(|t| match t { Target::Player => Some(Who::Player), Target::Mob(i) => Some(Who::Mob(i)), _ => None, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 545b306dc..a06bf80ac 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1552,6 +1552,18 @@ impl Game<'_> { amount: f32, from: [f64; 3], damage_type: &str, + ) -> bool { + self.hurt_player_from(amount, Some(from), damage_type, None) + } + /// `hurtServer` on the player. `from` is the source's position (none: no + /// direction), `known`: the causing mob when it is given (`/damage`), + /// else the melee attacker is the mob nearest to `from`. + pub(super) fn hurt_player_from( + &mut self, + amount: f32, + from: Option<[f64; 3]>, + damage_type: &str, + known: Option>, ) -> bool { // ServerPlayer.canHarmPlayer refused another player's projectile. if self.creative || self.combat.refuse_player_hit { @@ -1564,23 +1576,26 @@ impl Game<'_> { .damage_tags .get("minecraft:is_projectile") .is_some_and(|t| t.contains(damage_type)); - let blocking = self.player_blocking(Some(from), damage_type, false); + let blocking = self.player_blocking(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 = match known { + Some(known) => known, + None => from + .filter(|_| !projectile && damage_type != "minecraft:player_attack") + .and_then(|from| { + 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) + }), + }; // The causing entity for the death message. let owner = self.combat.projectile_owner.take(); if let Some(a) = attacker.or(owner) { @@ -1608,7 +1623,10 @@ impl Game<'_> { // LivingEntity.hurtServer's dealDefaultKnockback: not inside the // hurt cooldown (a stronger hit there only adds its difference). if o.knockback { - let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); + // No source position: a random direction. + let (xd, zd) = from.map_or((0.0, 0.0), |from| { + (from[0] - player.position.x, from[2] - player.position.z) + }); self.knock_back_player(f64::from(0.4_f32), xd, zd); if let Some(p) = self.player.as_mut() && let Some(r) = p.hurt_log.last_mut() From e23fcb1040d573c9254223af79a1f4c27c30bd35 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:35:46 +0100 Subject: [PATCH 043/106] 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 044/106] 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 045/106] 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 046/106] 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 047/106] 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 4201fd23c0dda6ab5ff3624cc79e4c322800980c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:39:05 +0100 Subject: [PATCH 048/106] 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 049/106] 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 36c06d6133a3e09d95c5027aa89ee15620596c02 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:41:38 +0100 Subject: [PATCH 050/106] Let a piglin celebrate a killed target and dance over a hoglin --- crates/horizon-client/src/game/lan.rs | 7 ++ .../src/game/remote_mob_data.rs | 2 + crates/horizon-client/src/mobs/ai.rs | 3 + crates/horizon-client/src/mobs/piglin.rs | 87 ++++++++++++++++++- 4 files changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..1682e6498 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -223,6 +223,13 @@ fn mob_meta( } defaults.push((16, serializer::BYTE, Value::Byte(0))); } + // Piglin.DATA_IS_DANCING (after the baby flag and the crossbow charge). + "minecraft:piglin" => { + if e.scratch[0] > 0 { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } // 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/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..3ee576e78 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -66,6 +66,8 @@ 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; } + // Piglin.DATA_IS_DANCING: the dance pose. + (Species::Piglin, 19, Value::Bool(dancing)) => m.extra.scratch[0] = i32::from(*dancing), // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. (Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => { m.extra.sitting = flags & 1 != 0; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 7f6c33fc1..8911d343f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -668,6 +668,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // serverAiStep has no goals, so it only falls and is pushed. let immobile = (m.species() == Species::Ravager && super::ravager::immobile(m)) || m.species() == Species::Mannequin; + if m.species() == Species::Piglin && m.alive() { + super::piglin::celebrate(m, w); + } if m.alive() && !immobile { server_ai_step(m, w, level_random, events); } else { diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index de9ba42dd..028fa0386 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -20,6 +20,9 @@ pub const ADMIRE: i32 = 119; pub const ATE_RECENTLY: i32 = 200; /// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's). const CONVERSION: i32 = 300; +/// `PiglinAi.CELEBRATION_TIME`: how long the `CELEBRATE_LOCATION` and +/// `DANCING` memories last. +const CELEBRATION: i32 = 300; fn hostile_to_player(m: &Mob, w: &MobWorld) -> bool { if m.is_baby() { @@ -50,6 +53,7 @@ pub fn register_piglin(m: &mut Mob) { g.add(3, MeleeAttack::new(1.0, true)); g.add(4, PiglinAvoidRepellent); g.add(4, GoToWantedItem); + g.add(4, Celebrate); g.add(5, Stroll::avoiding_water(0.6)); g.add(6, LookAtPlayer::new(8.0)); g.add(7, RandomLookAround::default()); @@ -243,6 +247,45 @@ impl Goal for Admire { m.nav_stop(); } } +/// The celebrate activity: `GoToTargetLocation` on the spot a killed target +/// fell (within 2 blocks, or 4 and slower while dancing). +#[derive(Clone, Debug)] +struct Celebrate; +impl Celebrate { + fn walk(m: &mut Mob, cx: &mut Cx) { + let Some(at) = m.extra.home else { return }; + let (close, speed) = if m.extra.scratch[0] > 0 { + (4.0, 0.6) + } else { + (2.0, 1.0) + }; + let center = Vec3::new( + f64::from(at[0]) + 0.5, + f64::from(at[1]), + f64::from(at[2]) + 0.5, + ); + if m.distance_sqr(center) >= close * close { + m.nav_move_to(cx.w, [center.x, center.y, center.z], speed); + } + } +} +impl Goal for Celebrate { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.scratch[1] > 0 && m.extra.home.is_some() && m.extra.using_item == 0 + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + Self::walk(m, cx); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.ai.nav.is_done() { + Self::walk(m, cx); + } + } +} /// `GoToWantedItem`: walk to the gold the game spotted. #[derive(Clone, Debug)] struct GoToWantedItem; @@ -294,6 +337,45 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.ai.target = None; } } +/// `StartCelebratingIfTargetDead` for a piglin (`scratch[0]` dancing, +/// `scratch[1]` ticks of celebration left, `scratch[2]` the hit seen, `home` +/// the `CELEBRATE_LOCATION`): a killed target starts a celebration at its +/// spot, and a hoglin's death makes the piglin dance one time in ten. +/// `PiglinAi.wasHurtBy` ends both. Runs before the target goals drop the +/// dead target. +pub fn celebrate(m: &mut Mob, w: &MobWorld) { + if m.extra.scratch[1] > 0 { + m.extra.scratch[1] -= 1; + if m.extra.scratch[1] == 0 { + m.extra.scratch[0] = 0; + m.extra.home = None; + } + } + if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.scratch[2] { + m.extra.scratch[2] = m.ai.last_hurt_by_time; + m.extra.scratch[0] = 0; + m.extra.scratch[1] = 0; + m.extra.home = None; + } + if m.extra.scratch[1] > 0 { + return; + } + let Some(target) = m.ai.target else { return }; + let Some(t) = w.target_info(target).filter(|t| !t.alive) else { + return; + }; + let hoglin = + matches!(target, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Hoglin)); + if hoglin && m.random.next_float() < 0.1 { + m.extra.scratch[0] = 1; + } + m.extra.scratch[1] = CELEBRATION; + m.extra.home = Some([ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]); +} /// Per-tick piglin and hoglin state: admiring, anger, zombification and the /// hoglin attack animation. Returns a conversion when it happens. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { @@ -420,7 +502,10 @@ pub fn ears(p: &mut Poses, s: &State) { /// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the /// arm pose (`PiglinModel`). pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { - let pose = if m.extra.using_item > 0 { + // Piglin.getArmPose: dancing comes first. + let pose = if m.extra.scratch[0] > 0 { + PiglinPose::Dancing + } else if m.extra.using_item > 0 { PiglinPose::AdmiringItem } else if m.extra.flag { PiglinPose::CrossbowCharge From 34dabe4afdfafd89c5bb1240843d4253d4f74fa2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:41:49 +0100 Subject: [PATCH 051/106] 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 052/106] 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 06b046d8fc3046bc83ad0ee1ba946e2e25676931 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:07:17 +0100 Subject: [PATCH 053/106] 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 054/106] 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 055/106] 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 f4a235e02792a38530ea9058bc4bbbde2ef771e2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:20:45 +0100 Subject: [PATCH 056/106] 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 057/106] 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 058/106] 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 56bf45cee512556c8c0a01eea04371876a117606 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:23:03 +0100 Subject: [PATCH 059/106] 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 060/106] 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 c808fae288d36c682b143edb4e1283438437e165 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:37:30 +0100 Subject: [PATCH 061/106] 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 062/106] 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 063/106] 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 d7fece582525719a905729232904b3d566090751 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:42:52 +0100 Subject: [PATCH 064/106] Keep hideParticles of mob effects: no swirls drawn or sent for them --- crates/horizon-client/src/game/client_ambient.rs | 1 + crates/horizon-client/src/game/commands/effects.rs | 11 ++++++++++- crates/horizon-client/src/game/lan.rs | 8 +++++++- crates/horizon-client/src/mobs.rs | 2 ++ crates/horizon-client/src/mobs/ai.rs | 3 +++ 5 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index 48bfc663c..3ea8f922a 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -81,6 +81,7 @@ impl Game<'_> { .extra .effects .iter() + .filter(|e| !m.extra.hidden_effects.contains(&e.0)) .filter_map(|e| effect_particle(e.0, false)) .collect(); swirl( diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 65d6592f7..6516bfe6c 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -91,7 +91,12 @@ impl Game<'_> { } Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { - m.add_effect(namespaced(effect.id), duration, amplifier); + let name = namespaced(effect.id); + m.add_effect(name, duration, amplifier); + m.extra.hidden_effects.retain(|h| *h != name); + if !particles { + m.extra.hidden_effects.push(name); + } true } None => false, @@ -154,6 +159,10 @@ impl Game<'_> { m.extra .effects .retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id))); + let left = &m.extra.effects; + m.extra + .hidden_effects + .retain(|h| left.iter().any(|x| x.0 == *h)); m.extra.effects.len() != before } None => false, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index a48c30656..f1298e589 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -180,7 +180,13 @@ fn mob_meta( defaults.push((9, serializer::FLOAT, Value::Float(1.0))); // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: the // swirls of its effects (the ones a mob has are visible, not ambient). - meta.extend(hub.effect_meta(m.extra.effects.iter().map(|e| (e.0, false)))); + meta.extend( + hub.effect_meta( + (m.extra.effects.iter()) + .filter(|e| !m.extra.hidden_effects.contains(&e.0)) + .map(|e| (e.0, false)), + ), + ); defaults.push((10, serializer::PARTICLES, Value::Particles(Vec::new()))); defaults.push((11, serializer::BOOLEAN, Value::Bool(false))); // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 0bc37bcc7..b02eb111a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -715,6 +715,8 @@ pub struct Extra { pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, + /// The effects above given with `hideParticles`: no swirls for them. + pub hidden_effects: Vec<&'static str>, /// `LivingEntity.DATA_EFFECT_PARTICLES` and `DATA_EFFECT_AMBIENCE_ID` as a /// server gave them: the swirls around it, and whether they are all faint. pub effect_particles: Vec, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..014032280 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1488,6 +1488,9 @@ fn tick_effects(m: &mut Mob) { *ticks -= 1; } effects.retain(|e| e.1 > 0); + m.extra + .hidden_effects + .retain(|h| effects.iter().any(|e| e.0 == *h)); m.extra.effects = effects; } From eab8d0f91120e6f9732196a01e2b2a9fb03bf0bf Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:45:02 +0100 Subject: [PATCH 065/106] 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 066/106] 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 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 067/106] 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 068/106] 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 069/106] 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 070/106] 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 071/106] 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 1b0937abff5f0bbca3f00655164bd948845012fa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:00:05 +0100 Subject: [PATCH 072/106] Piglin celebration: the dance roll and wasHurtBy as in PiglinAi wantsToDance draws from RandomSource.createThreadLocalInstance(gameTime), not the piglin's random, and wasHurtBy ignores another piglin's hit. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/piglin.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 028fa0386..5477ddb05 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -10,7 +10,7 @@ use super::{ }, }; use horizon_core::geometry::{Vec3, trig::Mth}; -use horizon_core::random::RandomSource; +use horizon_core::random::{LegacyRandom, RandomSource}; use std::f32::consts::PI; /// `PiglinAi.ADMIRE_DURATION`. @@ -351,11 +351,18 @@ pub fn celebrate(m: &mut Mob, w: &MobWorld) { m.extra.home = None; } } - if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.scratch[2] { + if let Some(by) = m.ai.last_hurt_by + && m.ai.last_hurt_by_time != m.extra.scratch[2] + { m.extra.scratch[2] = m.ai.last_hurt_by_time; - m.extra.scratch[0] = 0; - m.extra.scratch[1] = 0; - m.extra.home = None; + // PiglinAi.wasHurtBy: another piglin's hit ends nothing. + let piglin = + matches!(by, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Piglin)); + if !piglin { + m.extra.scratch[0] = 0; + m.extra.scratch[1] = 0; + m.extra.home = None; + } } if m.extra.scratch[1] > 0 { return; @@ -366,7 +373,9 @@ pub fn celebrate(m: &mut Mob, w: &MobWorld) { }; let hoglin = matches!(target, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Hoglin)); - if hoglin && m.random.next_float() < 0.1 { + // PiglinAi.wantsToDance: a fresh random seeded with the game time, not + // the piglin's own. + if hoglin && LegacyRandom::new(w.game_time).next_float() < 0.1 { m.extra.scratch[0] = 1; } m.extra.scratch[1] = CELEBRATION; 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 073/106] 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 266c7a2cd92116965fd379884591ddab373b3f46 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 14:47:04 +0100 Subject: [PATCH 074/106] 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 075/106] 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 076/106] 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 077/106] 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 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 078/106] 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 079/106] 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 080/106] 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 081/106] 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 082/106] 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 083/106] 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 084/106] 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 085/106] 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 086/106] 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 + (`_