From 70fad91ee5353b5828afc2dbe08d49d5984f8ea1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:08:26 +0200 Subject: [PATCH 01/11] F3 key combinations, as 26.3's KeyboardHandler runs them F3 only toggled the debug overlay. 26.3 makes the debug keys rebindable mappings (key.debug.*): the modifier (F3) held with another key runs handleDebugKeys, released alone toggles the overlay unless it was used as a modifier; F3+Escape pauses without the menu; F3+C held ten seconds crashes the game. - debug_keys: KeyboardHandler.keyPress's state (usedDebugKeyAsModifier, the modifier's down state, debugCrashKeyTime) and tick, with the actions in handleDebugKeys' order; unit tests replay key sequences. - gizmos: 26.3's gizmo lines (colour, width in pixels, near-plane clip as GizmoFeatureRenderer.buildLines), ChunkBorderRenderer's geometry and EntityHitboxDebugRenderer's boxes, eye lines and view arrows; a coloured line pipeline draws them, depth tested or always on top. - game/debug_keys: the actions. F3+A rebuilds every section, B hitboxes, C copies the location (/execute in ... run tp @s, %.2f half up), D clears chat, G chunk borders, H advanced tooltips (options.txt), I copies /setblock or /summon with data (Shift: client side), N toggles spectator and the previous mode with /gamemode's feedback, P pause on lost focus, T reloads resource packs, V dumps the version, X improved transparency; F4 without permission says debug.gamemodes.error. Messages carry the bold [Debug]: prefix in yellow (red for the crash countdown). - PauseScreen(false): only "Game Paused" at the top; the pauseOnLostFocus option now decides whether losing focus pauses. - The clipboard through arboard; `horizon-ctl status` reports the debug state and the text last copied. Fixes #73 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 135 ++++- crates/horizon-client/Cargo.toml | 1 + crates/horizon-client/src/debug_keys.rs | 456 ++++++++++++++++ crates/horizon-client/src/game.rs | 73 ++- crates/horizon-client/src/game/agent.rs | 2 +- crates/horizon-client/src/game/commands.rs | 2 +- .../horizon-client/src/game/commands/extra.rs | 47 +- crates/horizon-client/src/game/control.rs | 32 +- crates/horizon-client/src/game/debug_keys.rs | 503 ++++++++++++++++++ crates/horizon-client/src/game/game_mode.rs | 4 + crates/horizon-client/src/game/hand.rs | 2 +- crates/horizon-client/src/game/options.rs | 2 +- crates/horizon-client/src/game/screens.rs | 5 +- crates/horizon-client/src/game/stations.rs | 3 +- crates/horizon-client/src/gfx.rs | 81 +++ crates/horizon-client/src/gizmos.rs | 347 ++++++++++++ crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/terrain.wgsl | 33 ++ 18 files changed, 1694 insertions(+), 36 deletions(-) create mode 100644 crates/horizon-client/src/debug_keys.rs create mode 100644 crates/horizon-client/src/game/debug_keys.rs create mode 100644 crates/horizon-client/src/gizmos.rs diff --git a/Cargo.lock b/Cargo.lock index de5ec019d..f0e8c5987 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,6 +99,24 @@ dependencies = [ "libc", ] +[[package]] +name = "arboard" +version = "3.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.59.0", + "wl-clipboard-rs", + "x11rb", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -271,6 +289,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -494,6 +521,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "fdeflate" version = "0.3.7" @@ -509,6 +542,12 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flate2" version = "1.1.10" @@ -520,6 +559,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -641,6 +686,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -649,7 +703,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", ] [[package]] @@ -658,7 +712,7 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash", + "foldhash 0.2.0", ] [[package]] @@ -682,6 +736,7 @@ name = "horizon-client" version = "0.1.0" dependencies = [ "ab_glyph", + "arboard", "bytemuck", "cpal", "glam", @@ -1039,6 +1094,15 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "num-derive" version = "0.4.2" @@ -1123,6 +1187,18 @@ dependencies = [ "objc2-quartz-core 0.2.2", ] +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-audio-toolbox" version = "0.3.2" @@ -1213,6 +1289,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ + "bitflags 2.13.2", "dispatch2", "objc2 0.6.5", "objc2-core-foundation", @@ -1292,7 +1369,7 @@ checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" dependencies = [ "block2 0.5.1", "objc2 0.5.3", - "objc2-app-kit", + "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", ] @@ -1427,6 +1504,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "owned_ttf_parser" version = "0.25.1" @@ -1465,6 +1552,17 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -2099,6 +2197,17 @@ version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + [[package]] name = "ttf-parser" version = "0.25.1" @@ -2815,7 +2924,7 @@ dependencies = [ "memmap2", "ndk", "objc2 0.5.3", - "objc2-app-kit", + "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", "objc2-ui-kit", "orbclient", @@ -2858,6 +2967,24 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wl-clipboard-rs" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.5", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "x11-dl" version = "2.21.0" diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 7c2cacd86..23cd4cafb 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -24,6 +24,7 @@ symphonia = { version = "0.5", default-features = false, features = ["ogg", "vor miniz_oxide = "0.8" ab_glyph = "0.2.32" horizon-theme = { path = "../horizon-theme" } +arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } [features] # Records the call sites of mob random draws (`mob_ai_probe` traces). diff --git a/crates/horizon-client/src/debug_keys.rs b/crates/horizon-client/src/debug_keys.rs new file mode 100644 index 000000000..43e9c10bf --- /dev/null +++ b/crates/horizon-client/src/debug_keys.rs @@ -0,0 +1,456 @@ +//! The debug keys (26.3 `KeyboardHandler`): `key.debug.modifier` (F3) held +//! with another key runs a debug action (`handleDebugKeys`), released alone +//! it toggles the debug overlay (`key.debug.overlay`, F3 too by default); +//! with Escape it pauses without the menu; held with `key.debug.crash` (C) +//! for ten seconds it crashes the game (`tick`). +use crate::keybinds::KeyBinds; + +/// A debug mapping's action, as `handleDebugKeys` tests them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DebugAction { + ReloadChunks, + ShowHitboxes, + ClearChat, + ShowChunkBorders, + AdvancedTooltips, + CopyRecreateCommand, + Spectate, + SwitchGameMode, + DebugOptions, + FocusPause, + DumpDynamicTextures, + ReloadResourcePacks, + Profiling, + CopyLocation, + DumpVersion, + ProfilingChart, + FpsCharts, + NetworkCharts, + LightmapTexture, + ImprovedTransparency, +} + +/// The mappings `handleDebugKeys` tests, in its order. +pub const ACTIONS: [(&str, DebugAction); 20] = [ + ("key.debug.reloadChunk", DebugAction::ReloadChunks), + ("key.debug.showHitboxes", DebugAction::ShowHitboxes), + ("key.debug.clearChat", DebugAction::ClearChat), + ("key.debug.showChunkBorders", DebugAction::ShowChunkBorders), + ( + "key.debug.showAdvancedTooltips", + DebugAction::AdvancedTooltips, + ), + ( + "key.debug.copyRecreateCommand", + DebugAction::CopyRecreateCommand, + ), + ("key.debug.spectate", DebugAction::Spectate), + ("key.debug.switchGameMode", DebugAction::SwitchGameMode), + ("key.debug.debugOptions", DebugAction::DebugOptions), + ("key.debug.focusPause", DebugAction::FocusPause), + ( + "key.debug.dumpDynamicTextures", + DebugAction::DumpDynamicTextures, + ), + ( + "key.debug.reloadResourcePacks", + DebugAction::ReloadResourcePacks, + ), + ("key.debug.profiling", DebugAction::Profiling), + ("key.debug.copyLocation", DebugAction::CopyLocation), + ("key.debug.dumpVersion", DebugAction::DumpVersion), + ("key.debug.profilingChart", DebugAction::ProfilingChart), + ("key.debug.fpsCharts", DebugAction::FpsCharts), + ("key.debug.networkCharts", DebugAction::NetworkCharts), + ("key.debug.lightmapTexture", DebugAction::LightmapTexture), + ( + "key.debug.improvedTransparency", + DebugAction::ImprovedTransparency, + ), +]; + +/// GLFW's key actions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyAction { + Release, + Press, + Repeat, +} + +/// The screen open when a key reaches the game (after the screen itself +/// passed on it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OpenScreen { + None, + /// `PauseScreen` without its menu (F3+Escape). + PauseWithoutMenu, + GameModeSwitcher, + Other, +} + +/// What the game does for `KeyboardHandler.keyPress`. +pub trait DebugHost { + fn screen(&self) -> OpenScreen; + /// `DebugScreenEntries.toggleDebugOverlay`. + fn toggle_overlay(&mut self); + /// `Minecraft.pauseGame(suppressPauseMenu)`. + fn pause_game(&mut self, without_menu: bool); + /// One matching mapping of `handleDebugKeys`; whether its condition held + /// (vanilla's `debugAction = true`). `shift`: `event.hasShiftDown()`. + fn debug_action(&mut self, action: DebugAction, shift: bool) -> bool; +} + +/// What `KeyboardHandler.tick` reports while the debug crash keys are held. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CrashNotice { + /// `debug.crash.message`, a second after the keys went down. + Message, + /// `debug.crash.warning` with the seconds left. + Warning(i32), + /// "Manually triggered debug crash". + Crash, +} + +/// `KeyboardHandler`'s state, with the down state of `keyDebugModifier`. +#[derive(Clone, Debug, Default)] +pub struct DebugKeys { + pub used_debug_key_as_modifier: bool, + /// `debugCrashKeyTime`: when the crash keys went down (milliseconds), + /// 0 never, -1 released. + pub crash_key_time: i64, + pub crash_key_reported_time: i64, + pub crash_key_reported_count: i64, + /// `keyDebugModifier.isDown()`. + pub modifier_down: bool, +} + +impl DebugKeys { + /// `keyPress` once the open screen (if any) did not take the key. `key` + /// is the physical key's name (`key.keyboard.f3`); `crash_key_down` + /// whether the crash mapping's key is held (`InputConstants.isKeyDown`). + /// Returns whether the key goes on to the game's key mappings + /// (`KeyMapping.set(key, true)` and `click`): only without a screen and + /// when it ran no debug action. + #[allow(clippy::too_many_arguments)] + pub fn key_press( + &mut self, + host: &mut impl DebugHost, + binds: &KeyBinds, + key: &str, + action: KeyAction, + shift: bool, + crash_key_down: bool, + now: i64, + ) -> bool { + let modifier = binds.get("key.debug.modifier"); + let overlay = binds.get("key.debug.overlay"); + let same = modifier == overlay; + let modifier_down = self.modifier_down; + let crash = binds.get("key.debug.crash") != "key.keyboard.unknown" && crash_key_down; + if self.crash_key_time > 0 { + if !crash || !modifier_down { + self.crash_key_time = -1; + } + } else if crash && modifier_down { + self.used_debug_key_as_modifier = same; + self.crash_key_time = now; + self.crash_key_reported_time = now; + self.crash_key_reported_count = 0; + } + let screen = host.screen(); + let handles_game = screen == OpenScreen::None; + let handles_global = handles_game + || matches!( + screen, + OpenScreen::PauseWithoutMenu | OpenScreen::GameModeSwitcher + ); + if same && key == modifier && action == KeyAction::Release { + if self.used_debug_key_as_modifier { + self.used_debug_key_as_modifier = false; + } else { + host.toggle_overlay(); + } + } else if !same && key == overlay && action == KeyAction::Press { + host.toggle_overlay(); + } + if action == KeyAction::Release { + // KeyMapping.set(key, false). + if key == modifier { + self.modifier_down = false; + } + return false; + } + let mut did = false; + if handles_global && key == "key.keyboard.escape" { + host.pause_game(modifier_down); + did = modifier_down; + } else if modifier_down { + did = self.handle_debug_keys(host, binds, key, shift, now); + } + if same { + self.used_debug_key_as_modifier |= did; + } + // KeyMapping.set(key, !did) for the game, setDown(!did) behind a screen. + if key == modifier { + self.modifier_down = !did; + } + handles_game && !did + } + /// `handleDebugKeys`: every debug mapping on this key, in order. + fn handle_debug_keys( + &mut self, + host: &mut impl DebugHost, + binds: &KeyBinds, + key: &str, + shift: bool, + now: i64, + ) -> bool { + // Once the crash keys have been down a tenth of a second. + if self.crash_key_time > 0 && self.crash_key_time < now - 100 { + return true; + } + let mut did = false; + for (name, action) in ACTIONS { + if binds.get(name) == key { + did |= host.debug_action(action, shift); + } + } + did + } + /// `KeyboardHandler.tick`. + pub fn tick(&mut self, now: i64) -> Option { + if self.crash_key_time <= 0 { + return None; + } + let remaining = 10000 - (now - self.crash_key_time); + let reported = now - self.crash_key_reported_time; + if remaining < 0 { + return Some(CrashNotice::Crash); + } + if reported >= 1000 { + let notice = if self.crash_key_reported_count == 0 { + CrashNotice::Message + } else { + // Mth.ceil(remainingTime / 1000.0F). + CrashNotice::Warning((remaining as f32 / 1000.0).ceil() as i32) + }; + self.crash_key_reported_time = now; + self.crash_key_reported_count += 1; + return Some(notice); + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Host { + screen: Option, + overlay: u32, + paused: Vec, + actions: Vec<(DebugAction, bool)>, + /// Actions whose condition fails (no player, reduced debug info...). + refused: Vec, + } + impl DebugHost for Host { + fn screen(&self) -> OpenScreen { + self.screen.unwrap_or(OpenScreen::None) + } + fn toggle_overlay(&mut self) { + self.overlay += 1; + } + fn pause_game(&mut self, without_menu: bool) { + self.paused.push(without_menu); + } + fn debug_action(&mut self, action: DebugAction, shift: bool) -> bool { + self.actions.push((action, shift)); + !self.refused.contains(&action) + } + } + const F3: &str = "key.keyboard.f3"; + + fn press(k: &mut DebugKeys, h: &mut Host, b: &KeyBinds, key: &str, now: i64) -> bool { + k.key_press(h, b, key, KeyAction::Press, false, false, now) + } + fn release(k: &mut DebugKeys, h: &mut Host, b: &KeyBinds, key: &str) -> bool { + k.key_press(h, b, key, KeyAction::Release, false, false, 0) + } + + #[test] + fn f3_alone_toggles_the_overlay_on_release() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + // The F3 press goes to the game's mappings (key.debug.* are down now). + assert!(press(&mut k, &mut h, &b, F3, 0)); + assert!(k.modifier_down); + assert_eq!(h.overlay, 0); + assert!(!release(&mut k, &mut h, &b, F3)); + assert_eq!(h.overlay, 1); + assert!(!k.modifier_down); + } + + #[test] + fn a_combination_runs_its_action_and_keeps_the_overlay() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + press(&mut k, &mut h, &b, F3, 0); + // F3+G: the action, and G does not reach the game. + assert!(!press(&mut k, &mut h, &b, "key.keyboard.g", 10)); + assert_eq!(h.actions, [(DebugAction::ShowChunkBorders, false)]); + release(&mut k, &mut h, &b, "key.keyboard.g"); + release(&mut k, &mut h, &b, F3); + assert_eq!(h.overlay, 0); + // The next F3 alone toggles again. + press(&mut k, &mut h, &b, F3, 20); + release(&mut k, &mut h, &b, F3); + assert_eq!(h.overlay, 1); + } + + #[test] + fn c_copies_the_location_and_both_c_mappings_share_the_key() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + press(&mut k, &mut h, &b, F3, 0); + k.key_press( + &mut h, + &b, + "key.keyboard.c", + KeyAction::Press, + true, + true, + 5, + ); + assert_eq!(h.actions, [(DebugAction::CopyLocation, true)]); + // The crash keys are down: from a tenth of a second on, debug keys + // are swallowed. + assert_eq!(k.crash_key_time, 5); + k.key_press( + &mut h, + &b, + "key.keyboard.c", + KeyAction::Repeat, + false, + true, + 50, + ); + assert_eq!(h.actions.len(), 2); + assert!(!k.key_press( + &mut h, + &b, + "key.keyboard.c", + KeyAction::Repeat, + false, + true, + 200 + )); + assert_eq!(h.actions.len(), 2); + } + + #[test] + fn held_crash_keys_warn_every_second_then_crash() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + press(&mut k, &mut h, &b, F3, 0); + k.key_press( + &mut h, + &b, + "key.keyboard.c", + KeyAction::Press, + false, + true, + 1000, + ); + assert_eq!(k.tick(1500), None); + assert_eq!(k.tick(2000), Some(CrashNotice::Message)); + assert_eq!(k.tick(2999), None); + assert_eq!(k.tick(3000), Some(CrashNotice::Warning(8))); + assert_eq!(k.tick(4100), Some(CrashNotice::Warning(7))); + assert_eq!(k.tick(11_000), Some(CrashNotice::Warning(0))); + assert_eq!(k.tick(11_001), Some(CrashNotice::Crash)); + // Releasing either key stops it on the next key event. + let mut k2 = DebugKeys::default(); + press(&mut k2, &mut h, &b, F3, 0); + k2.key_press( + &mut h, + &b, + "key.keyboard.c", + KeyAction::Press, + false, + true, + 1000, + ); + k2.key_press( + &mut h, + &b, + "key.keyboard.c", + KeyAction::Release, + false, + false, + 1200, + ); + assert_eq!(k2.crash_key_time, -1); + assert_eq!(k2.tick(20_000), None); + // The crash used F3 as a modifier: its release does not toggle the overlay. + release(&mut k2, &mut h, &b, F3); + assert_eq!(h.overlay, 0); + } + + #[test] + fn refused_actions_do_not_count() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + h.refused.push(DebugAction::ShowHitboxes); + press(&mut k, &mut h, &b, F3, 0); + // F3+B without a player (or with reduced debug info): B reaches the + // game and F3's release still toggles the overlay. + assert!(press(&mut k, &mut h, &b, "key.keyboard.b", 1)); + release(&mut k, &mut h, &b, F3); + assert_eq!(h.overlay, 1); + } + + #[test] + fn escape_pauses_with_or_without_the_menu() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + assert!(press(&mut k, &mut h, &b, "key.keyboard.escape", 0)); + press(&mut k, &mut h, &b, F3, 1); + assert!(!press(&mut k, &mut h, &b, "key.keyboard.escape", 2)); + assert_eq!(h.paused, [false, true]); + release(&mut k, &mut h, &b, F3); + assert_eq!(h.overlay, 0); + // Behind another screen, Escape is the screen's. + h.screen = Some(OpenScreen::Other); + press(&mut k, &mut h, &b, "key.keyboard.escape", 3); + assert_eq!(h.paused.len(), 2); + } + + #[test] + fn behind_a_screen_combinations_work_but_keys_stay_with_the_screen() { + let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + h.screen = Some(OpenScreen::Other); + assert!(!press(&mut k, &mut h, &b, F3, 0)); + assert!(k.modifier_down); + assert!(!press(&mut k, &mut h, &b, "key.keyboard.h", 1)); + assert_eq!(h.actions, [(DebugAction::AdvancedTooltips, false)]); + release(&mut k, &mut h, &b, F3); + assert_eq!(h.overlay, 0); + } + + #[test] + fn a_separate_overlay_key_toggles_on_press() { + let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + b.set("key.debug.overlay", "key.keyboard.f7"); + press(&mut k, &mut h, &b, "key.keyboard.f7", 0); + assert_eq!(h.overlay, 1); + press(&mut k, &mut h, &b, F3, 1); + release(&mut k, &mut h, &b, F3); + assert_eq!(h.overlay, 1); + } + + #[test] + fn rebound_mappings_follow_their_keys() { + let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + b.set("key.debug.showChunkBorders", "key.keyboard.k"); + press(&mut k, &mut h, &b, F3, 0); + assert!(press(&mut k, &mut h, &b, "key.keyboard.g", 1)); + press(&mut k, &mut h, &b, "key.keyboard.k", 2); + assert_eq!(h.actions, [(DebugAction::ShowChunkBorders, false)]); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2e9dadd03..3cd8d5105 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -25,6 +25,7 @@ mod copper_golems; mod creaking; mod creatures; mod crossbow; +mod debug_keys; mod dedicated; mod dispense_fixture; mod dispenser; @@ -829,6 +830,18 @@ struct Game<'a> { /// This world is open to the network (game/lan.rs). lan: Option, world_options: Option, + /// KeyboardHandler's debug key state (game/debug_keys.rs), the physical + /// keys held, and the debug renderers F3+B and F3+G switch on. + debug_keys: horizon_client::debug_keys::DebugKeys, + show_hitboxes: bool, + show_chunk_borders: bool, + /// PauseScreen.showPauseMenu (false after F3+Escape). + pause_menu: bool, + /// MultiPlayerGameMode.previousLocalPlayerMode (F3+N goes back to it). + previous_mode: Option, + clipboard: Option, + /// The text last put on the clipboard (reported by `horizon-ctl status`). + copied: Option, /// The world was saved for the application ending (`save_for_exit`). saved_for_exit: bool, /// The block a guest is acting on (game/lan_actions.rs). @@ -2630,6 +2643,7 @@ impl Game<'_> { Ok(()) } fn tick(&mut self) -> Result<()> { + self.tick_debug_keys()?; if self.remote.is_some() { return self.tick_remote(); } @@ -3339,7 +3353,20 @@ impl Game<'_> { self.draw_chat(&mut batch); self.draw_tab_list(&mut batch); match self.screen { - Screen::Paused => self.draw_pause_menu(&mut batch), + Screen::Paused if self.pause_menu => self.draw_pause_menu(&mut batch), + // PauseScreen(false): only its title, at the top. + Screen::Paused => { + let title = self.translate("menu.paused", "Game Paused"); + let tw = HudBatch::text_width(&self.res.atlas, &title); + batch.text( + &self.res.atlas, + &title, + ((batch.width / 2.0).floor() - (tw / 2.0).floor()).floor(), + 10.0, + u32::MAX, + true, + ); + } Screen::Dead => self.draw_death_screen(&mut batch), Screen::Stats => self.draw_stats(&mut batch), Screen::Advancements => self.draw_advancements(&mut batch), @@ -7522,6 +7549,18 @@ impl Game<'_> { sky.sky_color = [0.9, 0.9, 1.0]; sky.sky_light_factor = 1.0; } + // DebugRenderer: chunk borders and hitboxes (F3+G, F3+B). + let (debug_lines, debug_lines_on_top) = if self.show_hitboxes || self.show_chunk_borders { + let g = self.debug_gizmos(alpha as f32); + let view = horizon_client::camera::view_matrix(view_yaw, view_pitch); + let at = camera.to_array(); + ( + horizon_client::gizmos::camera_relative(&g.lines, at, view), + horizon_client::gizmos::camera_relative(&g.on_top, at, view), + ) + } else { + (Vec::new(), Vec::new()) + }; // LevelRenderer.renderHitOutline: the outline shape's edges. let outline = if self.screen == Screen::Playing && !self.spectator() { self.pick() @@ -7674,6 +7713,8 @@ impl Game<'_> { }), dark_disc: self.dark_disc(camera), outline, + debug_lines: &debug_lines, + debug_lines_on_top: &debug_lines_on_top, hud: &hud, entities: &entities, additive: &additive, @@ -7764,6 +7805,7 @@ impl Game<'_> { Screen::Options => self.options_key(KeyCode::Escape, None)?, Screen::Playing => { self.screen = Screen::Paused; + self.pause_menu = true; self.capture(false); } Screen::Creative => { @@ -7774,6 +7816,7 @@ impl Game<'_> { Screen::Paused | Screen::Inventory => { self.close_container(); self.screen = Screen::Playing; + self.pause_menu = true; self.capture(true); } Screen::Dead => {} @@ -7833,7 +7876,6 @@ impl Game<'_> { } _ => {} }, - KeyCode::F3 => self.debug = !self.debug, // key.swapOffhand: ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND. KeyCode::KeyF if self.screen == Screen::Playing => { std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]); @@ -8046,6 +8088,23 @@ impl ApplicationHandler for Game<'_> { if let WindowEvent::Focused(false) = &event { self.physical_keys.clear(); } + // KeyboardHandler.keyPress: the debug keys come before the game's. + if let WindowEvent::KeyboardInput { + event: key_event, .. + } = &event + && let PhysicalKey::Code(key) = key_event.physical_key + && self.title.is_none() + { + use horizon_client::debug_keys::KeyAction; + let action = match (key_event.state, key_event.repeat) { + (ElementState::Released, _) => KeyAction::Release, + (_, false) => KeyAction::Press, + (_, true) => KeyAction::Repeat, + }; + if self.debug_key(key, action) { + return; + } + } if matches!( event, WindowEvent::KeyboardInput { .. } @@ -8086,6 +8145,7 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Playing && self.player.is_some() && !self.options.no_pause + && self.settings.file.bool("pauseOnLostFocus") && self.book.is_none() && self.sign_edit.is_none() { @@ -8264,7 +8324,7 @@ impl ApplicationHandler for Game<'_> { Screen::Creative if button == MouseButton::Left => { self.creative_screen.release(); } - Screen::Paused if pressed => self.pause_click()?, + Screen::Paused if pressed && self.pause_menu => self.pause_click()?, Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() } @@ -8965,6 +9025,13 @@ pub fn run() -> Result<()> { remote: None, lan: None, world_options: None, + debug_keys: Default::default(), + show_hitboxes: false, + show_chunk_borders: false, + pause_menu: true, + previous_mode: None, + clipboard: None, + copied: None, saved_for_exit: false, forced_hit: None, lan_events: Vec::new(), diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index e90b73ba8..b2351a723 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -271,7 +271,7 @@ pub(super) enum Handled { } impl Game<'_> { - fn state_string(&self, state: BlockStateId) -> String { + pub(super) fn state_string(&self, state: BlockStateId) -> String { let Some(s) = self.res.assets.registry.state(state) else { return "?".into(); }; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 77bd44325..aff5ad2a1 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -705,7 +705,7 @@ impl Game<'_> { _ => Ok(0), } } - fn set_game_mode(&mut self, mode: GameMode) -> bool { + pub(super) fn set_game_mode(&mut self, mode: GameMode) -> bool { if self.mode == mode { return false; } diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index 0b437d692..6429b8089 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -954,16 +954,11 @@ impl Game<'_> { Ok(1) } - /// `VersionCommand`: Horizon reports the version it implements. - pub(super) fn cmd_version(&mut self) -> R { - let send = |g: &mut Self, t: Text| { - if !g.command_source.is_some_and(|s| s.silent) { - g.system_message(t); - } - }; - send(self, Text::translate("commands.version.header", &[])); + /// `VersionCommand.dumpVersion`'s lines: Horizon reports the version it + /// implements. + pub(in crate::game) fn version_lines(&self) -> Vec { let protocol = horizon_protocol::PROTOCOL_VERSION; - for (key, args) in [ + let mut lines: Vec = [ ("commands.version.id", vec![Text::literal(VERSION_ID)]), ("commands.version.name", vec![Text::literal(VERSION_ID)]), ("commands.version.data", vec![num(DATA_VERSION)]), @@ -981,20 +976,28 @@ impl Game<'_> { vec![Text::literal("97.1")], ), ("commands.version.pack.data", vec![Text::literal("121.0")]), - ] { - send(self, Text::translate(key, &args)); + ] + .into_iter() + .map(|(key, args)| Text::translate(key, &args)) + .collect(); + lines.push(Text::translate( + if STABLE { + "commands.version.stable.yes" + } else { + "commands.version.stable.no" + }, + &[], + )); + lines + } + /// `VersionCommand`. + pub(super) fn cmd_version(&mut self) -> R { + if !self.command_source.is_some_and(|s| s.silent) { + self.system_message(Text::translate("commands.version.header", &[])); + for line in self.version_lines() { + self.system_message(line); + } } - send( - self, - Text::translate( - if STABLE { - "commands.version.stable.yes" - } else { - "commands.version.stable.no" - }, - &[], - ), - ); Ok(1) } } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index ffa1e4dda..57d3abaa4 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -141,6 +141,26 @@ impl Game<'_> { "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; self.require_world()?; + // KeyboardHandler.keyPress: the debug keys see the physical key first. + let physical = key; + { + use horizon_client::debug_keys::KeyAction; + let action = arg(2)?; + if action != "up" { + self.physical_keys.insert(key); + if self.debug_key(key, KeyAction::Press) { + if action == "tap" { + self.physical_keys.remove(&key); + self.debug_key(key, KeyAction::Release); + } + return ok(); + } + } + if action == "up" { + self.physical_keys.remove(&key); + self.debug_key(key, KeyAction::Release); + } + } // Physical key presses follow the key binds like the keyboard does. let key = if matches!(self.screen, Screen::Chat | Screen::Options) { key @@ -171,7 +191,8 @@ impl Game<'_> { "tap" => { self.control_key_down(key)?; self.keys.remove(&key); - self.physical_keys.remove(&key); + self.physical_keys.remove(&physical); + self.debug_key(physical, horizon_client::debug_keys::KeyAction::Release); } other => { return Err( @@ -561,6 +582,15 @@ impl Game<'_> { }); json!({ "screen": self.screen_name(), + "debug": { + "overlay": self.debug, + "hitboxes": self.show_hitboxes, + "chunk_borders": self.show_chunk_borders, + "pause_menu": self.pause_menu, + "advanced_tooltips": self.settings.file.bool("advancedItemTooltips"), + "pause_on_lost_focus": self.settings.file.bool("pauseOnLostFocus"), + "clipboard": self.copied, + }, "dimension": self.dim.id(), "creative": self.creative, "player": player, diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs new file mode 100644 index 000000000..1fb4004b9 --- /dev/null +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -0,0 +1,503 @@ +//! The debug keys in the game (26.3 `KeyboardHandler.keyPress`, +//! `handleDebugKeys` and `tick`): F3 combinations, F3+Escape, the held +//! debug-crash keys, and the debug renderers they switch on. +use super::{Game, Screen}; +use horizon_client::{ + Result, + command::args::GameMode, + debug_keys::{CrashNotice, DebugAction, DebugHost, KeyAction, OpenScreen}, + gizmos::Gizmos, + keybinds, + text::Text, +}; +use horizon_core::geometry::Axis; +use winit::keyboard::KeyCode; + +/// `ChatFormatting.YELLOW` and `RED`. +const YELLOW: u32 = 0xFF_FF55; +const RED: u32 = 0xFF_5555; + +/// The game as `KeyboardHandler` sees it while it runs one key event. +struct Host<'g, 'a> { + game: &'g mut Game<'a>, +} + +impl DebugHost for Host<'_, '_> { + fn screen(&self) -> OpenScreen { + self.game.open_screen() + } + fn toggle_overlay(&mut self) { + self.game.debug = !self.game.debug; + } + fn pause_game(&mut self, without_menu: bool) { + // Gui.setPauseScreen: PauseScreen(false) only when the game really + // pauses (single player, not open to the network). Escape alone opens + // the menu as it always has (key_pressed). + let g = &mut *self.game; + if without_menu && g.screen == Screen::Playing { + g.pause_menu = !(g.remote.is_none() && g.lan.is_none()); + g.screen = Screen::Paused; + g.capture(false); + g.mining = None; + } + } + fn debug_action(&mut self, action: DebugAction, shift: bool) -> bool { + self.game.run_debug_action(action, shift) + } +} + +impl Game<'_> { + fn open_screen(&self) -> OpenScreen { + match self.screen { + Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None, + Screen::Paused if !self.pause_menu => OpenScreen::PauseWithoutMenu, + _ => OpenScreen::Other, + } + } + /// A physical key event (already in `physical_keys`) before the game's + /// own handling. Returns true when it is used up (a debug combination, + /// F3 itself, F3+Escape). + pub(super) fn debug_key(&mut self, key: KeyCode, action: KeyAction) -> bool { + let Some(name) = keybinds::key_name(key) else { + return false; + }; + let pressed = action != KeyAction::Release; + // Screens with a text box take every key press first + // (EditBox.keyPressed); releases still reach KeyboardHandler. + let typing = matches!( + self.screen, + Screen::Chat | Screen::Options | Screen::WorldOptions + ) || self.sign_edit.is_some() + || self.book.is_some() + || (self.screen == Screen::Creative && self.creative_screen.tab().search) + || self.recipe_search_focused() + || self.station_typing() + || self.remote_chat_open(); + // Container screens use Escape, the inventory key and the hotbar and + // drop keys first; any other screen closes on Escape. + let screen_key = match self.screen { + Screen::Inventory | Screen::Creative => matches!( + key, + KeyCode::Escape + | KeyCode::KeyE + | KeyCode::KeyF + | KeyCode::KeyQ + | KeyCode::Digit1 + | KeyCode::Digit2 + | KeyCode::Digit3 + | KeyCode::Digit4 + | KeyCode::Digit5 + | KeyCode::Digit6 + | KeyCode::Digit7 + | KeyCode::Digit8 + | KeyCode::Digit9 + ), + Screen::Playing => false, + _ => key == KeyCode::Escape, + }; + if pressed && (typing || screen_key) { + return false; + } + let crash_down = keybinds::key_code(self.settings.keys.get("key.debug.crash")) + .is_some_and(|k| self.physical_keys.contains(&k)); + let shift = self.physical_keys.contains(&KeyCode::ShiftLeft) + || self.physical_keys.contains(&KeyCode::ShiftRight); + let now = self.debug_millis(); + let binds = self.settings.keys.clone(); + let mut keys = std::mem::take(&mut self.debug_keys); + let modifier_was_down = keys.modifier_down; + let to_game = keys.key_press( + &mut Host { game: self }, + &binds, + name, + action, + shift, + crash_down, + now, + ); + self.debug_keys = keys; + if !pressed { + return false; + } + // The debug modifier does nothing else. + if name == binds.get("key.debug.modifier") || name == binds.get("key.debug.overlay") { + return true; + } + if self.open_screen() == OpenScreen::None { + !to_game + } else { + modifier_was_down + } + } + /// `Util.getMillis` (positive: KeyboardHandler treats 0 as unset). + fn debug_millis(&self) -> i64 { + self.started.elapsed().as_millis() as i64 + 1_000_000 + } + /// `KeyboardHandler.tick`: the debug crash countdown. + pub(super) fn tick_debug_keys(&mut self) -> Result<()> { + let now = self.debug_millis(); + match self.debug_keys.tick(now) { + None => {} + Some(CrashNotice::Message) => { + let args = [ + self.key_text("key.debug.modifier"), + self.key_text("key.debug.crash"), + ]; + self.debug_feedback(Text::translate("debug.crash.message", &args)); + } + Some(CrashNotice::Warning(seconds)) => self.debug_warning(Text::translate( + "debug.crash.warning", + &[Text::literal(seconds.to_string())], + )), + Some(CrashNotice::Crash) => { + // Minecraft.emergencySaveAndCrash: the world is saved, then the + // game stops with the report. + eprintln!( + "---- Minecraft Crash Report ----\n\nDescription: Manually triggered debug crash\n\njava.lang.Throwable: Manually triggered debug crash" + ); + let _ = self.save_game(); + return Err("Manually triggered debug crash".into()); + } + } + Ok(()) + } + /// `KeyMapping.getTranslatedKeyMessage`. + fn key_text(&self, mapping: &str) -> Text { + keybinds::display_name(self.settings.keys.get(mapping)) + } + /// `KeyboardHandler.decorateDebugComponent`: `[Debug]:` in bold, a space, + /// the message, shown with `Minecraft.showDebugChat`. + fn debug_decorated(&mut self, color: u32, message: Text) { + let prefix = Text::translate("debug.prefix", &[]) + .with_color(color) + .bold(); + self.system_message( + Text::empty() + .append(prefix) + .append(Text::literal(" ")) + .append(message), + ); + } + fn debug_feedback(&mut self, message: Text) { + self.debug_decorated(YELLOW, message); + } + fn debug_warning(&mut self, message: Text) { + self.debug_decorated(RED, message); + } + fn debug_translated(&mut self, key: &str) { + self.debug_feedback(Text::translate(key, &[])); + } + /// `LocalPlayer.isReducedDebugInfo`: the server's rule or the option. + fn reduced_debug_info(&self) -> bool { + self.settings.reduced_debug_info || self.ui.rules.bool("reduced_debug_info") + } + /// `Permissions.COMMANDS_GAMEMASTER` (`GameModeCommand.PERMISSION_CHECK`). + fn gamemaster(&self) -> bool { + self.ui.registries.permission >= 2 + } + fn toggle_option(&mut self, key: &str) -> bool { + let on = !self.settings.file.bool(key); + self.settings + .file + .set(key, horizon_client::options_file::V::Bool(on)); + self.settings.save(&Self::options_path()); + on + } + /// One matching mapping of `handleDebugKeys`; whether it counts. + fn run_debug_action(&mut self, action: DebugAction, shift: bool) -> bool { + let player = self.player.is_some() && !self.reduced_debug_info(); + match action { + DebugAction::ReloadChunks => { + // LevelExtractor.allChanged: every section is rebuilt. + let keys: Vec<(i32, i32)> = self.world.chunks.keys().copied().collect(); + for (x, z) in keys { + for sy in 0..horizon_client::chunk::HEIGHT / 16 { + self.world.dirty_sections.insert((x, sy, z)); + } + } + self.debug_translated("debug.reload_chunks.message"); + true + } + DebugAction::ShowHitboxes if player => { + self.show_hitboxes = !self.show_hitboxes; + self.debug_translated(if self.show_hitboxes { + "debug.show_hitboxes.on" + } else { + "debug.show_hitboxes.off" + }); + true + } + DebugAction::ClearChat => { + // ChatComponent.clearMessages(false): sent history stays. + self.ui.chat.clear(); + true + } + DebugAction::ShowChunkBorders if player => { + self.show_chunk_borders = !self.show_chunk_borders; + self.debug_translated(if self.show_chunk_borders { + "debug.chunk_boundaries.on" + } else { + "debug.chunk_boundaries.off" + }); + true + } + DebugAction::AdvancedTooltips => { + // The message comes before Options.save here. + let on = !self.settings.file.bool("advancedItemTooltips"); + self.debug_translated(if on { + "debug.advanced_tooltips.on" + } else { + "debug.advanced_tooltips.off" + }); + self.toggle_option("advancedItemTooltips"); + true + } + DebugAction::CopyRecreateCommand => { + if player { + self.copy_recreate_command(self.gamemaster(), !shift); + } + true + } + DebugAction::Spectate => { + if self.player.is_none() || !self.gamemaster() { + self.debug_translated("debug.creative_spectator.error"); + } else if self.mode != GameMode::Spectator { + self.change_game_mode(GameMode::Spectator); + } else { + let back = self.previous_mode.unwrap_or(GameMode::Creative); + self.change_game_mode(back); + } + true + } + DebugAction::SwitchGameMode if self.open_screen() == OpenScreen::None => { + // Minecraft.canSwitchGameMode and the permission; the + // GameModeSwitcherScreen itself is not drawn yet. + if self.player.is_none() || !self.gamemaster() { + self.debug_translated("debug.gamemodes.error"); + } + true + } + DebugAction::FocusPause => { + let on = self.toggle_option("pauseOnLostFocus"); + self.debug_translated(if on { + "debug.pause_focus.on" + } else { + "debug.pause_focus.off" + }); + true + } + DebugAction::ReloadResourcePacks => { + self.debug_translated("debug.reload_resourcepacks.message"); + self.reload_packs(); + true + } + DebugAction::CopyLocation if player => { + self.debug_translated("debug.copy_location.message"); + if let Some(p) = &self.player { + use horizon_client::java_text::format_fixed2 as f2; + let command = format!( + "/execute in {} run tp @s {} {} {} {} {}", + self.dim.id(), + f2(p.position.x), + f2(p.position.y), + f2(p.position.z), + f2(f64::from(self.yaw)), + f2(f64::from(self.pitch)), + ); + self.set_clipboard(&command); + } + true + } + DebugAction::DumpVersion => { + self.debug_translated("debug.version.header"); + for line in self.version_lines() { + self.system_message(line); + } + true + } + DebugAction::ImprovedTransparency => { + self.settings.improved_transparency = !self.settings.improved_transparency; + self.settings.save(&Self::options_path()); + self.apply_settings(); + self.debug_translated(if self.settings.improved_transparency { + "debug.improvedTransparency.on" + } else { + "debug.improvedTransparency.off" + }); + true + } + // Screens and overlays Horizon does not draw yet (the debug + // options screen, the profiler and its charts, the lightmap, the + // texture dump): the keys are used up as in vanilla. + DebugAction::DebugOptions + | DebugAction::DumpDynamicTextures + | DebugAction::Profiling + | DebugAction::ProfilingChart + | DebugAction::FpsCharts + | DebugAction::NetworkCharts + | DebugAction::LightmapTexture => true, + DebugAction::ShowHitboxes + | DebugAction::ShowChunkBorders + | DebugAction::SwitchGameMode + | DebugAction::CopyLocation => false, + } + } + /// `ServerboundChangeGameModePacket` handled by the integrated server: + /// `GameModeCommand.setGameMode` with its feedback. + pub(super) fn change_game_mode(&mut self, mode: GameMode) { + // On a server the packet decides; Horizon's client does not send it yet. + if self.remote.is_some() { + return; + } + if self.set_game_mode(mode) { + let name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); + self.feedback(Text::translate("commands.gamemode.success.self", &[name])); + } + } + /// `KeyboardHandler.copyRecreateCommand`: the targeted block or mob as a + /// `/setblock` or `/summon` command. In a single-player world the + /// server's data (no Shift) is the game's own. + fn copy_recreate_command(&mut self, add_nbt: bool, from_server: bool) { + use horizon_client::java_text::format_fixed2 as f2; + let side = if add_nbt && from_server { + "server" + } else { + "client" + }; + if self.entity_targeted() + && let Some((index, _)) = self.mob_hit() + { + let (id, pos, mob) = { + let m = &self.mobs[index]; + (m.kind.id.clone(), m.position, m.id) + }; + let mut command = format!("/summon {id} {} {} {}", f2(pos.x), f2(pos.y), f2(pos.z)); + if add_nbt && let Some(mut tag) = self.entity_nbt(super::commands::Target::Mob(mob)) { + if let horizon_world::nbt::Tag::Compound(c) = &mut tag { + for key in ["id", "UUID", "Pos"] { + c.remove(&key.into()); + } + } + command.push(' '); + command.push_str(&horizon_client::snbt::pretty(&tag).plain()); + } + self.set_clipboard(&command); + self.debug_translated(&format!("debug.inspect.{side}.entity")); + return; + } + let Some(hit) = self.pick() else { + return; + }; + let p = hit.pos; + let mut description = self.state_string(self.world.block(p[0], p[1], p[2])); + if add_nbt && let Some(e) = self.world.block_entities.get(&(p[0], p[1], p[2])) { + // BlockEntity.saveWithoutMetadata: no id or position. + let name = self.data_block_name(p); + let mut tag = horizon_client::save::encode_block_entity((p[0], p[1], p[2]), e, &name); + if let horizon_world::nbt::Tag::Compound(c) = &mut tag { + for key in ["id", "x", "y", "z", "keepPacked"] { + c.remove(&key.into()); + } + } + description.push_str(&horizon_client::snbt::to_snbt(&tag)); + } + self.set_clipboard(&format!( + "/setblock {} {} {} {description}", + p[0], p[1], p[2] + )); + self.debug_translated(&format!("debug.inspect.{side}.block")); + } + /// `KeyboardHandler.setClipboard`. + fn set_clipboard(&mut self, text: &str) { + if text.is_empty() { + return; + } + if self.clipboard.is_none() { + self.clipboard = arboard::Clipboard::new().ok(); + } + if let Some(c) = self.clipboard.as_mut() { + let _ = c.set_text(text.to_owned()); + } + self.copied = Some(text.to_owned()); + } + /// The debug renderers' gizmos for a frame (`DebugRenderer.emitGizmos`). + pub(super) fn debug_gizmos(&self, alpha: f32) -> Gizmos { + let mut g = Gizmos::default(); + if self.show_chunk_borders + && let Some(p) = &self.player + { + let block = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + let min_y = horizon_client::chunk::MIN_Y; + g.chunk_borders(block, min_y, min_y + horizon_client::chunk::HEIGHT - 1); + } + if !self.show_hitboxes { + return g; + } + let lerp = |a: f64, b: f64| a + f64::from(alpha) * (b - a); + let lerpf = |a: f32, b: f32| a + alpha * (b - a); + for m in &self.mobs { + if m.removed || m.has_effect("minecraft:invisibility") { + continue; + } + let pos = [ + lerp(m.previous.x, m.position.x), + lerp(m.previous.y, m.position.y), + lerp(m.previous.z, m.position.z), + ]; + let view = ( + lerpf(m.previous_head_pitch, m.head_pitch), + lerpf(m.previous_head_yaw, m.head_yaw), + ); + g.hitbox( + pos, + (m.width(), m.height()), + m.eye_height() as f32, + true, + view, + ); + } + for item in &self.dropped { + let pos = [ + lerp(item.previous.x, item.position.x), + lerp(item.previous.y, item.position.y), + lerp(item.previous.z, item.position.z), + ]; + // EntityType.ITEM: 0.25 by 0.25, eyes at 0.2125. + g.hitbox(pos, (0.25, 0.25), 0.2125, false, (0.0, 0.0)); + } + // The dragon's parts. + for (id, b) in self.special_targets() { + if (super::dragon::SPECIAL..super::dragon::SPECIAL + 8).contains(&id) { + g.cuboid( + [b.min(Axis::X), b.min(Axis::Y), b.min(Axis::Z)], + [b.max(Axis::X), b.max(Axis::Y), b.max(Axis::Z)], + horizon_client::gizmos::DRAGON_PART, + horizon_client::gizmos::STROKE_WIDTH, + ); + } + } + // The player's own, unless the camera is in its head. + if !self.camera_type.first_person() + && let Some(p) = &self.player + { + let d = p.dimensions; + let pos = [ + lerp(self.previous_position.x, p.position.x), + lerp(self.previous_position.y, p.position.y), + lerp(self.previous_position.z, p.position.z), + ]; + g.hitbox( + pos, + (d.width, d.height), + d.eye_height, + true, + (self.pitch, self.yaw), + ); + } + g + } +} diff --git a/crates/horizon-client/src/game/game_mode.rs b/crates/horizon-client/src/game/game_mode.rs index 43fda6617..902220115 100644 --- a/crates/horizon-client/src/game/game_mode.rs +++ b/crates/horizon-client/src/game/game_mode.rs @@ -31,6 +31,10 @@ impl Game<'_> { /// `ServerPlayer.setGameMode` and `GameType.updatePlayerAbilities`. pub(super) fn set_mode(&mut self, mode: GameMode) { let was_spectator = self.spectator(); + // MultiPlayerGameMode.setLocalMode: the mode it leaves. + if mode != self.mode { + self.previous_mode = Some(self.mode); + } self.mode = mode; self.creative = mode == GameMode::Creative; // GameType.updatePlayerAbilities applies at once. diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index e414a719b..5ad7a7f22 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -119,7 +119,7 @@ impl Game<'_> { } /// Whether an attack would hit an entity rather than the block behind /// it: the crosshair's `EntityHitResult`. - fn entity_targeted(&self) -> bool { + pub(super) fn entity_targeted(&self) -> bool { let before = |d: Option| d.is_some_and(|d| self.before_block(d)); before(self.painting_hit().map(|h| h.1)) || before(self.frame_hit().map(|h| h.1)) diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 3c710c91e..b6767bade 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -11,7 +11,7 @@ use horizon_client::{ use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen}; impl Game<'_> { - fn options_path() -> std::path::PathBuf { + pub(super) fn options_path() -> std::path::PathBuf { std::env::current_dir() .unwrap_or_default() .join("options.txt") diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 63756daa1..96a4dc6c4 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -54,7 +54,10 @@ fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] { impl Game<'_> { /// Whether the pause menu is drawn in Horizon's style (over a blurred world). pub(super) fn horizon_pause(&self) -> bool { - self.screen == Screen::Paused && self.title.is_none() && horizon_client::ui_theme::horizon() + self.screen == Screen::Paused + && self.pause_menu + && self.title.is_none() + && horizon_client::ui_theme::horizon() } fn pause_labels(&self) -> (String, &'static str) { let world = if self.remote.is_some() { diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 5191d3ea2..bdf8ae4a7 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1928,8 +1928,9 @@ impl Game<'_> { "selected": s.selected, }) } + /// Options.advancedItemTooltips (F3+H). fn options_advanced_tooltips(&self) -> bool { - false + self.settings.file.bool("advancedItemTooltips") } /// `TooltipRenderUtil`: dark box with the purple border, first line spaced. pub(super) fn draw_tooltip_lines( diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 9b1af363a..c1f1e69da 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -144,6 +144,10 @@ pub struct Frame<'a> { pub dark_disc: bool, /// The hit block outline as line segments (from, to) in world space. pub outline: Vec<[f64; 6]>, + /// Debug gizmo lines (`gizmos::camera_relative`): depth tested, then + /// drawn over everything. + pub debug_lines: &'a [[f32; 8]], + pub debug_lines_on_top: &'a [[f32; 8]], pub hud: &'a HudBatch, /// CardinalLighting.Type.NETHER, otherwise DEFAULT. pub nether_lighting: bool, @@ -222,6 +226,12 @@ pub struct Renderer { sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, + /// Gizmo lines (`RenderTypes.linesTranslucentNoDepthWrite`) and the + /// always-on-top ones. + debug_lines: wgpu::RenderPipeline, + debug_lines_on_top: wgpu::RenderPipeline, + debug_line_buffer: wgpu::Buffer, + debug_line_capacity: u64, entity_pipeline: wgpu::RenderPipeline, crumbling_pipeline: wgpu::RenderPipeline, cloud_pipeline: wgpu::RenderPipeline, @@ -534,6 +544,13 @@ impl Renderer { attributes: &line_attributes, })]; let alpha_blend = wgpu::BlendState::ALPHA_BLENDING; + let debug_line_attributes = + wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3,2=>Unorm8x4,3=>Float32]; + let debug_line_buffers = [Some(wgpu::VertexBufferLayout { + array_stride: 32, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &debug_line_attributes, + })]; let pipeline = |label: &str, vertex: &str, fragment: &str, @@ -639,6 +656,28 @@ impl Renderer { true, Some(alpha_blend), ); + let debug_lines = pipeline( + "Debug lines", + "vs_debug_line", + "fs_debug_line", + &debug_line_buffers, + wgpu::PrimitiveTopology::TriangleStrip, + None, + false, + true, + Some(alpha_blend), + ); + let debug_lines_on_top = pipeline( + "Debug lines on top", + "vs_debug_line", + "fs_debug_line", + &debug_line_buffers, + wgpu::PrimitiveTopology::TriangleStrip, + None, + false, + false, + Some(alpha_blend), + ); let globals = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Horizon globals"), size: std::mem::size_of::() as u64, @@ -746,6 +785,12 @@ impl Renderer { usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + let debug_line_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Debug lines"), + size: 32 * 4096, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); let depth = Self::depth(&device, &config); let (atlas_pixels, atlas_width, atlas_height) = hud_atlas; let atlas = device.create_texture_with_data( @@ -1300,6 +1345,10 @@ impl Renderer { sky, dark_disc, lines, + debug_lines, + debug_lines_on_top, + debug_line_buffer, + debug_line_capacity: 4096, entity_pipeline, crumbling_pipeline, cloud_pipeline, @@ -1982,6 +2031,28 @@ impl Renderer { self.queue .write_buffer(&self.indirect, 0, bytemuck::cast_slice(&self.draws)); } + let debug_depth = frame.debug_lines.len() as u32; + let debug_top = frame.debug_lines_on_top.len() as u32; + if debug_depth + debug_top > 0 { + let needed = u64::from(debug_depth + debug_top); + if needed > self.debug_line_capacity { + self.debug_line_capacity = needed.next_power_of_two(); + self.debug_line_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Debug lines"), + size: 32 * self.debug_line_capacity, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + let all: Vec<[f32; 8]> = frame + .debug_lines + .iter() + .chain(frame.debug_lines_on_top) + .copied() + .collect(); + self.queue + .write_buffer(&self.debug_line_buffer, 0, bytemuck::cast_slice(&all)); + } let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize); if outline_edges > 0 { let lines = outline_vertices(&frame.outline[..outline_edges], camera); @@ -2157,6 +2228,16 @@ impl Renderer { pass.set_vertex_buffer(0, self.outline.slice(..)); pass.draw(0..4, 0..outline_edges as u32); } + if debug_depth > 0 { + pass.set_pipeline(&self.debug_lines); + pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..)); + pass.draw(0..4, 0..debug_depth); + } + if debug_top > 0 { + pass.set_pipeline(&self.debug_lines_on_top); + pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..)); + pass.draw(0..4, debug_depth..debug_depth + debug_top); + } pass.set_pipeline(&self.translucent); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); diff --git a/crates/horizon-client/src/gizmos.rs b/crates/horizon-client/src/gizmos.rs new file mode 100644 index 000000000..842f0be97 --- /dev/null +++ b/crates/horizon-client/src/gizmos.rs @@ -0,0 +1,347 @@ +//! Debug gizmos (26.3 `net.minecraft.gizmos`): coloured lines with a width +//! in pixels, as `GizmoFeatureRenderer.buildLines` draws them, and the two +//! debug renderers the F3 keys switch on: `ChunkBorderRenderer` (F3+G) and +//! `EntityHitboxDebugRenderer` (F3+B). + +/// A line: world-space ends, ARGB colour, width in pixels. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Line { + pub start: [f64; 3], + pub end: [f64; 3], + pub color: u32, + pub width: f32, +} + +/// The gizmos of a frame: depth-tested lines, and lines drawn over +/// everything (`GizmoProperties.setAlwaysOnTop`). +#[derive(Clone, Debug, Default)] +pub struct Gizmos { + pub lines: Vec, + pub on_top: Vec, +} + +/// `CommonColors`. +pub const WHITE: u32 = 0xFFFF_FFFF; +pub const RED: u32 = 0xFFFF_0000; +pub const BLUE: u32 = 0xFF00_00FF; +pub const YELLOW: u32 = 0xFFFF_FF00; +/// `ChunkBorderRenderer.CELL_BORDER`, `YELLOW`, `MAJOR_LINES` and the outer +/// columns' `ARGB.colorFromFloat(0.5F, 1.0F, 0.0F, 0.0F)`. +pub const CELL_BORDER: u32 = 0xFF00_9B9B; +pub const CHUNK_YELLOW: u32 = 0xFFFF_FF00; +pub const MAJOR_LINES: u32 = 0xFF3F_3FFF; +pub const OUTER_COLUMNS: u32 = 0x7FFF_0000; +/// `ARGB.colorFromFloat(1.0F, 0.25F, 1.0F, 0.0F)`: dragon parts. +pub const DRAGON_PART: u32 = 0xFF3F_FF00; +/// `GizmoStyle.stroke(argb)` and `Gizmos.arrow(start, end, argb)`. +pub const STROKE_WIDTH: f32 = 2.5; + +impl Gizmos { + /// `Gizmos.line`. + pub fn line(&mut self, start: [f64; 3], end: [f64; 3], color: u32, width: f32) { + self.lines.push(Line { + start, + end, + color, + width, + }); + } + /// `CuboidGizmo.emit` with a stroke style: the twelve edges in its order. + pub fn cuboid(&mut self, min: [f64; 3], max: [f64; 3], color: u32, width: f32) { + let edges = cuboid_edges(min, max); + self.lines.extend(edges.iter().map(|&(start, end)| Line { + start, + end, + color, + width, + })); + } + /// `ArrowGizmo.emit`: the shaft, then four tips around the end. + pub fn arrow(&mut self, start: [f64; 3], end: [f64; 3], color: u32, width: f32) { + self.line(start, end, color, width); + let d = glam::DVec3::from(end) - glam::DVec3::from(start); + let dir = d.as_vec3().normalize(); + // Quaternionf.rotationTo((1, 0, 0), direction). + let rotation = glam::Quat::from_rotation_arc(glam::Vec3::X, dir); + // (float) Mth.clamp(distance * 0.1, 0.1, 1.0). + let len = (d.length() * f64::from(0.1f32)).clamp(f64::from(0.1f32), 1.0) as f32; + for tip in [ + glam::Vec3::new(-len, len, 0.0), + glam::Vec3::new(-len, 0.0, len), + glam::Vec3::new(-len, -len, 0.0), + glam::Vec3::new(-len, 0.0, -len), + ] { + let t = rotation * tip; + let from = [ + end[0] + f64::from(t.x), + end[1] + f64::from(t.y), + end[2] + f64::from(t.z), + ]; + self.line(from, end, color, width); + } + } + /// `ChunkBorderRenderer.emitGizmos` around the camera entity's block. + pub fn chunk_borders(&mut self, camera_block: [i32; 3], min_y: i32, max_y: i32) { + let x0 = f64::from(camera_block[0] & !15); + let z0 = f64::from(camera_block[2] & !15); + let section_y = camera_block[1] & !15; + let (ymin, ymax) = (min_y as f32 as f64, (max_y + 1) as f32 as f64); + let column = |g: &mut Self, x: f64, z: f64, color: u32, width: f32| { + g.line([x, ymin, z], [x, ymax, z], color, width); + }; + for x in (-16..=32).step_by(16) { + for z in (-16..=32).step_by(16) { + column( + self, + x0 + f64::from(x), + z0 + f64::from(z), + OUTER_COLUMNS, + 4.0, + ); + } + } + for x in (2..16).step_by(2) { + let color = if x % 4 == 0 { + CELL_BORDER + } else { + CHUNK_YELLOW + }; + column(self, x0 + f64::from(x), z0, color, 1.0); + column(self, x0 + f64::from(x), z0 + 16.0, color, 1.0); + } + for z in (2..16).step_by(2) { + let color = if z % 4 == 0 { + CELL_BORDER + } else { + CHUNK_YELLOW + }; + column(self, x0, z0 + f64::from(z), color, 1.0); + column(self, x0 + 16.0, z0 + f64::from(z), color, 1.0); + } + let ring = |g: &mut Self, y: f64, color: u32, width: f32| { + g.line([x0, y, z0], [x0, y, z0 + 16.0], color, width); + g.line([x0, y, z0 + 16.0], [x0 + 16.0, y, z0 + 16.0], color, width); + g.line([x0 + 16.0, y, z0 + 16.0], [x0 + 16.0, y, z0], color, width); + g.line([x0 + 16.0, y, z0], [x0, y, z0], color, width); + }; + let mut y = min_y; + while y <= max_y + 1 { + let color = if y % 8 == 0 { + CELL_BORDER + } else { + CHUNK_YELLOW + }; + ring(self, f64::from(y as f32), color, 1.0); + y += 2; + } + for x in [0.0, 16.0] { + for z in [0.0, 16.0] { + column(self, x0 + x, z0 + z, MAJOR_LINES, 4.0); + } + } + // The camera's section, always on top. + let min = [x0, f64::from(section_y), z0]; + let max = [x0 + 16.0, f64::from(section_y + 16), z0 + 16.0]; + self.on_top + .extend(cuboid_edges(min, max).iter().map(|&(start, end)| Line { + start, + end, + color: MAJOR_LINES, + width: 1.0, + })); + let mut y = min_y; + while y <= max_y + 1 { + ring(self, f64::from(y), MAJOR_LINES, 4.0); + y += 16; + } + } + /// `EntityHitboxDebugRenderer.showHitboxes` for a client entity: + /// `position` is the interpolated position, `size` (width, height). + /// `eye` is the eye height and view rotations (x, y) for living + /// entities; other entities still get the view arrow from `view`. + pub fn hitbox( + &mut self, + position: [f64; 3], + size: (f32, f32), + eye_height: f32, + living: bool, + view: (f32, f32), + ) { + let half = f64::from(size.0) / 2.0; + let min = [position[0] - half, position[1], position[2] - half]; + let max = [ + position[0] + half, + position[1] + f64::from(size.1), + position[2] + half, + ]; + self.cuboid(min, max, WHITE, STROKE_WIDTH); + if living { + let eye = min[1] + f64::from(eye_height); + let d = 0.009999999776482582; + self.cuboid( + [min[0], eye - d, min[2]], + [max[0], eye + d, max[2]], + RED, + STROKE_WIDTH, + ); + } + let eye = [ + position[0], + position[1] + f64::from(eye_height), + position[2], + ]; + let v = view_vector(view.0, view.1); + let end = [ + eye[0] + v[0] * 2.0, + eye[1] + v[1] * 2.0, + eye[2] + v[2] * 2.0, + ]; + self.arrow(eye, end, BLUE, STROKE_WIDTH); + } +} + +/// The edges of `CuboidGizmo.emit`'s stroke, in order. +fn cuboid_edges(min: [f64; 3], max: [f64; 3]) -> [([f64; 3], [f64; 3]); 12] { + let [x0, y0, z0] = min; + let [x1, y1, z1] = max; + [ + ([x0, y0, z0], [x1, y0, z0]), + ([x0, y0, z0], [x0, y1, z0]), + ([x0, y0, z0], [x0, y0, z1]), + ([x1, y0, z0], [x1, y1, z0]), + ([x1, y1, z0], [x0, y1, z0]), + ([x0, y1, z0], [x0, y1, z1]), + ([x0, y1, z1], [x0, y0, z1]), + ([x0, y0, z1], [x1, y0, z1]), + ([x1, y0, z1], [x1, y0, z0]), + ([x0, y1, z1], [x1, y1, z1]), + ([x1, y0, z1], [x1, y1, z1]), + ([x1, y1, z0], [x1, y1, z1]), + ] +} + +/// `Entity.calculateViewVector(xRot, yRot)`. +pub fn view_vector(x_rot: f32, y_rot: f32) -> [f64; 3] { + use horizon_core::geometry::trig::{cos, sin}; + let x = f64::from(x_rot * (std::f32::consts::PI / 180.0)); + let y = f64::from(-y_rot * (std::f32::consts::PI / 180.0)); + let (yc, ys, xc, xs) = (cos(y), sin(y), cos(x), sin(x)); + [f64::from(ys * xc), f64::from(-xs), f64::from(yc * xc)] +} + +/// `GizmoFeatureRenderer.buildLines`: camera-relative ends, clipped at the +/// near plane in view space (z = -0.05), as (start, end, colour, width). +pub fn camera_relative(lines: &[Line], camera: [f64; 3], view: glam::Mat4) -> Vec<[f32; 8]> { + let mut out = Vec::with_capacity(lines.len()); + for l in lines { + let rel = |p: [f64; 3]| { + glam::Vec3::new( + (p[0] - camera[0]) as f32, + (p[1] - camera[1]) as f32, + (p[2] - camera[2]) as f32, + ) + }; + let (mut start, mut end) = (rel(l.start), rel(l.end)); + let (sv, ev) = (view.transform_point3(start), view.transform_point3(end)); + let (start_behind, end_behind) = (sv.z > -0.05, ev.z > -0.05); + if start_behind && end_behind { + continue; + } + if start_behind || end_behind { + let denom = ev.z - sv.z; + if denom.abs() >= 1.0e-9 { + let t = ((-0.05 - sv.z) / denom).clamp(0.0, 1.0); + let cut = start.lerp(end, t); + if start_behind { + start = cut; + } else { + end = cut; + } + } + } + out.push([ + start.x, + start.y, + start.z, + end.x, + end.y, + end.z, + f32::from_bits(l.color), + l.width, + ]); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chunk_borders_match_the_renderer() { + let mut g = Gizmos::default(); + g.chunk_borders([37, 70, -5], -64, 319); + // 4 * 4 outer columns, 2 * 7 + 2 * 7 inner columns, a ring every 2 + // blocks, 4 major columns, a major ring every 16. + let rings = (-64..=320).step_by(2).count(); + let majors = (-64..=320).step_by(16).count(); + assert_eq!(g.lines.len(), 16 + 28 + rings * 4 + 4 + majors * 4); + assert_eq!(g.on_top.len(), 12); + let first = g.lines[0]; + assert_eq!(first.start, [16.0, -64.0, -32.0]); + assert_eq!(first.end, [16.0, 320.0, -32.0]); + assert_eq!((first.color, first.width), (OUTER_COLUMNS, 4.0)); + // The section box around y 70. + assert_eq!(g.on_top[0].start, [32.0, 64.0, -16.0]); + assert_eq!(g.on_top[11].end, [48.0, 80.0, 0.0]); + // y 0 and 8 are cell-coloured rings, y 2 yellow. + let ring_at = |y: f64| { + g.lines + .iter() + .find(|l| l.start[1] == y && l.end[1] == y) + .unwrap() + }; + assert_eq!(ring_at(8.0).color, CELL_BORDER); + assert_eq!(ring_at(2.0).color, CHUNK_YELLOW); + } + + #[test] + fn hitbox_box_eye_line_and_view_arrow() { + let mut g = Gizmos::default(); + g.hitbox([0.5, 64.0, 0.5], (0.6, 1.8), 1.62, true, (0.0, 0.0)); + assert_eq!(g.lines.len(), 12 + 12 + 5); + // EntityDimensions.makeBoundingBox: the float half width. + let corner = 0.5 - f64::from(0.6f32 / 2.0); + assert_eq!(g.lines[0].start, [corner, 64.0, corner]); + assert_eq!(g.lines[12].color, RED); + // Looking south (yRot 0): the arrow points +z. + let arrow = g.lines[24]; + assert_eq!(arrow.color, BLUE); + assert!((arrow.end[2] - 2.5).abs() < 1e-6 && (arrow.end[0] - 0.5).abs() < 1e-6); + let mut g = Gizmos::default(); + g.hitbox([0.0, 0.0, 0.0], (0.25, 0.25), 0.2125, false, (0.0, 0.0)); + assert_eq!(g.lines.len(), 12 + 5); + } + + #[test] + fn lines_behind_the_camera_are_clipped_at_the_near_plane() { + let view = glam::Mat4::IDENTITY; // looking down -z + let lines = [ + Line { + start: [0.0, 0.0, -2.0], + end: [0.0, 0.0, 2.0], + color: WHITE, + width: 1.0, + }, + Line { + start: [0.0, 0.0, 1.0], + end: [1.0, 0.0, 2.0], + color: WHITE, + width: 1.0, + }, + ]; + let out = camera_relative(&lines, [0.0; 3], view); + assert_eq!(out.len(), 1); + assert!((out[0][5] + 0.05).abs() < 1e-6); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 5f433982c..7f60a690b 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -38,6 +38,7 @@ pub mod crafting; pub mod creative; pub mod data_cmd; pub mod datapack; +pub mod debug_keys; pub mod effects; pub mod enchant; pub mod entities; @@ -52,6 +53,7 @@ pub mod font; pub mod front; pub mod gamerules; pub mod gfx; +pub mod gizmos; pub mod gossip; pub mod graphics; pub mod graphics_style; diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 8fcb8c216..b128fa63f 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -209,3 +209,36 @@ struct LineOut { @fragment fn fs_line(in: LineOut) -> @location(0) vec4 { return apply_fog(vec4(0.0, 0.0, 0.0, 0.4), in.spherical, in.cylindrical); } +// Gizmo lines (rendertype_lines with a per-vertex colour and LineWidth in +// pixels; no layering transform). +struct DebugLineOut { + @builtin(position) clip: vec4, + @location(0) spherical: f32, + @location(1) cylindrical: f32, + @location(2) color: vec4, +} +@vertex fn vs_debug_line(@builtin(vertex_index) vertex: u32, + @location(0) start: vec3, @location(1) end: vec3, + @location(2) argb: vec4, @location(3) width: f32) -> DebugLineOut { + let position = select(start, end, vertex >= 2u); + let view_shrink = 1.0 - 1.0 / 256.0; + let line_start = globals.view_proj * vec4(position * view_shrink, 1.0); + let line_end = globals.view_proj * vec4((position + (end - start)) * view_shrink, 1.0); + let ndc1 = line_start.xyz / line_start.w; + let ndc2 = line_end.xyz / line_end.w; + let screen = globals.outline_params.xy; + let direction = normalize((ndc2.xy - ndc1.xy) * screen); + var offset = vec2(-direction.y, direction.x) * width / screen; + if offset.x < 0.0 { offset = -offset; } + if vertex % 2u != 0u { offset = -offset; } + var out: DebugLineOut; + out.clip = vec4((ndc1 + vec3(offset, 0.0)) * line_start.w, line_start.w); + out.spherical = length(position); + out.cylindrical = max(length(position.xz), abs(position.y)); + // ARGB in a little-endian u32 reads as B, G, R, A. + out.color = argb.zyxw; + return out; +} +@fragment fn fs_debug_line(in: DebugLineOut) -> @location(0) vec4 { + return apply_fog(in.color, in.spherical, in.cylindrical); +} From 383fc116c98720a8f06cfb13c2ba16b2ec4e4929 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:13:38 +0200 Subject: [PATCH 02/11] Entity particle bursts: as many particles as vanilla, about the body Villagers showed one angry, happy or heart particle where vanilla's AbstractVillager.addParticlesAroundSelf shows five, spread over the body with Gaussian motion. Taming and love bursts were spread about the middle of the body rather than over it, and drew from the world random. particles::around_self places a burst as the client handlers do: per particle three Gaussian speeds, then getRandomX(1), getRandomY() + y, getRandomZ(1). Burst holds the counts, speeds and heights vanilla uses, and entity_event_burst maps entity events to them. The client side uses the particle engine's random, so no server draw moves. - villager hurt by a player, failed breeding (13), breeding hearts and the child's (12), trades, job sites and beds (14): five particles about the villager, not one 1.8 above its feet. - wolf, cat, parrot, nautilus and horse taming (7/6): seven hearts or smoke about the body. - allay duplication (18): three hearts about the allay. - llama growth from food: one particle at rest about the body. - animals in love: the heart moves at the Gaussian speeds already drawn, exactly where vanilla puts it; forced growth's particle sits where it was placed (sendParticles with no spread) instead of being jittered. New harness tools/test_entity_particles_parity.py: the real client handleEntityEvent of Villager, Animal, TamableAnimal, AbstractHorse, Ocelot, Dolphin and Allay against entity_event_burst and around_self. Part of #63 Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_particles_probe.rs | 51 ++++++++ crates/horizon-client/src/game/allays.rs | 18 +-- crates/horizon-client/src/game/creatures.rs | 49 +++++--- crates/horizon-client/src/game/llamas.rs | 15 +-- crates/horizon-client/src/game/mounts.rs | 16 +-- crates/horizon-client/src/game/nautili.rs | 14 +-- crates/horizon-client/src/game/villagers.rs | 68 +++++++++-- crates/horizon-client/src/mobs.rs | 14 +++ crates/horizon-client/src/mobs/ai.rs | 15 ++- .../horizon-client/src/mobs/villager_brain.rs | 41 +++---- crates/horizon-client/src/particles.rs | 109 +++++++++++++++++ .../parity/VanillaEntityParticlesOracle.java | 78 ++++++++++++ tools/test_entity_particles_parity.py | 112 ++++++++++++++++++ 13 files changed, 504 insertions(+), 96 deletions(-) create mode 100644 crates/horizon-client/examples/entity_particles_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityParticlesOracle.java create mode 100644 tools/test_entity_particles_parity.py diff --git a/crates/horizon-client/examples/entity_particles_probe.rs b/crates/horizon-client/examples/entity_particles_probe.rs new file mode 100644 index 000000000..ef38f1000 --- /dev/null +++ b/crates/horizon-client/examples/entity_particles_probe.rs @@ -0,0 +1,51 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_entity_particles_parity.py's entity events through +//! `particles::entity_event_burst` and `particles::around_self`. +use horizon_client::{Result, particles}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn d(v: f64) -> String { + format!("{:016x}", v.to_bits()) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let mut random = LegacyRandom::new(c["seed"].as_i64().ok_or("seed")?); + let feet: [f64; 3] = std::array::from_fn(|i| c["feet"][i].as_f64().unwrap_or(0.0)); + // EntityDimensions hold floats. + let width = f64::from(c["width"].as_f64().unwrap_or(0.0) as f32); + let height = f64::from(c["height"].as_f64().unwrap_or(0.0) as f32); + let entity = c["entity"].as_str().unwrap_or(""); + if let Some((kind, burst)) = + particles::entity_event_burst(entity, c["event"].as_u64().unwrap_or(0) as u8) + { + let mut lines = Vec::new(); + particles::around_self(&mut random, feet, width, height, burst, |p, v| { + lines.push(format!( + "+ {kind} {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(v[0]), + d(v[1]), + d(v[2]) + )); + }); + for l in lines { + writeln!(out, "{l}")?; + } + } + writeln!(out, "next {}", random.next_long())?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index 7a6d62e63..c948663b1 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -139,21 +139,9 @@ impl Game<'_> { { c.extra.egg_time = 6000; } - for _ in 0..3 { - let r = &mut self.world.random; - let p = [ - at[0] + r.next_double() - 0.5, - at[1] + 0.5 + r.next_double() * 0.6, - at[2] + r.next_double() - 0.5, - ]; - if let Some(ty) = horizon_client::particles::ParticleType::from_name("heart") { - self.particles.add( - &horizon_client::particles::ParticleOptions::simple(ty), - p, - [0.0; 3], - ); - } - } + // Allay.duplicateAllay: entity event 18, three spawnHeartParticle. + let id = self.mobs[index].id; + self.particles_around_mob(id, "heart", horizon_client::particles::Burst::ALLAY); self.audio .play("minecraft:block.amethyst_block.chime", Some(at), 2.0, 1.0); self.consume_held(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 7aff7847f..6935e05fa 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -909,6 +909,19 @@ impl Game<'_> { } } } + MobEvent::AroundSelf { + kind, + feet, + width, + height, + burst, + } => self.particles_around(kind, feet, [width, height], burst), + MobEvent::ParticleAt { kind, at, velocity } => { + if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { + let options = horizon_client::particles::ParticleOptions::simple(ty); + self.particles.add(&options, at, velocity); + } + } MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount), MobEvent::EffectPlayer { effect, @@ -1969,11 +1982,6 @@ impl Game<'_> { && !horizon_client::mobs::tame::angry(m) => { consume = true; - let at = [ - m.position.x, - m.position.y + f64::from(m.height()) * 0.5 + 0.5, - m.position.z, - ]; let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { horizon_client::mobs::tame::set_tame(m, true); @@ -1985,7 +1993,12 @@ impl Game<'_> { } // TamableAnimal.spawnTamingParticles. let kind = if tamed { "heart" } else { "smoke" }; - self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; + // TamableAnimal.spawnTamingParticles (entity event 7 or 6). + self.particles_around_mob( + self.mobs[index].id, + kind, + horizon_client::particles::Burst::TAMING, + ); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -2045,11 +2058,6 @@ impl Game<'_> { Species::Cat if !m.extra.tame && is_food => { consume = true; m.persistent = true; - let at = [ - m.position.x, - m.position.y + f64::from(m.height()) * 0.5 + 0.5, - m.position.z, - ]; let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { m.extra.tame = true; @@ -2058,7 +2066,12 @@ impl Game<'_> { } eat = eating_sound(m, &mut self.world.random); let kind = if tamed { "heart" } else { "smoke" }; - self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; + // TamableAnimal.spawnTamingParticles (entity event 7 or 6). + self.particles_around_mob( + self.mobs[index].id, + kind, + horizon_client::particles::Burst::TAMING, + ); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -2090,18 +2103,18 @@ impl Game<'_> { let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2; eat = Some(("entity.parrot.eat", 1.0, pitch)); } - let at = [ - m.position.x, - m.position.y + f64::from(m.height()) * 0.5 + 0.5, - m.position.z, - ]; let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0; if tamed { m.extra.tame = true; m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); } let kind = if tamed { "heart" } else { "smoke" }; - self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; + // TamableAnimal.spawnTamingParticles (entity event 7 or 6). + self.particles_around_mob( + self.mobs[index].id, + kind, + horizon_client::particles::Burst::TAMING, + ); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); diff --git a/crates/horizon-client/src/game/llamas.rs b/crates/horizon-client/src/game/llamas.rs index 5b54f6719..b9be87e3e 100644 --- a/crates/horizon-client/src/game/llamas.rs +++ b/crates/horizon-client/src/game/llamas.rs @@ -4,7 +4,7 @@ use super::Game; use horizon_client::{ items::ItemStack, - mobs::{MobEvent, equine, llama}, + mobs::{equine, llama}, }; use horizon_core::random::RandomSource; @@ -45,13 +45,14 @@ impl Game<'_> { m.extra.variant3 = (i32::from(m.extra.variant3) + temper).min(llama::MAX_TEMPER) as u8; used = true; } - let at = m.center(); if happy { - let _ = self.handle_mob_events(vec![MobEvent::Particles { - kind: "happy_villager", - at, - count: 1, - }]); + // AbstractHorse.handleEating: one at rest about the body. + let id = m.id; + self.particles_around_mob( + id, + "happy_villager", + horizon_client::particles::Burst::HORSE_EATING, + ); } if !used { return false; diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 2d987ea28..7e8923f23 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -437,16 +437,12 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { m.extra.owner = owner; m.persistent = true; - let at = [ - m.position.x, - m.position.y + f64::from(m.height()) * 0.5 + 0.5, - m.position.z, - ]; - let _ = self.handle_mob_events(vec![MobEvent::Particles { - kind: "heart", - at, - count: 7, - }]); + // AbstractHorse.tameWithName: entity event 7, spawnTamingParticles(true). + self.particles_around_mob( + mob, + "heart", + horizon_client::particles::Burst::TAMING, + ); } } MobEvent::Buck { mob } if self.riding == Some(mob) => self.dismount_mount(), diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index 592416630..c039b7d9a 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -4,7 +4,7 @@ use super::Game; use horizon_client::{ items::ItemStack, - mobs::{MobEvent, Species, nautilus}, + mobs::{Species, nautilus}, }; use horizon_core::random::RandomSource; @@ -84,14 +84,14 @@ impl Game<'_> { m.nav_stop(); m.ai.target = None; } - let at = [ - m.position.x, - m.position.y + f64::from(m.height()) * 0.5 + 0.5, - m.position.z, - ]; let sound = nautilus::eat_sound(m); let kind = if tamed { "heart" } else { "smoke" }; - let _ = self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }]); + // TamableAnimal.spawnTamingParticles (entity event 7 or 6). + self.particles_around_mob( + self.mobs[index].id, + kind, + horizon_client::particles::Burst::TAMING, + ); self.nautilus_sound(index, sound); if tamed { let view = self.mob_entity(&self.mobs[index]); diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 0d3f01c07..0d547c0b0 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -176,9 +176,10 @@ impl Game<'_> { villager::ext_mut(&mut self.mobs[ib]).eat_and_digest(); let from = self.mobs[ia].position; let Some((bed, variant)) = child else { - for i in [ia, ib] { - let p = self.mobs[i].position; - self.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]); + // VillagerMakeLove: entity event 13 for the partner, then the parent. + for i in [ib, ia] { + let id = self.mobs[i].id; + self.villager_particles(id, "angry_villager"); } return; }; @@ -202,12 +203,52 @@ impl Game<'_> { child.extra.age = -24000; child.extra.bed = Some(bed); } - self.particles_at("heart", [from.x, from.y + 1.8, from.z]); + // VillagerMakeLove.giveBirth: entity event 12 for the child. + self.villager_particles(id, "heart"); } - fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) { - if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { - let options = horizon_client::particles::ParticleOptions::simple(ty); - self.particles.add(&options, at, [0.0; 3]); + /// `Villager.handleEntityEvent` 12, 13, 14 and 42: + /// `AbstractVillager.addParticlesAroundSelf`. + pub(super) fn villager_particles(&mut self, id: u32, kind: &'static str) { + self.particles_around_mob(id, kind, horizon_client::particles::Burst::VILLAGER); + } + /// `particles::around_self` about mob `id`. + pub(super) fn particles_around_mob( + &mut self, + id: u32, + kind: &'static str, + burst: horizon_client::particles::Burst, + ) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let feet = [m.position.x, m.position.y, m.position.z]; + let size = [f64::from(m.width()), f64::from(m.height())]; + self.particles_around(kind, feet, size, burst); + } + /// `particles::around_self` on the client: the particle engine's random + /// stands in for the client entity's, so no server draw moves. + pub(super) fn particles_around( + &mut self, + kind: &'static str, + feet: [f64; 3], + size: [f64; 2], + burst: horizon_client::particles::Burst, + ) { + let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) else { + return; + }; + let options = horizon_client::particles::ParticleOptions::simple(ty); + let mut spawned = Vec::new(); + horizon_client::particles::around_self( + self.particles.random(), + feet, + size[0], + size[1], + burst, + |p, v| spawned.push((p, v)), + ); + for (p, v) in spawned { + self.particles.add(&options, p, v); } } @@ -281,7 +322,7 @@ impl Game<'_> { } let time = m.ai.last_hurt_by_time; let alive = m.alive(); - let at = m.position; + let at = m.id; let e = villager::ext_mut(m); if e.hurt_seen != time { e.hurt_seen = time; @@ -295,8 +336,9 @@ impl Game<'_> { } } } - for at in angry { - self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]); + // Villager.setLastHurtByMob: entity event 13. + for id in angry { + self.villager_particles(id, "angry_villager"); } } /// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a @@ -350,8 +392,8 @@ impl Game<'_> { GossipType::Trading, gossip::REPUTATION_CHANGE_PER_TRADE, ); - let p = self.mobs[i].position; - self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]); + // Villager.customServerAiStep after a trade: entity event 14. + self.villager_particles(id, "happy_villager"); } /// `Villager.getPlayerReputation` of the local player. pub(super) fn villager_reputation(&self, id: u32) -> i32 { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 195bf536f..4c2ff6bba 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -933,6 +933,20 @@ pub enum MobEvent { at: [f64; 3], count: u32, }, + /// Client particles about a mob's box (`particles::around_self`). + AroundSelf { + kind: &'static str, + feet: [f64; 3], + width: f64, + height: f64, + burst: crate::particles::Burst, + }, + /// One particle exactly at `at`, moving at `velocity`. + ParticleAt { + kind: &'static str, + at: [f64; 3], + velocity: [f64; 3], + }, Experience { at: [f64; 3], amount: u32, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index f3045a8b1..606e67f26 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -626,10 +626,11 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & let x = m.position.x + w * (2.0 * r.next_double() - 1.0); let y = m.position.y + h * r.next_double() + 0.5; let z = m.position.z + w * (2.0 * r.next_double() - 1.0); + // sendParticles(HAPPY_VILLAGER, x, y, z, 1, 0, 0, 0, 0): exactly there, at rest. events.push(MobEvent::Particles { kind: "happy_villager", at: [x, y, z], - count: 1, + count: 0, }); } m.extra.forced_age_timer -= 1; @@ -655,16 +656,18 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // The heart's speed and getRandomX/Y/Z, drawn even on the server. let (w, h) = (f64::from(m.width()), f64::from(m.height())); let r = &mut m.random; - for _ in 0..3 { - let _ = r.next_gaussian(); - } + let velocity = [ + r.next_gaussian() * 0.02, + r.next_gaussian() * 0.02, + r.next_gaussian() * 0.02, + ]; let x = m.position.x + w * (2.0 * r.next_double() - 1.0); let y = m.position.y + h * r.next_double() + 0.5; let z = m.position.z + w * (2.0 * r.next_double() - 1.0); - events.push(MobEvent::Particles { + events.push(MobEvent::ParticleAt { kind: "heart", at: [x, y, z], - count: 1, + velocity, }); } } diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 9c1efb7ac..e318fb9f2 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -2925,15 +2925,21 @@ impl B { child, }); } else if m.random.next_int_bound(35).unwrap_or(1) == 0 { - let mut p = vec![m.position]; + // Entity event 12 for the partner, then this villager: + // AbstractVillager.addParticlesAroundSelf(HEART). + let mut bodies = Vec::new(); if let Some(t) = cx.w.target_info(target) { - p.push(t.position); + let (min, max) = (t.bounds.min_position(), t.bounds.max_position()); + bodies.push((t.position, max.x - min.x, max.y - min.y)); } - for at in p { - cx.events.push(MobEvent::Particles { + bodies.push((m.position, f64::from(m.width()), f64::from(m.height()))); + for (feet, width, height) in bodies { + cx.events.push(MobEvent::AroundSelf { kind: "heart", - at: [at.x, at.y + 1.8, at.z], - count: 1, + feet: [feet.x, feet.y, feet.z], + width, + height, + burst: crate::particles::Burst::VILLAGER, }); } } @@ -3527,21 +3533,16 @@ fn pois_scan_order(_m: &Mob, found: &[(Poi, [i32; 3])]) -> Vec { } /// Entity event 14: the client shows happy particles (with its own random, /// not the mob's). +/// Entity event 14 (`AcquirePoi`, `AssignProfessionFromJobSite`): +/// `AbstractVillager.addParticlesAroundSelf(HAPPY_VILLAGER)` on the client. fn happy_particles(m: &Mob, cx: &mut Bx) { - let mut r = LegacyRandom::new(cx.now ^ i64::from(m.id)); - let (w, h) = (f64::from(m.width()), f64::from(m.height())); - for _ in 0..5 { - let at = [ - m.position.x + w * (2.0 * r.next_double() - 1.0), - m.position.y + h * r.next_double() + 1.0, - m.position.z + w * (2.0 * r.next_double() - 1.0), - ]; - cx.events.push(MobEvent::Particles { - kind: "happy_villager", - at, - count: 0, - }); - } + cx.events.push(MobEvent::AroundSelf { + kind: "happy_villager", + feet: [m.position.x, m.position.y, m.position.z], + width: f64::from(m.width()), + height: f64::from(m.height()), + burst: crate::particles::Burst::VILLAGER, + }); } /// `BehaviorUtils.findSectionClosestToVillage`. fn closest_section(villages: &[[i32; 3]], center: [i32; 3], radius: i32) -> [i32; 3] { diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index f9ecd61ba..bc32e4926 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -447,6 +447,115 @@ pub fn breaking_position( Some(p) } +/// A burst of particles about an entity's box (`around_self`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Burst { + pub count: u32, + /// Scale of the Gaussian speeds; `None` spawns them at rest without drawing any. + pub speed: Option, + /// Added to `getRandomY()`. + pub y: f64, +} +impl Burst { + /// `AbstractVillager.addParticlesAroundSelf`. + pub const VILLAGER: Self = Self { + count: 5, + speed: Some(0.02), + y: 1.0, + }; + /// `TamableAnimal`/`AbstractHorse.spawnTamingParticles`, + /// `Ocelot.spawnTrustingParticles`, `Animal`'s entity event 18. + pub const TAMING: Self = Self { + count: 7, + speed: Some(0.02), + y: 0.5, + }; + /// `Allay`'s entity event 18: three `spawnHeartParticle`. + pub const ALLAY: Self = Self { + count: 3, + speed: Some(0.02), + y: 0.5, + }; + /// `Dolphin.addParticlesAroundSelf`. + pub const DOLPHIN: Self = Self { + count: 7, + speed: Some(0.01), + y: 0.2, + }; + /// `AbstractHorse.handleEating`'s growth particle. + pub const HORSE_EATING: Self = Self { + count: 1, + speed: None, + y: 0.5, + }; +} +/// The particle bursts entity events show on the client: the particle and +/// burst of `handleEntityEvent(event)` for the entity type `entity`. +pub fn entity_event_burst(entity: &str, event: u8) -> Option<(&'static str, Burst)> { + let entity = entity.strip_prefix("minecraft:").unwrap_or(entity); + let tamable = matches!( + entity, + "wolf" | "cat" | "parrot" | "nautilus" | "zombie_nautilus" + ); + let horse = matches!( + entity, + "horse" + | "donkey" + | "mule" + | "llama" + | "trader_llama" + | "camel" + | "camel_husk" + | "skeleton_horse" + | "zombie_horse" + ); + Some(match (entity, event) { + ("villager", 12) => ("heart", Burst::VILLAGER), + ("villager", 13) => ("angry_villager", Burst::VILLAGER), + ("villager", 14) => ("happy_villager", Burst::VILLAGER), + ("villager", 42) => ("splash", Burst::VILLAGER), + ("allay", 18) => ("heart", Burst::ALLAY), + ("dolphin", 38) => ("happy_villager", Burst::DOLPHIN), + ("ocelot", 41) => ("heart", Burst::TAMING), + ("ocelot", 40) => ("smoke", Burst::TAMING), + (_, 7) if tamable || horse => ("heart", Burst::TAMING), + (_, 6) if tamable || horse => ("smoke", Burst::TAMING), + (_, 18) if !matches!(entity, "villager" | "allay") => ("heart", Burst::TAMING), + _ => return None, + }) +} + +/// Particles about an entity's box, as `AbstractVillager.addParticlesAroundSelf`, +/// `Animal`'s love hearts (entity event 18), `TamableAnimal` and +/// `AbstractHorse.spawnTamingParticles`, `Ocelot.spawnTrustingParticles`, +/// `Allay`'s hearts and `Dolphin.addParticlesAroundSelf` place them: `count` +/// times three Gaussian speeds scaled by `speed` (none drawn without one), then +/// `getRandomX(1.0)`, `getRandomY() + y` and `getRandomZ(1.0)`. +pub fn around_self( + random: &mut impl RandomSource, + feet: [f64; 3], + width: f64, + height: f64, + burst: Burst, + mut emit: impl FnMut([f64; 3], [f64; 3]), +) { + for _ in 0..burst.count { + let v = burst.speed.map_or([0.0; 3], |s| { + [ + random.next_gaussian() * s, + random.next_gaussian() * s, + random.next_gaussian() * s, + ] + }); + let p = [ + feet[0] + width * ((2.0 * random.next_double() - 1.0) * 1.0), + feet[1] + height * random.next_double() + burst.y, + feet[2] + width * ((2.0 * random.next_double() - 1.0) * 1.0), + ]; + emit(p, v); + } +} + /// ClientLevel.addDestroyBlockEffect placement and pre-constructor velocities. pub fn destroy_positions( pos: [i32; 3], diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityParticlesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityParticlesOracle.java new file mode 100644 index 000000000..06b1eb53d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityParticlesOracle.java @@ -0,0 +1,78 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.server.Bootstrap; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.animal.camel.Camel; +import net.minecraft.world.entity.animal.cow.Cow; +import net.minecraft.world.entity.animal.dolphin.Dolphin; +import net.minecraft.world.entity.animal.equine.Horse; +import net.minecraft.world.entity.animal.equine.Llama; +import net.minecraft.world.entity.animal.feline.Cat; +import net.minecraft.world.entity.animal.feline.Ocelot; +import net.minecraft.world.entity.animal.nautilus.Nautilus; +import net.minecraft.world.entity.animal.parrot.Parrot; +import net.minecraft.world.entity.animal.wolf.Wolf; +import net.minecraft.world.entity.npc.villager.Villager; +import net.minecraft.world.phys.Vec3; + +/** Calls the real client handleEntityEvent of entities whose events are particle + * bursts about their body, and records what they ask the level to spawn. The + * entities are allocated without constructors and given only a level stand-in, + * a position, dimensions and their random, which is all those handlers read. */ +public final class VanillaEntityParticlesOracle { + static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); } + static Field field(Class type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f; + } + static final class Level0 extends ClientLevel { + List events; + Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + @Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) { + events.add("+ " + BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()).getPath() + " " + d(x) + " " + d(y) + " " + d(z) + + " " + d(xd) + " " + d(yd) + " " + d(zd)); + } + } + static final Map> TYPES = Map.ofEntries( + Map.entry("villager", Villager.class), Map.entry("cow", Cow.class), Map.entry("wolf", Wolf.class), + Map.entry("cat", Cat.class), Map.entry("parrot", Parrot.class), Map.entry("horse", Horse.class), + Map.entry("llama", Llama.class), Map.entry("camel", Camel.class), Map.entry("ocelot", Ocelot.class), + Map.entry("dolphin", Dolphin.class), Map.entry("allay", Allay.class), Map.entry("nautilus", Nautilus.class)); + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); var unsafe = field(u, "theUnsafe").get(null); + var allocate = u.getMethod("allocateInstance", Class.class); + var level = (Level0) allocate.invoke(unsafe, Level0.class); level.events = new ArrayList<>(); + Field levelField = field(Entity.class, "level"), position = field(Entity.class, "position"), + dimensions = field(Entity.class, "dimensions"), random = field(Entity.class, "random"); + try (var output = Files.newBufferedWriter(Path.of(args[1]))) { + int n = 0; + for (String line : Files.readAllLines(Path.of(args[0]))) { + var c = JsonParser.parseString(line).getAsJsonObject(); + output.write("== " + n++); output.newLine(); + var entity = (Entity) allocate.invoke(unsafe, TYPES.get(c.get("entity").getAsString())); + var feet = c.getAsJsonArray("feet"); + levelField.set(entity, level); + position.set(entity, new Vec3(feet.get(0).getAsDouble(), feet.get(1).getAsDouble(), feet.get(2).getAsDouble())); + dimensions.set(entity, EntityDimensions.scalable(c.get("width").getAsFloat(), c.get("height").getAsFloat())); + var r = RandomSource.create(c.get("seed").getAsLong()); + random.set(entity, r); + level.events.clear(); + entity.handleEntityEvent((byte) c.get("event").getAsInt()); + for (var e : level.events) { output.write(e); output.newLine(); } + output.write("next " + r.nextLong()); output.newLine(); + } + } + } +} diff --git a/tools/test_entity_particles_parity.py b/tools/test_entity_particles_parity.py new file mode 100644 index 000000000..2156f97ec --- /dev/null +++ b/tools/test_entity_particles_parity.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Compare the particle bursts entity events show on the client (villagers' +hearts, anger and happiness, love hearts, taming and trusting hearts and smoke, +the allay's and dolphin's) with the real handleEntityEvent of each entity: +particle, count, positions about the body, motion and every random draw.""" +import json +import platform +import random +import struct +import subprocess + +try: + from . import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking + +EVENTS = { + 'villager': [12, 13, 14, 42], + 'cow': [18], 'wolf': [6, 7, 18], 'cat': [6, 7, 18], 'parrot': [6, 7], 'nautilus': [6, 7, 18], + 'horse': [6, 7, 18], 'llama': [6, 7, 18], 'camel': [6, 7, 18], + 'ocelot': [40, 41, 18], 'dolphin': [38], 'allay': [18], +} +# Dyadic sizes and positions: serde_json's decimal parsing may round others a unit off. +SIZES = [(0.6, 1.95), (0.9, 1.4), (0.3, 0.85), (1.3964844, 1.6), (0.35, 0.6), (0.875, 0.9375)] + + +def cases(rng): + for entity, events in EVENTS.items(): + for event in events: + for _ in range(40): + w, h = rng.choice(SIZES) + feet = [rng.randrange(-4096, 4096) / 64 for _ in range(3)] + yield dict(entity=entity, event=event, feet=feet, width=w, height=h, + seed=rng.randrange(-2**63, 2**63)) + + +def make_cases(build): + path = build / 'cases.jsonl' + count = 0 + with path.open('w') as out: + for case in cases(random.Random(0x454e5450)): + out.write(json.dumps(case, separators=(',', ':')) + '\n') + count += 1 + return path, count + + +def close(a, b): + """Lines equal but for doubles within 1e-12 relative error. The motion is + Gaussian, and MarsagliaPolarGaussian calls Math.log, which HotSpot's x86-64 + intrinsic rounds a unit apart from the platform libm horizon_core::jmath + uses for a small fraction of arguments.""" + ta, tb = a.split(), b.split() + if len(ta) != len(tb): + return False + for x, y in zip(ta, tb): + if x == y: + continue + if len(x) != 16 or len(y) != 16: + return False + fx, fy = (struct.unpack('>d', bytes.fromhex(t))[0] for t in (x, y)) + if not abs(fx - fy) <= 1e-12 * max(1.0, abs(fx)): + return False + return True + + +def main(): + lock, jars, _ = base.verify_artifacts() + name, oracle, probe = 'rust-entity-particles-parity', 'VanillaEntityParticlesOracle', 'entity_particles_probe' + build = lab.LOCAL / name + build.mkdir(exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + sources = [lab.ROOT / p for p in [ + 'tools/test_entity_particles_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', + f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', + 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', + f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + tested = base.source_hashes(sources) + cases_path, units = make_cases(build) + classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, baking.client_libraries(), + lock['minecraft']['java_major']) + binary = harness.build_probe(build, probe) + harness.run_logged([binary, cases_path, build / 'rust.txt'], build, 'rust') + harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') + vanilla = (build / 'client.txt').read_text().splitlines() + rust = (build / 'rust.txt').read_text().splitlines() + assert len(vanilla) == len(rust), f'{len(vanilla)} vanilla lines, {len(rust)} Rust lines' + tolerated = 0 + for line, (a, b) in enumerate(zip(vanilla, rust), 1): + if a != b: + assert close(a, b), f'Parity mismatch at output line {line}: vanilla={a!r}, Rust={b!r}' + tolerated += 1 + particles = sum(line.startswith('+ ') for line in vanilla) + assert particles > units, 'too few particles to establish parity' + base.ensure_sources_unchanged(sources, tested) + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(), units=units, + sources_sha256=tested, input_sha256=lab.digest(cases_path, 'sha256'), + client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=len(vanilla), + libm_tolerated_lines=tolerated, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), + scope=('The real client handleEntityEvent of Villager (12, 13, 14, 42), Animal (18, love hearts), TamableAnimal ' + 'and AbstractHorse (6, 7, taming), Ocelot (40, 41, trusting), Dolphin (38) and Allay (18), on entities ' + 'allocated with a stand-in level, a position, dimensions and a seeded random: the particle type, ' + 'count, positions, motion and draws on the entity random. Which server code fires each event, and ' + 'the particles themselves once spawned, are covered elsewhere.'))) + print(f'{units:,} entity events, {particles:,} particles match the pinned client ({tolerated} lines within the ' + f'Math.log tolerance): {report}', flush=True) + + +if __name__ == '__main__': + main() From efa2f0e3be5e4b9d8f29b91ed82830e74774fa47 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:24:37 +0200 Subject: [PATCH 03/11] Particles: 29 missing vanilla particle types Horizon's engine knew 91 of vanilla's 128 particle types. These come from their real providers, constructor to tick: - sweep_attack (AttackSweepParticle) - glow, wax_on, wax_off, electric_spark, scrape (GlowParticle and its providers) - squid_ink, glow_squid_ink (SquidInkParticle: sinks through air) - item, item_slime, item_snowball, item_cobweb, sulfur_cube_goo (BreakingItemParticle: a quarter of the item's ground-model sprite in full colour, unlike terrain crumbs) - flash (FireworkParticles.OverlayParticle, its sine pulse and fading alpha), which firework explosions now show as vanilla's Starter does - firefly (FireflyParticle: wanders, fades in and out, vanishes inside blocks) - trial_spawner_detection(_ominous) (TrialSpawnerDetectionParticle) - trial_omen, raid_omen (SpellParticle) - ominous_spawning (FlyStraightTowardsParticle, colour lerped like ARGB.srgbLerp) - spit (ExplodeParticle falling at 0.5), fishing (WakeParticle), dust_plume (DustPlumeParticle) - red/orange/yellow_poplar_leaves (FallingLeavesParticle.PoplarProvider) - pause_mob_growth, reset_mob_growth (SimpleVerticalParticle) - block_marker (BlockMarker) ParticleType.getOverrideLimiter now lists every type vanilla registers with it (gust, sonic_boom, sculk charges, campfire smoke, vault_connection and the new ones were missing), so they show beyond 32 blocks. The /particle commands take the new types; item particles resolve the stack's ground model. The particle_providers harness now builds all 120 types Horizon implements through the real providers (1428 cases). Part of #63 Co-Authored-By: Claude Opus 5.5 --- .../examples/particle_providers_probe.rs | 24 +- crates/horizon-client/src/game.rs | 1 + .../src/game/commands/world_cmds.rs | 25 +- .../horizon-client/src/game/item_particles.rs | 35 ++ .../horizon-client/src/game/render_control.rs | 14 +- crates/horizon-client/src/particles.rs | 503 +++++++++++++++++- .../VanillaParticleProvidersOracle.java | 1 + tools/test_particle_providers_parity.py | 18 +- 8 files changed, 599 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-client/src/game/item_particles.rs diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/particle_providers_probe.rs index ddd71b52e..7c819eccd 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/particle_providers_probe.rs @@ -46,9 +46,10 @@ fn options(case: &Value) -> Option { [r, g, b, ((c >> 24) & 255) as f32 / 255.0] }; Some(match ty { - ParticleType::Block | ParticleType::BlockCrumble | ParticleType::DustPillar => { - ParticleOptions::block(ty, "terrain".into(), 0xFF_FFFF) - } + ParticleType::Block + | ParticleType::BlockCrumble + | ParticleType::DustPillar + | ParticleType::BlockMarker => ParticleOptions::block(ty, "terrain".into(), 0xFF_FFFF), // Stone's map colour: FallingDustParticle.Provider's tint without a tint source. ParticleType::FallingDust => ParticleOptions::block(ty, "terrain".into(), 0x70_7070), ParticleType::Dust => ParticleOptions::dust(rgb(c), scale), @@ -59,7 +60,15 @@ fn options(case: &Value) -> Option { scale, ..ParticleOptions::colored(ty, argb) }, - ParticleType::EntityEffect | ParticleType::TintedLeaves => { + // The oracle's item models: one layer whose sprite is named after the item. + ParticleType::Item => { + let item = o["item"].as_str()?; + ParticleOptions::item(vec![format!( + "item_{}", + item.strip_prefix("minecraft:").unwrap_or(item) + )]) + } + ParticleType::EntityEffect | ParticleType::TintedLeaves | ParticleType::Flash => { ParticleOptions::colored(ty, argb) } ParticleType::DragonBreath => ParticleOptions { @@ -137,6 +146,13 @@ fn main() -> Result<()> { world(&assets, &facts, true)?, ]; let mut engine = ParticleEngine::new(root, &HashMap::new()); + for (ty, item) in [ + (ParticleType::ItemSlime, "item_slime_ball"), + (ParticleType::ItemSnowball, "item_snowball"), + (ParticleType::ItemCobweb, "item_cobweb"), + ] { + engine.item_sprites.insert(ty, vec![item.to_owned()]); + } // The oracle's output: the seed line of each case. let mut seeds = Vec::new(); for line in BufReader::new(File::open(&args[2])?).lines() { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3cd8d5105..d6b027c57 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -45,6 +45,7 @@ mod golems; mod growth; mod hand; mod item_draw; +mod item_particles; mod jukebox; mod lan; mod lan_actions; diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 0a6cb379a..43049111a 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -418,7 +418,30 @@ impl Game<'_> { .unwrap_or(1.0) .clamp(0.01, 4.0), ), - ParticleType::Block | ParticleType::FallingDust | ParticleType::DustPillar => { + // ItemParticleOption: an item id, or a stack {id, ...}. + ParticleType::Item => { + let id = match field("item") { + Some(Tag::String(s)) => s.to_string_lossy(), + Some(Tag::Compound(c)) => { + c.get(&"id".into()).and_then(string).unwrap_or_default() + } + _ => String::new(), + }; + let id = if id.contains(':') { + id + } else { + format!("minecraft:{id}") + }; + self.item_particle(&horizon_client::items::ItemStack::new(&id, 1)) + } + ParticleType::ItemSlime | ParticleType::ItemSnowball | ParticleType::ItemCobweb => { + self.ensure_item_particle_sprites(); + ParticleOptions::simple(ty) + } + ParticleType::Block + | ParticleType::FallingDust + | ParticleType::DustPillar + | ParticleType::BlockMarker => { // BlockParticleOption: a block id, or {Name, Properties}. let text = match field("block_state") { Some(Tag::String(s)) => s.to_string_lossy(), diff --git a/crates/horizon-client/src/game/item_particles.rs b/crates/horizon-client/src/game/item_particles.rs new file mode 100644 index 000000000..a60fca68a --- /dev/null +++ b/crates/horizon-client/src/game/item_particles.rs @@ -0,0 +1,35 @@ +//! The sprites of item particles: `BreakingItemParticle.ItemParticleProvider.getSprite` +//! resolves the stack's model for the ground and picks a layer's particle sprite. +use super::Game; +use horizon_assets::item_model::DisplayContext; +use horizon_client::{ + items::ItemStack, + particles::{ParticleOptions, ParticleType}, +}; + +impl Game<'_> { + /// `ItemParticleOption(ITEM, stack)`: the layer particle sprites of the + /// stack's model resolved for the ground, with seed 0. + pub(super) fn item_particle(&self, stack: &ItemStack) -> ParticleOptions { + let state = self.resolve_item(stack, DisplayContext::Ground, None, 0); + ParticleOptions::item(state.layers.iter().map(|l| l.particle.clone()).collect()) + } + /// The slime ball, snowball and cobweb models behind `item_slime`, + /// `item_snowball` and `item_cobweb`, resolved on first use. + pub(super) fn ensure_item_particle_sprites(&mut self) { + if !self.particles.item_sprites.is_empty() { + return; + } + for (ty, item) in [ + (ParticleType::ItemSlime, "minecraft:slime_ball"), + (ParticleType::ItemSnowball, "minecraft:snowball"), + (ParticleType::ItemCobweb, "minecraft:cobweb"), + ] { + let sprites = self + .item_particle(&ItemStack::new(item, 1)) + .item + .unwrap_or_default(); + self.particles.item_sprites.insert(ty, sprites); + } + } +} diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index cf57a9abe..d34b1d7ab 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -83,9 +83,21 @@ impl Game<'_> { let count = num(8, 1.0)? as u32; let options = match ty { ParticleType::Dust => ParticleOptions::dust([1.0, 0.0, 0.0], 1.0), - ParticleType::Block | ParticleType::FallingDust | ParticleType::DustPillar => { + ParticleType::Block + | ParticleType::FallingDust + | ParticleType::DustPillar + | ParticleType::BlockMarker => { ParticleOptions::block(ty, "block/stone".into(), 0x808080) } + ParticleType::Item => self.item_particle( + &horizon_client::items::ItemStack::new("minecraft:apple", 1), + ), + ParticleType::ItemSlime + | ParticleType::ItemSnowball + | ParticleType::ItemCobweb => { + self.ensure_item_particle_sprites(); + ParticleOptions::simple(ty) + } _ => ParticleOptions::simple(ty), }; // ServerLevel.sendParticles: count 0 uses the delta as velocity. diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index f9ecd61ba..34d0957de 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -130,18 +130,69 @@ particle_types! { 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`: spawned regardless of distance. + /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): + /// spawned regardless of distance. pub fn override_limiter(self) -> bool { matches!( self, - Self::DamageIndicator + Self::BlockMarker + | Self::DamageIndicator | Self::ExplosionEmitter | Self::Explosion - | Self::Poof + | 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 ) } } @@ -161,6 +212,9 @@ pub struct ParticleOptions { pub to_color: [f32; 3], /// `TrailParticleOption`: the point it flies to and how many ticks it takes. pub trail: Option<([f64; 3], i32)>, + /// `ItemParticleOption`: the particle sprite of each layer of the item's + /// model as resolved for the ground. + pub item: Option>, } impl ParticleOptions { pub fn simple(ty: ParticleType) -> Self { @@ -171,6 +225,14 @@ impl ParticleOptions { scale: 1.0, to_color: [1.0, 0.0, 0.0], trail: None, + item: None, + } + } + /// `ItemParticleOption`: the stack's layer particle sprites (`BreakingItemParticle`). + pub fn item(layers: Vec) -> Self { + Self { + item: Some(layers), + ..Self::simple(ParticleType::Item) } } /// `DustColorTransitionOptions`. @@ -260,6 +322,8 @@ enum Size { ReversePortal, /// `ShriekParticle.getQuadSize`. Shriek, + /// `FireworkParticles.OverlayParticle.getQuadSize`: a sine pulse. + Flash, } #[derive(Clone, Copy, Debug, PartialEq)] enum Light { @@ -271,6 +335,8 @@ enum Light { AgeEmission, /// `addSmoothBlockEmission` with the age fraction to the fourth power. AgeEmission4, + /// `FireflyParticle.getLightCoords`: block light fading in and out, no sky. + Firefly, } #[derive(Clone, Copy, Debug, PartialEq)] enum Behaviour { @@ -359,6 +425,20 @@ enum Behaviour { Trail { target: [f64; 3], }, + /// `SquidInkParticle`: `SimpleAnimatedParticle`, sinking through air. + SquidInk, + /// `FireflyParticle`: wanders, fading in and out, gone inside blocks. + Firefly, + /// `WakeParticle` (fishing): grows and cycles four sprites. + Wake, + /// `DustPlumeParticle`: gravity and friction decay every tick. + DustPlume, + /// `FlyStraightTowardsParticle`: from its start along its motion back to + /// the start, the colour moving from one to the other. + FlyStraight { + start: [f64; 3], + colors: [u32; 2], + }, } #[derive(Clone, Copy, Debug, PartialEq)] enum DripStage { @@ -692,6 +772,11 @@ impl Particle { let b = (b * b) * (b * b); (sky, (block + (b.clamp(0.0, 1.0) * 240.0) as u32).min(240)) } + Light::Firefly => ( + 0, + (255.0 * fade_amount(self.lifetime_progress(self.age as f32 + partial), 0.1, 0.3)) + as u32, + ), } } fn quad_size(&self, a: f32) -> f32 { @@ -709,8 +794,27 @@ impl Particle { self.size * (1.0 - (self.age as f32 + a) / (self.lifetime as f32 * 1.5)) } Size::Shriek => self.size * (t * 0.75).clamp(0.0, 1.0), + Size::Flash => { + 7.1 * trig::sin(f64::from( + (self.age as f32 + a - 1.0) * 0.25 * std::f64::consts::PI as f32, + )) + } } } + /// `FireflyParticle.getLifetimeProgress`. + fn lifetime_progress(&self, age: f32) -> f32 { + (age / self.lifetime as f32).clamp(0.0, 1.0) + } +} +/// `FireflyParticle.getFadeAmount`. +fn fade_amount(progress: f32, fade_in: f32, fade_out: f32) -> f32 { + if progress >= 1.0 - fade_in { + (1.0 - progress) / fade_in + } else if progress <= fade_out { + progress / fade_out + } else { + 1.0 + } } /// A particle's fields as the parity probe reports them. @@ -827,6 +931,9 @@ pub struct ParticleEngine { starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>, + /// The item particles' sprites (`BreakingItemParticle`'s slime ball, snowball + /// and cobweb models, resolved for the ground), one per model layer. + pub item_sprites: HashMap>, } /// `ParticleGroup.MAX_PARTICLES` (per render group; one group here). const MAX_PARTICLES: usize = 16384; @@ -849,6 +956,7 @@ impl ParticleEngine { starters: Vec::new(), camera: [0.0; 3], sounds: Vec::new(), + item_sprites: HashMap::new(), }; let dir = root.join("assets/minecraft/particles"); for &ty in ParticleType::ALL { @@ -1227,12 +1335,22 @@ impl ParticleEngine { q.set = set; q } - T::Smoke | T::LargeSmoke | T::WhiteSmoke | T::Ash | T::WhiteAsh => { + T::Smoke | T::LargeSmoke | T::WhiteSmoke | T::Ash | T::WhiteAsh | T::DustPlume => { // BaseAshSmokeParticle(dir, xa, scale, colorRandom, maxLifetime, gravity, hasPhysics). let (dir, scale, color_random, max_lifetime, gravity, physics, vel) = match ty { T::Smoke | T::WhiteSmoke => ([0.1, 0.1, 0.1], 1.0, 0.3, 8, -0.1, true, v), T::LargeSmoke => ([0.1, 0.1, 0.1], 2.5, 0.3, 8, -0.1, true, v), T::Ash => ([0.1, -0.1, 0.1], 1.0, 0.5, 20, 0.1, false, [0.0; 3]), + // DustPlumeParticle: ya + 0.15F. + T::DustPlume => ( + [0.7, 0.6, 0.7], + 1.0, + 0.5, + 7, + 0.5, + false, + [v[0], v[1] + f64::from(0.15f32), v[2]], + ), _ => { // WhiteAshParticle.Provider draws the motion. let pr = &mut self.random; @@ -1267,6 +1385,15 @@ impl ParticleEngine { } q.size_curve = Size::GrowIn; q.behaviour = Behaviour::Animated; + if ty == T::DustPlume { + let shift = r.next_float() * 0.2; + q.set_color( + 186.0 / 255.0 - shift, + 177.0 / 255.0 - shift, + 194.0 / 255.0 - shift, + ); + q.behaviour = Behaviour::DustPlume; + } q.set = set; q } @@ -1740,9 +1867,9 @@ impl ParticleEngine { } q } - T::Poof | T::Snowflake => { + T::Poof | T::Snowflake | T::Spit => { let mut q = Particle::at(r, ty, p); - if ty == T::Poof { + if ty != T::Snowflake { q.gravity = -0.1; q.friction = 0.9; } else { @@ -1752,7 +1879,7 @@ impl ParticleEngine { for i in 0..3 { q.velocity[i] = v[i] + f64::from((r.next_float() * 2.0 - 1.0) * 0.05); } - if ty == T::Poof { + if ty != T::Snowflake { let col = r.next_float() * 0.3 + 0.7; q.set_color(col, col, col); q.size = 0.1 * (r.next_float() * r.next_float() * 6.0 + 1.0); @@ -1760,11 +1887,15 @@ impl ParticleEngine { q.size = 0.1 * (r.next_float() * r.next_float() + 1.0); } q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32 + 2; - q.behaviour = if ty == T::Poof { - Behaviour::Animated - } else { + q.behaviour = if ty == T::Snowflake { Behaviour::Snowflake + } else { + Behaviour::Animated }; + // SpitParticle: ExplodeParticle falling at gravity 0.5. + if ty == T::Spit { + q.gravity = 0.5; + } if ty == T::Snowflake { q.set_color(0.923, 0.964, 0.999); } @@ -2005,7 +2136,12 @@ impl ParticleEngine { q.set = set; q } - T::CherryLeaves | T::PaleOakLeaves | T::TintedLeaves => { + T::CherryLeaves + | T::PaleOakLeaves + | T::TintedLeaves + | T::RedPoplarLeaves + | T::OrangePoplarLeaves + | T::YellowPoplarLeaves => { let (fall, side, swirl, flow, scale, start) = if ty == T::CherryLeaves { (0.25f32, 2.0f32, false, true, 1.0f32, 0.0f32) } else { @@ -2041,7 +2177,13 @@ impl ParticleEngine { }; q } - T::Effect | T::InstantEffect | T::EntityEffect | T::Witch | T::Infested => { + T::Effect + | T::InstantEffect + | T::EntityEffect + | T::Witch + | T::Infested + | T::TrialOmen + | T::RaidOmen => { // SpellParticle: x/z velocity from `SpellParticle.RANDOM`, y from the option. let xa = 0.5 - self.spell_random.next_double(); let za = 0.5 - self.spell_random.next_double(); @@ -2117,6 +2259,239 @@ impl ParticleEngine { q.set_power(o.scale); q } + // AttackSweepParticle: `xAux` shrinks it; still, bright, animated over 4 ticks. + T::SweepAttack => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.lifetime = 4; + let col = r.next_float() * 0.6 + 0.4; + q.set_color(col, col, col); + q.size = 1.0 - v[0] as f32 * 0.5; + q.light = Light::FullBright; + q.behaviour = Behaviour::HugeExplosion; + q.set = set; + q + } + // GlowParticle and its providers. + T::Glow | T::WaxOn | T::WaxOff | T::ElectricSpark | T::Scrape => { + let pr = &mut self.random; + let start = if ty == T::Glow { + let xa = 0.5 - pr.next_double(); + [xa, v[1], 0.5 - pr.next_double()] + } else { + [0.0; 3] + }; + let mut q = Particle::moving(r, ty, p, start); + q.friction = 0.96; + q.speed_up_when_y_blocked = true; + q.size *= 0.75; + q.has_physics = false; + q.light = Light::AgeEmission; + q.behaviour = Behaviour::Animated; + q.set = set; + match ty { + T::ElectricSpark => { + q.set_color(1.0, 0.9, 1.0); + q.velocity = [v[0] * 0.25, v[1] * 0.25, v[2] * 0.25]; + q.lifetime = pr.next_int_bound(2).unwrap_or(0) + 2; + } + T::Glow => { + if pr.next_boolean() { + q.set_color(0.6, 1.0, 0.8); + } else { + q.set_color(0.08, 0.4, 0.4); + } + q.velocity[1] *= f64::from(0.2f32); + if v[0] == 0.0 && v[2] == 0.0 { + q.velocity[0] *= f64::from(0.1f32); + q.velocity[2] *= f64::from(0.1f32); + } + q.lifetime = (8.0 / (pr.next_double() * 0.8 + 0.2)) as i32; + } + T::Scrape => { + if pr.next_boolean() { + q.set_color(0.29, 0.58, 0.51); + } else { + q.set_color(0.43, 0.77, 0.62); + } + q.velocity = [v[0] * 0.01, v[1] * 0.01, v[2] * 0.01]; + q.lifetime = pr.next_int_bound(30).unwrap_or(0) + 10; + } + _ => { + if ty == T::WaxOn { + q.set_color(0.91, 0.55, 0.08); + } else { + q.set_color(1.0, 0.9, 1.0); + } + q.velocity = [v[0] * 0.01 / 2.0, v[1] * 0.01, v[2] * 0.01 / 2.0]; + q.lifetime = pr.next_int_bound(30).unwrap_or(0) + 10; + } + } + q + } + // SquidInkParticle (SimpleAnimatedParticle, gravity 0). + T::SquidInk | T::GlowSquidInk => { + let mut q = Particle::at(r, ty, p); + q.friction = 0.92; + q.size = 0.5; + if ty == T::GlowSquidInk { + // ARGB.colorFromFloat(1, 0.2, 0.8, 0.6), back to floats. + q.set_color(51.0 / 255.0, 204.0 / 255.0, 153.0 / 255.0); + } else { + q.set_color(0.0, 0.0, 0.0); + } + q.lifetime = (q.size * 12.0 / (r.next_float() * 0.8 + 0.2)) as i32; + q.has_physics = false; + q.velocity = v; + q.light = Light::FullBright; + q.behaviour = Behaviour::SquidInk; + q.set = set; + q + } + // BreakingItemParticle: a crumb of the item's sprite. + T::Item | T::ItemSlime | T::ItemSnowball | T::ItemCobweb | T::SulfurCubeGoo => { + let sprite = if ty == T::SulfurCubeGoo { + self.first(ty) + } else { + // ItemStackRenderState.pickParticleMaterial. + let layers = match ty { + T::Item => o.item.clone().unwrap_or_default(), + _ => self.item_sprites.get(&ty).cloned().unwrap_or_default(), + }; + if layers.is_empty() { + Sprite::Index(u32::MAX) + } else { + let i = self.random.next_int_bound(layers.len() as i32).unwrap_or(0); + Sprite::Named(layers[i as usize].clone()) + } + }; + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.sprite = sprite; + q.gravity = 1.0; + q.size /= 2.0; + let uo = r.next_float() * 3.0; + let vo = r.next_float() * 3.0; + q.uv = [(uo + 1.0) / 4.0, vo / 4.0, uo / 4.0, (vo + 1.0) / 4.0]; + if ty == T::Item { + for i in 0..3 { + q.velocity[i] = q.velocity[i] * f64::from(0.1f32) + v[i]; + } + } + q + } + // FireworkParticles.OverlayParticle: the flash of an explosion. + T::Flash => { + let mut q = Particle::at(r, ty, p); + q.lifetime = 4; + q.set_color(o.color[0], o.color[1], o.color[2]); + q.rgba[3] = o.color[3]; + q.size_curve = Size::Flash; + q + } + // FireflyParticle; the provider draws its motion, sprite and lifetime. + T::Firefly => { + let pr = &mut self.random; + let xa = 0.5 - pr.next_double(); + let ya = if pr.next_boolean() { v[1] } else { -v[1] }; + let za = 0.5 - pr.next_double(); + let sprite = self.sprite_from_set(ty); + let mut q = Particle::moving(r, ty, p, [xa, ya, za]); + q.sprite = sprite; + q.speed_up_when_y_blocked = true; + q.friction = 0.96; + q.size *= 0.75; + q.velocity[1] *= f64::from(0.8f32); + q.velocity[0] *= f64::from(0.8f32); + q.velocity[2] *= f64::from(0.8f32); + q.lifetime = self + .random + .next_int_between_inclusive(200, 300) + .unwrap_or(200); + q.scale(1.5); + q.rgba[3] = 0.0; + q.light = Light::Firefly; + q.behaviour = Behaviour::Firefly; + q + } + // TrialSpawnerDetectionParticle (scale 1.5 from the provider). + T::TrialSpawnerDetection | T::TrialSpawnerDetectionOminous => { + let scale = 1.5f32; + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.friction = 0.96; + q.gravity = -0.1; + q.speed_up_when_y_blocked = true; + q.velocity[0] *= 0.0; + q.velocity[1] *= 0.9; + q.velocity[2] *= 0.0; + for i in 0..3 { + q.velocity[i] += v[i]; + } + q.size *= 0.75 * scale; + // Mth.randomBetween(random, 0.5, 1.0). + q.lifetime = ((8.0 / (r.next_float() * (1.0 - 0.5) + 0.5) * scale) as i32).max(1); + q.light = Light::Block15; + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::Animated; + q.set = set; + q + } + // FlyStraightTowardsParticle.OminousSpawnProvider. + T::OminousSpawning => { + let sprite = self.sprite_from_set(ty); + let mut q = Particle::at(r, ty, p); + q.sprite = sprite; + q.velocity = v; + let start = [p[0] + v[0], p[1] + v[1], p[2] + v[2]]; + q.previous = start; + q.position = start; + q.size = 0.1 * (r.next_float() * 0.5 + 0.2); + q.has_physics = false; + q.free_move = true; + q.lifetime = (r.next_float() * 5.0) as i32 + 25; + q.light = Light::Block15; + q.behaviour = Behaviour::FlyStraight { + start: p, + colors: [0xFF45_AEFE, 0xFFFF_FFFF], + }; + // Mth.randomBetween(level.getRandom(), 3, 5). + let s = self.level_random.next_float() * (5.0 - 3.0) + 3.0; + q.scale(s); + q + } + // WakeParticle. + T::Fishing => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.velocity[0] *= f64::from(0.3f32); + q.velocity[1] = f64::from(r.next_float() * 0.2 + 0.1); + q.velocity[2] *= f64::from(0.3f32); + q.set_size(0.01, 0.01); + q.lifetime = (8.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32; + q.gravity = 0.0; + q.velocity = v; + q.behaviour = Behaviour::Wake; + q.set = set; + q + } + // SimpleVerticalParticle. + T::PauseMobGrowth | T::ResetMobGrowth => { + let mut q = Particle::moving(r, ty, p, v); + q.velocity = v; + q.gravity = 0.0; + q.velocity[1] += if ty == T::ResetMobGrowth { 0.03 } else { -0.03 }; + q.size *= r.next_float() * 0.6 + 0.5; + q.lifetime = 8; + q + } + // BlockMarker: the block's particle sprite, half a block wide, 80 ticks. + T::BlockMarker => { + let (sprite, _) = o.block.clone()?; + let mut q = Particle::at(r, ty, p); + q.sprite = Sprite::Named(sprite); + q.gravity = 0.0; + q.lifetime = 80; + q.has_physics = false; + q.size = 0.5; + q + } T::Trail => { let (target, duration) = o.trail?; let mut q = Particle::moving(r, ty, p, v); @@ -2256,6 +2631,19 @@ impl ParticleEngine { } } } + // The flash: ColorParticleOption.create(FLASH, first colour), alpha 0. + let c = colors[0]; + let rgba = [ + ((c >> 16) & 255) as f32 / 255.0, + ((c >> 8) & 255) as f32 / 255.0, + (c & 255) as f32 / 255.0, + ((c >> 24) & 255) as f32 / 255.0, + ]; + self.create( + &ParticleOptions::colored(ParticleType::Flash, rgba), + s.at, + [0.0; 3], + ); } s.life += 1; if s.life > s.lifetime { @@ -2886,6 +3274,93 @@ impl ParticleEngine { p.velocity[1] -= f64::from(0.003f32); p.velocity[1] = p.velocity[1].max(f64::from(-0.14f32)); } + Behaviour::SquidInk => { + // SimpleAnimatedParticle.tick, then SquidInkParticle's. + p.base_tick(level); + self.sprite_from_age(p); + let half = |p: &mut Particle| { + if p.age > p.lifetime / 2 { + p.rgba[3] = + 1.0 - (p.age as f32 - (p.lifetime / 2) as f32) / p.lifetime as f32; + } + }; + half(p); + if !p.removed { + self.sprite_from_age(p); + half(p); + let b = ParticleLevel::block_at(p.position); + if level.facts.is_air(level.world.block(b[0], b[1], b[2])) { + p.velocity[1] -= f64::from(0.0074f32); + } + } + } + Behaviour::Firefly => { + p.base_tick(level); + let b = ParticleLevel::block_at(p.position); + if !level.facts.is_air(level.world.block(b[0], b[1], b[2])) { + p.removed = true; + } else { + p.rgba[3] = fade_amount(p.lifetime_progress(p.age as f32), 0.3, 0.5); + if p.random.next_float() > 0.95 || p.age == 1 { + let r = &mut p.random; + let mut speed = || f64::from(-0.05f32 + 0.1 * r.next_float()); + p.velocity = [speed(), speed(), speed()]; + } + } + } + Behaviour::Wake => { + p.previous = p.position; + let life = 60 - p.lifetime; + let lifetime = p.lifetime; + p.lifetime -= 1; + if lifetime <= 0 { + p.removed = true; + return; + } + p.velocity[1] -= f64::from(p.gravity); + p.move_by(level, p.velocity); + for c in &mut p.velocity { + *c *= f64::from(0.98f32); + } + let size = life as f32 * 0.001; + p.set_size(size, size); + // SpriteSet.get(life % 4, 4). + if let Some(set) = p.set { + let sprites = &self.set_sprites[set as usize]; + let index = (life % 4) as usize * (sprites.len() - 1) / 4; + p.sprite = Sprite::Index(sprites[index]); + } + } + Behaviour::DustPlume => { + p.gravity *= 0.88; + p.friction *= 0.92; + p.base_tick(level); + self.sprite_from_age(p); + } + Behaviour::FlyStraight { start, colors } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let normalized = p.age as f32 / p.lifetime as f32; + let along = 1.0 - normalized; + for i in 0..3 { + p.position[i] = start[i] + p.velocity[i] * f64::from(along); + } + // ARGB.srgbLerp: Mth.lerpInt on each 8-bit channel. + let lerp = |shift: u32| { + let (a, b) = ( + (colors[0] >> shift & 255) as i32, + (colors[1] >> shift & 255) as i32, + ); + (a + (normalized * (b - a) as f32).floor() as i32) as f32 / 255.0 + }; + p.set_color(lerp(16), lerp(8), lerp(0)); + p.rgba[3] = lerp(24); + } Behaviour::DragonBreath { mut hit_ground } => { p.previous = p.position; let age = p.age; @@ -2961,6 +3436,10 @@ impl ParticleEngine { }; let size = p.quad_size(partial); let mut alpha = p.rgba[3]; + // OverlayParticle.extract: the flash fades as it pulses. + if p.ty == ParticleType::Flash { + alpha = 0.6 - (p.age as f32 + partial - 1.0) * 0.25 * 0.5; + } if let Behaviour::FlyTowards { alpha: la, .. } = p.behaviour { alpha = lifetime_alpha(la, p.age, p.lifetime, partial); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java index c1531c1a0..f060351b3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java @@ -198,6 +198,7 @@ public final class VanillaParticleProvidersOracle { public static void main(String[] args) throws Exception { SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); + ParityData.init(); // item components, for the item particle providers' stacks var u = Class.forName("sun.misc.Unsafe"); unsafe = field(u, "theUnsafe").get(null); allocate = u.getMethod("allocateInstance", Class.class); var mc = make(Minecraft.class); field(Minecraft.class, "instance").set(null, mc); var manager = make(ModelManager.class); field(ModelManager.class, "blockStateModelSet").set(manager, new Models()); diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index b413c38fe..afd283359 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -31,11 +31,15 @@ falling_lava falling_nectar falling_obsidian_tear falling_spore_blossom falling_ gust gust_emitter_large gust_emitter_small happy_villager heart infested landing_honey landing_lava landing_obsidian_tear large_smoke lava mycelium nautilus note pale_oak_leaves poof portal rain reverse_portal sculk_charge_pop sculk_soul smoke small_flame small_gust sneeze snowflake sonic_boom soul soul_fire_flame splash -spore_blossom_air totem_of_undying underwater vault_connection warped_spore white_ash white_smoke witch""".split() +spore_blossom_air totem_of_undying underwater vault_connection warped_spore white_ash white_smoke witch +sweep_attack glow wax_on wax_off electric_spark scrape squid_ink glow_squid_ink item_slime item_snowball item_cobweb +sulfur_cube_goo firefly trial_spawner_detection trial_spawner_detection_ominous trial_omen raid_omen ominous_spawning +spit fishing dust_plume red_poplar_leaves orange_poplar_leaves yellow_poplar_leaves pause_mob_growth +reset_mob_growth""".split() def options(kind, rng): - if kind in ('block', 'block_crumble', 'dust_pillar', 'falling_dust'): + if kind in ('block', 'block_crumble', 'dust_pillar', 'falling_dust', 'block_marker'): return dict(state=STONE) if kind == 'dust': return dict(color=rng.choice([0xFF0000, 0x3A9E2C, 0xFFFFFF]), scale=rng.choice([1.0, 0.5, 2.0])) @@ -47,6 +51,10 @@ def options(kind, rng): return dict(color=rng.choice([0xFF3366CC, 0x26AA00FF])) if kind == 'tinted_leaves': return dict(color=0xFF48B518) + if kind == 'flash': + return dict(color=rng.choice([0xFF3366CC, 0x00FFAA00])) + if kind == 'item': + return dict(item=rng.choice(['minecraft:apple', 'minecraft:cooked_beef', 'minecraft:egg'])) if kind == 'dragon_breath': return dict(scale=rng.choice([1.0, 0.25])) if kind == 'sculk_charge': @@ -60,7 +68,8 @@ def options(kind, rng): def cases(rng): kinds = SIMPLE + ['block', 'block_crumble', 'dust_pillar', 'falling_dust', 'dust', 'dust_color_transition', 'effect', - 'instant_effect', 'entity_effect', 'tinted_leaves', 'dragon_breath', 'sculk_charge', 'shriek', 'trail'] + 'instant_effect', 'entity_effect', 'tinted_leaves', 'dragon_breath', 'sculk_charge', 'shriek', 'trail', + 'block_marker', 'flash', 'item'] # Dyadic values: serde_json's decimal parsing may round others a unit off. starts = [([0.3125, 66.6875, -0.40625], False), ([0.3125, 64.046875, -0.40625], True), ([-5.75, 64.59375, 3.125], True)] velocities = [[0.0, 0.0, 0.0], [0.078125, 0.125, -0.046875], [0.0, -0.296875, 0.0], [0.5, 0.0, 0.25]] @@ -99,7 +108,8 @@ def decode(token): # (Intel's libm) round a fraction of a percent of arguments a unit apart from # the platform libm horizon_core::jmath uses, so their motion is compared to # 1e-12 relative error; everything else about them, and every other type, exactly. -LIBM = {'cherry_leaves', 'pale_oak_leaves', 'tinted_leaves'} +LIBM = {'cherry_leaves', 'pale_oak_leaves', 'tinted_leaves', 'red_poplar_leaves', 'orange_poplar_leaves', + 'yellow_poplar_leaves'} def sections(path): From 9fa3a684c6bc5c45d456b54fb5ec7d388d7abb42 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:03:26 +0200 Subject: [PATCH 04/11] horizon-prepare: the resource preparation in Rust A port of tools/prepare_native_client.py and the helpers it imported from lab.py and the test_*_parity.py modules: the player's pinned game files are imported and checked against research-lock.json, the client's assets and data copied, the vanilla exporters compiled and run with the JDK (JAVA_HOME, the PATH, or java_home on macOS, at the pinned java_major), and the resources and their manifest written byte for byte as the script wrote them, with its sha256-keyed skips. tools/compare_prepare.py checks that against the Python preparer. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 184 ++++ Cargo.toml | 2 +- crates/horizon-prepare/Cargo.toml | 19 + crates/horizon-prepare/build.rs | 38 + crates/horizon-prepare/src/artifacts.rs | 681 ++++++++++++++ crates/horizon-prepare/src/inventory.rs | 177 ++++ crates/horizon-prepare/src/java.rs | 179 ++++ crates/horizon-prepare/src/lib.rs | 1134 +++++++++++++++++++++++ crates/horizon-prepare/src/main.rs | 109 +++ crates/horizon-prepare/src/pyjson.rs | 541 +++++++++++ crates/horizon-prepare/src/survival.rs | 146 +++ tools/compare_prepare.py | 149 +++ 12 files changed, 3358 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-prepare/Cargo.toml create mode 100644 crates/horizon-prepare/build.rs create mode 100644 crates/horizon-prepare/src/artifacts.rs create mode 100644 crates/horizon-prepare/src/inventory.rs create mode 100644 crates/horizon-prepare/src/java.rs create mode 100644 crates/horizon-prepare/src/lib.rs create mode 100644 crates/horizon-prepare/src/main.rs create mode 100644 crates/horizon-prepare/src/pyjson.rs create mode 100644 crates/horizon-prepare/src/survival.rs create mode 100644 tools/compare_prepare.py diff --git a/Cargo.lock b/Cargo.lock index f0e8c5987..b95c1ab9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,6 +37,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -99,6 +108,15 @@ dependencies = [ "libc", ] +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "arboard" version = "3.6.1" @@ -183,6 +201,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -412,6 +439,15 @@ dependencies = [ "windows 0.54.0", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -433,6 +469,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -445,6 +491,27 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -461,6 +528,17 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "dlib" version = "0.5.3" @@ -622,6 +700,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -761,6 +849,16 @@ dependencies = [ "libm", ] +[[package]] +name = "horizon-prepare" +version = "0.1.0" +dependencies = [ + "regex", + "sha1", + "sha2", + "zip", +] + [[package]] name = "horizon-protocol" version = "0.1.0" @@ -1754,6 +1852,35 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -1889,6 +2016,28 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -2214,6 +2363,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.26" @@ -3068,6 +3223,23 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zip" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "displaydoc", + "flate2", + "indexmap", + "memchr", + "thiserror 2.0.21", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -3079,3 +3251,15 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/Cargo.toml b/Cargo.toml index a0eb0c0f2..46f2b68fe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher"] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme"] +members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare"] resolver = "2" [workspace.package] diff --git a/crates/horizon-prepare/Cargo.toml b/crates/horizon-prepare/Cargo.toml new file mode 100644 index 000000000..3d62202bd --- /dev/null +++ b/crates/horizon-prepare/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "horizon-prepare" +version = "0.1.0" +edition = "2021" +license = "MIT" +description = "Prepares Horizon's resources from the player's own Minecraft: imports and checks the pinned jars, runs the vanilla exporters, writes the resource folder" + +[dependencies] +regex = { version = "1", default-features = false, features = ["std", "unicode-perl"] } +sha1 = "0.10" +sha2 = "0.10" +zip = { version = "2", default-features = false, features = ["deflate"] } + +[build-dependencies] +sha2 = "0.10" + +[[bin]] +name = "horizon-prepare" +path = "src/main.rs" diff --git a/crates/horizon-prepare/build.rs b/crates/horizon-prepare/build.rs new file mode 100644 index 000000000..fa2ef8a11 --- /dev/null +++ b/crates/horizon-prepare/build.rs @@ -0,0 +1,38 @@ +//! HORIZON_PREPARE_SOURCES_SHA256: a digest of this crate's sources, which the launcher compares +//! with a version folder's copy to know whether it may prepare that version in-process. Keep the +//! algorithm the same as `horizon_prepare::sources_sha256`. + +use sha2::Digest; +use std::fs; +use std::path::Path; + +fn main() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")); + let mut files = Vec::new(); + for name in ["Cargo.toml", "build.rs"] { + println!("cargo:rerun-if-changed={name}"); + files.push((name.to_string(), fs::read(dir.join(name)).unwrap())); + } + println!("cargo:rerun-if-changed=src"); + let mut sources: Vec = fs::read_dir(dir.join("src")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|n| n.ends_with(".rs")) + .collect(); + sources.sort(); + for name in sources { + println!("cargo:rerun-if-changed=src/{name}"); + files.push(( + format!("src/{name}"), + fs::read(dir.join("src").join(&name)).unwrap(), + )); + } + let mut hash = sha2::Sha256::new(); + for (name, data) in files { + let data: Vec = data.into_iter().filter(|b| *b != b'\r').collect(); + hash.update(format!("{name}\0{}\0", data.len())); + hash.update(&data); + } + let hex: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect(); + println!("cargo:rustc-env=HORIZON_PREPARE_SOURCES_SHA256={hex}"); +} diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs new file mode 100644 index 000000000..c3aa10280 --- /dev/null +++ b/crates/horizon-prepare/src/artifacts.rs @@ -0,0 +1,681 @@ +//! The player's own game files: the pinned version JSON, client jar and libraries from their +//! official launcher install, and the server jar they downloaded, each checked against +//! research-lock.json before it is copied to `.local/minecraft/` (tools/lab.py's +//! `prepare`, which the Python preparer ran first), then checked again on every run +//! (tools/test_rust_parity.py's `verify_artifacts`). + +use crate::pyjson::{self, Value}; +use crate::{digest, read_json, relative_display, write_json, Log}; +use std::collections::HashMap; +use std::fs; +use std::path::{Component, Path, PathBuf}; + +const LAUNCHER_HINT: &str = + "Horizon does not download the game: install Minecraft Java Edition with the official \ +launcher, play {version} once, then rerun. If the launcher uses another game directory, \ +pass --minecraft-dir or set HORIZON_MINECRAFT_DIR."; +const SERVER_HINT: &str = "Horizon does not download the game: download the {version} server jar yourself (minecraft.net/download/server \ +while {version} is the current release, otherwise the downloads.server.url in your launcher's \ +versions/{version}/{version}.json), then pass --server-jar PATH or set HORIZON_SERVER_JAR."; + +fn hint(text: &str, version: &str) -> String { + text.replace("{version}", version) +} + +/// research-lock.json and the folder the pinned version's files go to. +pub struct Lock { + pub json: Value, + pub version: String, + pub java_major: i64, + pub directory: PathBuf, +} + +impl Lock { + pub fn read(root: &Path) -> Result { + let json = read_json(&root.join("research-lock.json"))?; + let game = json + .get("minecraft") + .ok_or("research-lock.json has no minecraft")?; + let version = game + .get("version") + .and_then(Value::as_str) + .ok_or("research-lock.json has no minecraft version")? + .to_string(); + if version.is_empty() + || !version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) + || version == "." + || version == ".." + { + return Err("Unsafe version identifier in lock file".into()); + } + let java_major = game + .get("java_major") + .and_then(Value::as_i64) + .ok_or("research-lock.json has no java_major")?; + let directory = root.join(".local/minecraft").join(&version); + Ok(Lock { + json, + version, + java_major, + directory, + }) + } + + fn pin(&self, key: &str) -> Result<&str, String> { + self.json + .get("minecraft") + .and_then(|m| m.get(key)) + .and_then(Value::as_str) + .ok_or_else(|| format!("research-lock.json has no minecraft {key}")) + } + + /// Mojang republishes a version JSON for asset-index changes; every known one is accepted. + fn manifest_accepted(&self, checksum: &str) -> bool { + let game = self.json.get("minecraft"); + self.pin("manifest_sha1").is_ok_and(|pin| pin == checksum) + || game + .and_then(|g| g.get("accepted_manifest_sha1")) + .and_then(Value::as_array) + .is_some_and(|list| list.iter().any(|v| v.as_str() == Some(checksum))) + } +} + +fn home() -> PathBuf { + let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; + std::env::var_os(var) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")) +} + +/// Python's `Path.expanduser` for the forms players type: `~` and `~/...`. +fn expand_user(path: &Path) -> PathBuf { + let mut components = path.components(); + match components.next() { + Some(Component::Normal(first)) if first == "~" => home().join(components.as_path()), + _ => path.to_path_buf(), + } +} + +/// The official launcher's game directory, which holds the player's own copy of the game. +pub fn minecraft_dir(chosen: Option<&Path>) -> PathBuf { + if let Some(dir) = chosen.filter(|d| !d.as_os_str().is_empty()) { + return expand_user(dir); + } + if let Some(dir) = std::env::var_os("HORIZON_MINECRAFT_DIR").filter(|d| !d.is_empty()) { + return expand_user(Path::new(&dir)); + } + if cfg!(target_os = "macos") { + home().join("Library/Application Support/minecraft") + } else if cfg!(windows) { + std::env::var_os("APPDATA") + .map(PathBuf::from) + .unwrap_or_else(home) + .join(".minecraft") + } else { + home().join(".minecraft") + } +} + +/// Copy one file from the player's install, checked like a download; an existing verified +/// copy is kept. +fn import_copy( + source: &Path, + destination: &Path, + checksum: &str, + algorithm: &str, + hint: &str, +) -> Result { + fs::create_dir_all(destination.parent().unwrap()).map_err(|e| e.to_string())?; + if destination.exists() && digest(destination, algorithm)? == checksum { + return Ok(destination.to_path_buf()); + } + if !source.is_file() { + return Err(format!("Missing {}. {hint}", source.display()) + .trim() + .to_string()); + } + let actual = digest(source, algorithm)?; + if actual != checksum { + return Err(format!( + "{} is not the pinned file: expected {algorithm} {checksum}, got {actual}", + source.display() + )); + } + let temporary = destination.with_file_name(format!( + ".{}.partial-{}", + destination.file_name().unwrap().to_string_lossy(), + std::process::id() + )); + let copied = fs::copy(source, &temporary).and_then(|_| fs::rename(&temporary, destination)); + let _ = fs::remove_file(&temporary); + copied.map_err(|e| format!("{}: {e}", destination.display()))?; + Ok(destination.to_path_buf()) +} + +/// The pinned version JSON from the launcher's versions/ directory. The launcher's copy wins +/// over the cached one so the manifest matches the asset index installed alongside it. +fn import_manifest(lock: &Lock, minecraft: &Path) -> Result { + let version = &lock.version; + let destination = lock.directory.join("manifest.json"); + let source = minecraft + .join("versions") + .join(version) + .join(format!("{version}.json")); + if source.is_file() { + let manifest = read_json(&source)?; + let downloads = manifest.get("downloads"); + let sha1 = |side: &str| { + downloads + .and_then(|d| d.get(side)) + .and_then(|d| d.get("sha1")) + .and_then(Value::as_str) + }; + if manifest.get("id").and_then(Value::as_str) != Some(version) + || sha1("client") != Some(lock.pin("client_sha1")?) + || sha1("server") != Some(lock.pin("server_sha1")?) + { + return Err(format!( + "{} does not describe the pinned {version} release", + source.display() + )); + } + let checksum = digest(&source, "sha1")?; + if !lock.manifest_accepted(&checksum) { + return Err(format!( + "{} is a {version} version file Horizon does not know yet (sha1 {checksum}); \ + Mojang may have republished it. Update Horizon, or report it if this is the latest release.", + source.display() + )); + } + if !(destination.exists() && digest(&destination, "sha1")? == checksum) { + fs::create_dir_all(&lock.directory).map_err(|e| e.to_string())?; + fs::copy(&source, &destination).map_err(|e| e.to_string())?; + } + } else if !(destination.exists() && lock.manifest_accepted(&digest(&destination, "sha1")?)) { + return Err(format!( + "Missing {}. {}", + source.display(), + hint(LAUNCHER_HINT, version) + )); + } + let manifest = read_json(&destination)?; + let java = manifest + .get("javaVersion") + .and_then(|j| j.get("majorVersion")) + .and_then(Value::as_i64); + if java != Some(lock.java_major) { + return Err("Manifest Java version does not match lock file".into()); + } + Ok(manifest) +} + +fn import_server(lock: &Lock, server_jar: Option<&Path>) -> Result { + let version = &lock.version; + let destination = lock.directory.join("jars/server.jar"); + let checksum = lock.pin("server_sha1")?; + let hint = hint(SERVER_HINT, version); + let source = server_jar + .map(Path::to_path_buf) + .or_else(|| std::env::var_os("HORIZON_SERVER_JAR").map(PathBuf::from)); + let Some(source) = source else { + if destination.exists() && digest(&destination, "sha1")? == checksum { + return Ok(destination); + } + return Err(format!("No {version} server jar. {hint}")); + }; + import_copy(&expand_user(&source), &destination, checksum, "sha1", &hint) +} + +/// The launcher's `os.name` for this machine. +fn rule_system() -> &'static str { + if cfg!(target_os = "macos") { + "osx" + } else if cfg!(windows) { + "windows" + } else { + "linux" + } +} + +/// This machine's architecture and its aliases, as Python's `platform.machine()` names them. +fn rule_architectures() -> Vec<&'static str> { + match std::env::consts::ARCH { + "x86_64" => vec!["x86_64", "amd64", "x64"], + "aarch64" => vec!["arm64", "aarch64"], + "x86" => vec!["i686"], + other => vec![other], + } +} + +/// The kernel release Python's `platform.release()` reports (only old version JSONs ask). +fn os_release() -> String { + #[cfg(unix)] + { + if let Ok(out) = std::process::Command::new("uname").arg("-r").output() { + return String::from_utf8_lossy(&out.stdout).trim().to_string(); + } + } + String::new() +} + +/// The official launcher's rules: the last matching rule decides, no rules means allowed. +fn library_allowed(library: &Value) -> Result { + let system = rule_system(); + let architectures = rule_architectures(); + let rules = library + .get("rules") + .and_then(Value::as_array) + .unwrap_or(&[]); + let mut allowed = rules.is_empty(); + for rule in rules { + let empty = Value::Object(Vec::new()); + let os = rule.get("os").unwrap_or(&empty); + if os.get("name").and_then(Value::as_str).unwrap_or(system) != system { + continue; + } + if let Some(arch) = os.get("arch") { + let pattern = regex::Regex::new(&format!("^(?:{})$", arch.as_str().unwrap_or(""))) + .map_err(|e| e.to_string())?; + if !architectures.iter().any(|name| pattern.is_match(name)) { + continue; + } + } + if let Some(version) = os.get("version") { + let pattern = + regex::Regex::new(version.as_str().unwrap_or("")).map_err(|e| e.to_string())?; + if !pattern.is_match(&os_release()) { + continue; + } + } + if rule.get("features").is_some_and(|f| match f { + Value::Object(o) => !o.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Null | Value::Bool(false) => false, + Value::Str(s) => !s.is_empty(), + _ => true, + }) { + continue; + } + allowed = rule.get("action").and_then(Value::as_str) == Some("allow"); + } + Ok(allowed) +} + +fn classifier_ends_with(classifier: &str, names: &[&str]) -> bool { + names.iter().any(|name| { + classifier == *name + || classifier + .strip_suffix(name) + .is_some_and(|rest| rest.ends_with('-')) + }) +} + +/// Modern manifests list x64 and ARM natives with OS-only rules; keep this machine's. A plain +/// natives- jar is the x64 build when the manifest also lists an ARM variant of it. +fn native_library_matches(library: &Value, names: &[&str]) -> bool { + let arm = rule_architectures().contains(&"arm64"); + let name = library.get("name").and_then(Value::as_str).unwrap_or(""); + let classifier = name.split(':').nth(3).unwrap_or(""); + if classifier_ends_with(classifier, &["arm64", "aarch64", "aarch_64"]) { + return arm; + } + if classifier_ends_with(classifier, &["x86_64", "x64"]) { + return !arm; + } + if arm && classifier.starts_with("natives-") { + return !["arm64", "aarch64"] + .iter() + .any(|suffix| names.contains(&format!("{name}-{suffix}").as_str())); + } + true +} + +/// The client libraries the official launcher installs on this OS and architecture. +fn client_library_artifacts(manifest: &Value) -> Result, String> { + let libraries = manifest + .get("libraries") + .and_then(Value::as_array) + .ok_or("The version JSON has no libraries")?; + let names: Vec<&str> = libraries + .iter() + .filter_map(|l| l.get("name").and_then(Value::as_str)) + .collect(); + let mut artifacts = Vec::new(); + for library in libraries { + let Some(artifact) = library.get("downloads").and_then(|d| d.get("artifact")) else { + continue; + }; + if library_allowed(library)? && native_library_matches(library, &names) { + artifacts.push(artifact); + } + } + Ok(artifacts) +} + +/// A relative path with only normal components and forward slashes, from a manifest or bundle. +fn safe_relative(path: &str) -> Option { + if path.contains('\\') || path.starts_with('/') { + return None; + } + let parts: Vec<&str> = path + .split('/') + .filter(|p| !p.is_empty() && *p != ".") + .collect(); + if parts.contains(&"..") || (cfg!(windows) && parts.first().is_some_and(|p| p.contains(':'))) { + return None; + } + Some(parts.iter().collect()) +} + +fn artifact_fields(artifact: &Value) -> Result<(&str, &str), String> { + let path = artifact.get("path").and_then(Value::as_str); + let sha1 = artifact.get("sha1").and_then(Value::as_str); + path.zip(sha1) + .ok_or_else(|| "A library in the version JSON has no path or sha1".to_string()) +} + +/// `(sha256, identifier, path)` lines of a server bundle's versions.list or libraries.list. +fn bundle_entries( + archive: &mut zip::ZipArchive, + name: &str, +) -> Result, String> { + let text = crate::zip_text(archive, name)?; + let mut entries = Vec::new(); + for line in crate::split_lines(&text) { + if line.trim().is_empty() { + continue; + } + let fields: Vec<&str> = line.split('\t').collect(); + let [checksum, identifier, relative] = fields[..] else { + return Err(format!("Malformed line in {name}")); + }; + let path = + safe_relative(relative).ok_or_else(|| format!("Unsafe bundled path: {relative}"))?; + // PurePosixPath's text: empty and `.` parts dropped. + let posix = relative + .split('/') + .filter(|p| !p.is_empty() && *p != ".") + .collect::>() + .join("/"); + entries.push((checksum.to_string(), identifier.to_string(), path, posix)); + } + Ok(entries) +} + +fn extract_verified( + archive: &mut zip::ZipArchive, + member: &str, + destination: &Path, + checksum: &str, +) -> Result<(), String> { + let data = crate::zip_bytes(archive, member)?; + if crate::sha256_hex(&data) != checksum { + return Err(format!("Bundled artifact checksum mismatch: {member}")); + } + fs::create_dir_all(destination.parent().unwrap()).map_err(|e| e.to_string())?; + fs::write(destination, data).map_err(|e| format!("{}: {e}", destination.display())) +} + +/// Modern server downloads are launchers: the game jar and its libraries are inside. +fn unpack_server( + server: PathBuf, + directory: &Path, + version: &str, +) -> Result<(PathBuf, Vec), String> { + let mut archive = crate::open_zip(&server)?; + if archive.index_for_name("META-INF/versions.list").is_none() { + return Ok((server, Vec::new())); + } + let versions = bundle_entries(&mut archive, "META-INF/versions.list")?; + if versions.len() != 1 || versions[0].1 != version { + return Err("Expected one bundled server matching the pinned version".into()); + } + let (checksum, _, _, relative) = &versions[0]; + let game = directory.join("jars/server-game.jar"); + extract_verified( + &mut archive, + &format!("META-INF/versions/{relative}"), + &game, + checksum, + )?; + let mut libraries = Vec::new(); + for (checksum, _, path, relative) in bundle_entries(&mut archive, "META-INF/libraries.list")? { + let destination = directory.join("libraries/server").join(path); + extract_verified( + &mut archive, + &format!("META-INF/libraries/{relative}"), + &destination, + checksum.as_str(), + )?; + libraries.push(destination); + } + Ok((game, libraries)) +} + +/// Imports the player's own pinned game files into `.local/minecraft/` and writes the +/// class inventories and prepared.json (tools/lab.py `prepare`). The decompiler lab.py also +/// fetches is a development tool, not something preparing needs; `tools/lab.py prepare` gets it. +pub fn import( + root: &Path, + lock: &Lock, + minecraft: Option<&Path>, + server_jar: Option<&Path>, + log: Log, +) -> Result<(), String> { + let minecraft = minecraft_dir(minecraft); + let version = &lock.version; + let manifest = import_manifest(lock, &minecraft)?; + let client = import_copy( + &minecraft + .join("versions") + .join(version) + .join(format!("{version}.jar")), + &lock.directory.join("jars/client.jar"), + lock.pin("client_sha1")?, + "sha1", + &hint(LAUNCHER_HINT, version), + )?; + let downloads = manifest.get("downloads"); + if downloads.and_then(|d| d.get("client_mappings")).is_some() + || downloads.and_then(|d| d.get("server_mappings")).is_some() + { + return Err( + "This workflow targets unobfuscated releases. Older releases need a remapping stage." + .into(), + ); + } + let id = manifest + .get("id") + .and_then(Value::as_str) + .ok_or("The version JSON has no id")?; + log(&format!( + "Imported client {id} from {}", + minecraft.display() + )); + let server = import_server(lock, server_jar)?; + let (server, server_libraries) = unpack_server(server, &lock.directory, id)?; + let mut client_libraries = Vec::new(); + for artifact in client_library_artifacts(&manifest)? { + let (path, sha1) = artifact_fields(artifact)?; + let relative = safe_relative(path).ok_or("Unsafe library path")?; + client_libraries.push(import_copy( + &minecraft.join("libraries").join(&relative), + &lock.directory.join("libraries/client").join(&relative), + sha1, + "sha1", + &hint(LAUNCHER_HINT, version), + )?); + } + for (side, jar) in [("client", &client), ("server", &server)] { + let data = crate::inventory::inventory(jar)?; + let count = |key| data.get(key).cloned().unwrap_or(Value::Null); + write_json( + &lock + .directory + .join(format!("reports/{side}-inventory.json")), + &data, + )?; + log(&format!( + "{side}: {} classes, {} methods", + pyjson::dumps(&count("class_count"), &pyjson::DEFAULT), + pyjson::dumps(&count("method_count"), &pyjson::DEFAULT) + )); + } + let paths = |list: &[PathBuf]| -> Result { + Ok(Value::Array( + list.iter() + .map(|p| relative_display(p, root).map(Value::Str)) + .collect::>()?, + )) + }; + write_json( + &lock.directory.join("prepared.json"), + &Value::Object(vec![ + ("version".into(), Value::str(id)), + ( + "jars".into(), + Value::Object(vec![ + ( + "client".into(), + Value::Str(relative_display(&client, root)?), + ), + ( + "server".into(), + Value::Str(relative_display(&server, root)?), + ), + ]), + ), + ( + "libraries".into(), + Value::Object(vec![ + ("client".into(), paths(&client_libraries)?), + ("server".into(), paths(&server_libraries)?), + ]), + ), + ]), + )?; + log(&format!("Artifacts: {}", lock.directory.display())); + Ok(()) +} + +/// The checked jars (`client`, `server` = the bundle's inner game jar) and the server +/// libraries, authenticated against the lock and the bundle's own checksums on every run. +pub struct Artifacts { + pub manifest: Value, + pub jars: HashMap<&'static str, PathBuf>, + pub libraries: Vec, +} + +pub fn verify(lock: &Lock) -> Result { + let manifest_path = lock.directory.join("manifest.json"); + if !manifest_path.exists() { + return Err(format!( + "{} is missing: prepare with --prepare first", + manifest_path.display() + )); + } + if !lock.manifest_accepted(&digest(&manifest_path, "sha1")?) { + return Err("Manifest checksum changed; prepare again with --prepare".into()); + } + let manifest = read_json(&manifest_path)?; + let id = manifest.get("id").and_then(Value::as_str).unwrap_or(""); + if id != lock.version { + return Err("Manifest version differs from the lock".into()); + } + let mut jars = HashMap::new(); + for side in ["client", "server"] { + let jar = lock.directory.join(format!("jars/{side}.jar")); + let pinned = manifest + .get("downloads") + .and_then(|d| d.get(side)) + .and_then(|d| d.get("sha1")) + .and_then(Value::as_str); + if !jar.exists() || Some(digest(&jar, "sha1")?.as_str()) != pinned { + return Err(format!( + "{side} artifact checksum changed; prepare again with --prepare" + )); + } + jars.insert(side, jar); + } + let mut archive = crate::open_zip(&jars["server"])?; + let versions = bundle_entries(&mut archive, "META-INF/versions.list")?; + if versions.len() != 1 || versions[0].1 != id { + return Err("Unexpected server bundle".into()); + } + let game = lock.directory.join("jars/server-game.jar"); + if !game.exists() || digest(&game, "sha256")? != versions[0].0 { + return Err("Inner server artifact checksum changed".into()); + } + jars.insert("server", game); + let mut libraries = Vec::new(); + for (checksum, _, path, relative) in bundle_entries(&mut archive, "META-INF/libraries.list")? { + let library = lock.directory.join("libraries/server").join(path); + if !library.exists() || digest(&library, "sha256")? != checksum { + return Err(format!("Dependency checksum changed: {relative}")); + } + libraries.push(library); + } + Ok(Artifacts { + manifest, + jars, + libraries, + }) +} + +/// The client libraries, checked against the version JSON (tools/test_model_baking_parity.py's +/// `client_libraries`); the client-side exporters compile against them. +pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result, String> { + let mut libraries = Vec::new(); + for artifact in client_library_artifacts(manifest)? { + let (path, sha1) = artifact_fields(artifact)?; + let relative = safe_relative(path).ok_or("Unsafe client library path")?; + let library = lock.directory.join("libraries/client").join(&relative); + if !library.exists() || digest(&library, "sha1")? != sha1 { + return Err(format!("Client dependency checksum changed: {path}")); + } + libraries.push(library); + } + Ok(libraries) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn natives_follow_the_architecture() { + let names = ["a:b:1:natives-macos", "a:b:1:natives-macos-arm64"]; + let lib = |name: &str| pyjson::loads(&format!("{{\"name\":\"{name}\"}}")).unwrap(); + let arm = rule_architectures().contains(&"arm64"); + assert_eq!( + native_library_matches(&lib("a:b:1:natives-macos-arm64"), &names), + arm + ); + assert_eq!( + native_library_matches(&lib("x:y:1:linux-x86_64"), &names), + !arm + ); + assert_eq!( + native_library_matches(&lib("x:y:1:linux-aarch_64"), &names), + arm + ); + assert_eq!( + native_library_matches(&lib("a:b:1:natives-macos"), &names), + !arm + ); + assert!(native_library_matches(&lib("a:b:1"), &names)); + } + + #[test] + fn unsafe_paths_are_refused() { + assert!(safe_relative("a/../b").is_none()); + assert!(safe_relative("/a").is_none()); + assert!(safe_relative("a\\b").is_none()); + assert_eq!( + safe_relative("a/b.jar").unwrap(), + Path::new("a").join("b.jar") + ); + } +} diff --git a/crates/horizon-prepare/src/inventory.rs b/crates/horizon-prepare/src/inventory.rs new file mode 100644 index 000000000..fbf9097b7 --- /dev/null +++ b/crates/horizon-prepare/src/inventory.rs @@ -0,0 +1,177 @@ +//! Class inventories of the imported jars (tools/lab.py's `inventory` and `ClassReader`): each +//! class's SourceFile and method count, read from the bytecode; no Java text is published. + +use crate::pyjson::Value; +use std::path::Path; + +struct ClassReader<'a> { + data: &'a [u8], + offset: usize, +} + +impl ClassReader<'_> { + fn take(&mut self, count: usize) -> Result<&[u8], String> { + let value = self + .data + .get(self.offset..self.offset + count) + .ok_or("Truncated class file")?; + self.offset += count; + Ok(value) + } + + fn number(&mut self, count: usize) -> Result { + Ok(self + .take(count)? + .iter() + .fold(0usize, |n, b| (n << 8) | *b as usize)) + } + + fn attributes(&mut self) -> Result)>, String> { + let count = self.number(2)?; + let mut attributes = Vec::with_capacity(count); + for _ in 0..count { + let name = self.number(2)?; + let length = self.number(4)?; + attributes.push((name, self.take(length)?.to_vec())); + } + Ok(attributes) + } + + /// `(SourceFile, method count)`. + fn metadata(&mut self) -> Result<(Option, usize), String> { + if self.take(4)? != b"\xca\xfe\xba\xbe" { + return Err("Invalid class file magic".into()); + } + self.take(4)?; // Minor and major version. + let mut pool: Vec> = vec![None; self.number(2)?]; + let mut i = 1; + while i < pool.len() { + let tag = self.number(1)?; + if tag == 1 { + let length = self.number(2)?; + pool[i] = Some(String::from_utf8_lossy(self.take(length)?).into_owned()); + } else { + let size = match tag { + 3 | 4 | 9 | 10 | 11 | 12 | 17 | 18 => 4, + 5 | 6 => 8, + 7 | 8 | 16 | 19 | 20 => 2, + 15 => 3, + _ => return Err(format!("Unknown constant pool tag: {tag}")), + }; + self.take(size)?; + } + i += if tag == 5 || tag == 6 { 2 } else { 1 }; + } + self.take(6)?; // Access, this class, super class. + let interfaces = self.number(2)?; + self.take(interfaces * 2)?; + for _ in 0..self.number(2)? { + self.take(6)?; // Fields. + self.attributes()?; + } + let methods = self.number(2)?; + for _ in 0..methods { + self.take(6)?; + self.attributes()?; + } + let mut source = None; + for (name, data) in self.attributes()? { + if pool.get(name).and_then(Option::as_deref) == Some("SourceFile") { + let [high, low] = data[..] else { + return Err("Malformed SourceFile attribute".into()); + }; + let index = ((high as usize) << 8) | low as usize; + source = Some( + pool.get(index) + .cloned() + .flatten() + .ok_or("SourceFile points outside the constant pool")?, + ); + } + } + Ok((source, methods)) + } +} + +/// PurePosixPath(name).parent as text. +fn parent(name: &str) -> &str { + match name.trim_end_matches('/').rsplit_once('/') { + Some((parent, _)) if !parent.is_empty() => parent, + Some(_) => "/", + None => ".", + } +} + +pub fn inventory(jar: &Path) -> Result { + let mut archive = crate::open_zip(jar)?; + let mut classes = Vec::new(); + let mut packages: Vec<(String, usize)> = Vec::new(); + let mut sources = std::collections::BTreeSet::new(); + let mut method_count = 0; + for index in 0..archive.len() { + let mut item = archive.by_index(index).map_err(|e| e.to_string())?; + let name = item.name().to_string(); + if !name.ends_with(".class") { + continue; + } + let size = item.size(); + let mut data = Vec::with_capacity(size as usize); + std::io::Read::read_to_end(&mut item, &mut data).map_err(|e| e.to_string())?; + let (source, methods) = ClassReader { + data: &data, + offset: 0, + } + .metadata() + .map_err(|e| format!("{name}: {e}"))?; + let file = name.rsplit('/').next().unwrap(); + let source = source.filter(|s| !s.is_empty()).unwrap_or_else(|| { + let stem = file.split('$').next().unwrap(); + format!("{}.java", stem.strip_suffix(".class").unwrap_or(stem)) + }); + if source.contains('/') || source.contains('\\') || source == "." { + return Err(format!("Unsafe SourceFile attribute in {name}")); + } + let directory = parent(&name); + let source_path = if directory == "." { + source + } else { + format!("{directory}/{source}") + }; + match packages.iter_mut().find(|(p, _)| p == directory) { + Some(entry) => entry.1 += 1, + None => packages.push((directory.to_string(), 1)), + } + sources.insert(source_path.clone()); + method_count += methods; + classes.push(Value::Object(vec![ + ("class".into(), Value::Str(name)), + ("source".into(), Value::Str(source_path)), + ("bytecode_bytes".into(), Value::Int(size.to_string())), + ("methods".into(), Value::Int(methods.to_string())), + ])); + } + // Counter.most_common: by count, ties in first-seen order. + packages.sort_by_key(|(_, count)| std::cmp::Reverse(*count)); + Ok(Value::Object(vec![ + ( + "jar_sha256".into(), + Value::Str(crate::digest(jar, "sha256")?), + ), + ("class_count".into(), Value::Int(classes.len().to_string())), + ( + "expected_source_files".into(), + Value::Array(sources.into_iter().map(Value::Str).collect()), + ), + ("method_count".into(), Value::Int(method_count.to_string())), + ( + "packages".into(), + Value::Object( + packages + .into_iter() + .map(|(p, n)| (p, Value::Int(n.to_string()))) + .collect(), + ), + ), + ("classes".into(), Value::Array(classes)), + ])) +} diff --git a/crates/horizon-prepare/src/java.rs b/crates/horizon-prepare/src/java.rs new file mode 100644 index 000000000..860f4835a --- /dev/null +++ b/crates/horizon-prepare/src/java.rs @@ -0,0 +1,179 @@ +//! The JDK that compiles and runs the vanilla exporters. They call Mojang's own code, so they +//! stay Java; everything around them is here. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +pub struct Jdk { + pub javac: PathBuf, + pub java: PathBuf, +} + +const TIMEOUT: Duration = Duration::from_secs(3600); + +fn executable(dir: &Path, name: &str) -> PathBuf { + dir.join(if cfg!(windows) { + format!("{name}.exe") + } else { + name.to_string() + }) +} + +fn on_path(name: &str) -> Option { + std::env::split_paths(&std::env::var_os("PATH")?) + .map(|dir| executable(&dir, name)) + .find(|p| p.is_file()) +} + +/// The major version `javac -version` reports ("javac 25.0.1" โ†’ 25; "javac 1.8.0" โ†’ 8). +fn javac_major(javac: &Path) -> Result { + let output = Command::new(javac) + .arg("-version") + .stdin(Stdio::null()) + .output() + .map_err(|e| format!("{}: {e}", javac.display()))?; + let text = String::from_utf8_lossy(&output.stdout).into_owned() + + &String::from_utf8_lossy(&output.stderr); + let version = text + .split_whitespace() + .skip_while(|w| *w != "javac") + .nth(1) + .ok_or_else(|| { + format!( + "{} -version printed no version: {}", + javac.display(), + text.trim() + ) + })?; + let mut parts = version.split(['.', '-', '+', '_']); + let first: u32 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0); + Ok(if first == 1 { + parts.next().and_then(|p| p.parse().ok()).unwrap_or(0) + } else { + first + }) +} + +/// Finds a JDK with `javac` of at least `major`, the version research-lock.json pins: +/// `JAVA_HOME` when it holds one, else `javac` and `java` on the PATH (as the Python preparer +/// ran them), else, on macOS, the JDK `/usr/libexec/java_home -v ` reports. +pub fn find(major: i64) -> Result { + let need = format!( + "Java {major} is needed (a JDK with javac, e.g. Eclipse Temurin {major}). \ + Install it, or set JAVA_HOME to it, and try again." + ); + let mut candidates = Vec::new(); + if let Some(home) = std::env::var_os("JAVA_HOME").filter(|h| !h.is_empty()) { + let bin = Path::new(&home).join("bin"); + candidates.push(( + executable(&bin, "javac"), + executable(&bin, "java"), + "JAVA_HOME", + )); + } + if let (Some(javac), Some(java)) = (on_path("javac"), on_path("java")) { + candidates.push((javac, java, "PATH")); + } + if cfg!(target_os = "macos") { + if let Ok(out) = Command::new("/usr/libexec/java_home") + .args(["-v", &major.to_string()]) + .stderr(Stdio::null()) + .output() + { + let home = String::from_utf8_lossy(&out.stdout).trim().to_string(); + if out.status.success() && !home.is_empty() { + let bin = Path::new(&home).join("bin"); + candidates.push(( + executable(&bin, "javac"), + executable(&bin, "java"), + "/usr/libexec/java_home", + )); + } + } + } + let mut problems = Vec::new(); + for (javac, java, from) in candidates { + if !javac.is_file() || !java.is_file() { + problems.push(format!( + "{from} ({}) has no javac and java", + javac.parent().unwrap().display() + )); + continue; + } + match javac_major(&javac) { + Ok(found) if i64::from(found) >= major => return Ok(Jdk { javac, java }), + Ok(found) => problems.push(format!("{from} has Java {found} ({})", javac.display())), + Err(e) => problems.push(e), + } + } + if problems.is_empty() { + Err(format!("{need} No javac was found.")) + } else { + Err(format!("{need} Found: {}.", problems.join("; "))) + } +} + +/// A classpath with the platform's separator. +pub fn classpath<'a>(paths: impl IntoIterator) -> String { + let separator = if cfg!(windows) { ";" } else { ":" }; + paths + .into_iter() + .map(|p| p.to_string_lossy().into_owned()) + .collect::>() + .join(separator) +} + +impl Jdk { + /// `javac --release -proc:none` with Python's `subprocess.run(..., check=True, + /// stdout=log, stderr=STDOUT, timeout=3600)`. + pub fn javac(&self, major: i64, args: &[String], log: &fs::File) -> Result<(), String> { + let mut command = Command::new(&self.javac); + command + .args(["--release", &major.to_string(), "-proc:none"]) + .args(args); + run(command, log) + } + + pub fn java(&self, args: &[String], cwd: Option<&Path>, log: &fs::File) -> Result<(), String> { + let mut command = Command::new(&self.java); + command.args(args); + if let Some(dir) = cwd { + command.current_dir(dir); + } + run(command, log) + } +} + +fn run(mut command: Command, log: &fs::File) -> Result<(), String> { + let out = log.try_clone().map_err(|e| e.to_string())?; + let err = log.try_clone().map_err(|e| e.to_string())?; + let program = Path::new(command.get_program()) + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + let mut child = command + .stdin(Stdio::null()) + .stdout(out) + .stderr(err) + .spawn() + .map_err(|e| format!("Cannot start {program}: {e}"))?; + let start = Instant::now(); + loop { + if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { + return if status.success() { + Ok(()) + } else { + Err(format!("{program} failed ({status})")) + }; + } + if start.elapsed() > TIMEOUT { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("{program} took over an hour and was stopped")); + } + std::thread::sleep(Duration::from_millis(50)); + } +} diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs new file mode 100644 index 000000000..e09b529eb --- /dev/null +++ b/crates/horizon-prepare/src/lib.rs @@ -0,0 +1,1134 @@ +//! Prepares Horizon's resources from the player's own Minecraft Java Edition: imports the pinned +//! client jar, libraries and version JSON from their official launcher install and the server +//! jar they downloaded (each checked against research-lock.json), copies the game's assets and +//! data, and runs the vanilla exporters (mods/horizon/src/test/java/dev/horizonlab/parity), which +//! call Mojang's own code and so stay Java. The result, `.local/horizon-client/` with its +//! `horizon-resources.json` manifest, is what the game's `--resources` and the launcher read. +//! +//! This is the Rust port of the Python preparer (tools/prepare_native_client.py and the helpers +//! it imported); its files are byte for byte the ones the script wrote (tools/compare_prepare.py +//! checks it), so the manifest's `schema` is unchanged. Unchanged steps are skipped on the next +//! run, keyed by the sha256 of their inputs and outputs recorded in the manifest, as before. + +pub mod artifacts; +mod inventory; +pub mod java; +pub mod pyjson; +mod survival; + +use pyjson::Value; +use sha2::Digest; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +/// Where progress lines go: the terminal for the binary, the log pane for the launcher. +pub type Log<'a> = &'a dyn Fn(&str); + +/// The manifest's `schema`: the prepared files' layout, which the launcher compares. +pub const SCHEMA: i64 = 7; + +/// Digest of this crate's sources (build.rs): the launcher prepares a version in-process when +/// that version ships these same sources, and runs the version's own binary otherwise. +pub const SOURCES_SHA256: &str = env!("HORIZON_PREPARE_SOURCES_SHA256"); + +/// `SOURCES_SHA256` of the sources in `crate_dir` (a version folder's crates/horizon-prepare), +/// computed as build.rs computes it; None when the folder has none. +pub fn sources_sha256(crate_dir: &Path) -> Option { + let mut files = Vec::new(); + for name in ["Cargo.toml", "build.rs"] { + files.push((name.to_string(), fs::read(crate_dir.join(name)).ok()?)); + } + let mut sources: Vec = fs::read_dir(crate_dir.join("src")) + .ok()? + .filter_map(Result::ok) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.ends_with(".rs")) + .collect(); + sources.sort(); + for name in sources { + let data = fs::read(crate_dir.join("src").join(&name)).ok()?; + files.push((format!("src/{name}"), data)); + } + let mut hash = sha2::Sha256::new(); + for (name, data) in files { + // Line endings as checked out: a Windows checkout's CRLF is the same source. + let data: Vec = data.into_iter().filter(|b| *b != b'\r').collect(); + hash.update(format!("{name}\0{}\0", data.len())); + hash.update(&data); + } + Some(hex(&hash.finalize())) +} + +pub struct Options { + /// The version folder (a release folder, or a checkout): research-lock.json, the exporters' + /// Java sources, and `.local/` where everything is written. + pub root: PathBuf, + /// Import the pinned game files from the player's own copy first (`--prepare`). + pub import: bool, + /// The official launcher's game directory (`--minecraft-dir`, else HORIZON_MINECRAFT_DIR, + /// else the launcher's own). + pub minecraft_dir: Option, + /// The pinned server jar the player downloaded (`--server-jar`, else HORIZON_SERVER_JAR). + pub server_jar: Option, +} + +pub(crate) fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +pub(crate) fn sha256_hex(data: &[u8]) -> String { + hex(&sha2::Sha256::digest(data)) +} + +pub(crate) fn digest(path: &Path, algorithm: &str) -> Result { + fn stream(mut file: fs::File) -> std::io::Result { + let mut hash = D::new(); + let mut buffer = vec![0; 1 << 20]; + loop { + let n = file.read(&mut buffer)?; + if n == 0 { + return Ok(hex(&hash.finalize())); + } + hash.update(&buffer[..n]); + } + } + let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + match algorithm { + "sha1" => stream::(file), + _ => stream::(file), + } + .map_err(|e| format!("{}: {e}", path.display())) +} + +fn read(path: &Path) -> Result, String> { + fs::read(path).map_err(|e| format!("{}: {e}", path.display())) +} + +fn write(path: &Path, data: &[u8]) -> Result<(), String> { + fs::write(path, data).map_err(|e| format!("{}: {e}", path.display())) +} + +fn mkdir(path: &Path) -> Result<(), String> { + fs::create_dir_all(path).map_err(|e| format!("{}: {e}", path.display())) +} + +pub(crate) fn read_json(path: &Path) -> Result { + let text = String::from_utf8(read(path)?).map_err(|e| format!("{}: {e}", path.display()))?; + pyjson::loads(&text).map_err(|e| format!("{}: {e}", path.display())) +} + +/// Python's `Path.write_text`: text mode, so `\n` is the platform's line ending. +fn write_text(path: &Path, text: &str) -> Result<(), String> { + if cfg!(windows) { + write(path, text.replace('\n', "\r\n").as_bytes()) + } else { + write(path, text.as_bytes()) + } +} + +/// tools/lab.py's `write_json`: indented by two, with a final newline. +pub(crate) fn write_json(path: &Path, value: &Value) -> Result<(), String> { + mkdir(path.parent().unwrap())?; + write_text(path, &(pyjson::dumps(value, &pyjson::INDENT2) + "\n")) +} + +/// Writes `data` unless the file already holds it, so unchanged files keep their times. +fn write_if_changed(target: &Path, data: &[u8]) -> Result<(), String> { + if !(target.exists() && read(target)? == data) { + mkdir(target.parent().unwrap())?; + write(target, data)?; + } + Ok(()) +} + +fn copy(from: &Path, to: &Path) -> Result<(), String> { + write(to, &read(from)?) +} + +/// `path` relative to `root`, with the platform's separators, as Python's +/// `str(path.relative_to(ROOT))` prints it. +pub(crate) fn relative_display(path: &Path, root: &Path) -> Result { + let relative = path + .strip_prefix(root) + .map_err(|_| format!("{} is outside {}", path.display(), root.display()))?; + Ok(relative + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join(std::path::MAIN_SEPARATOR_STR)) +} + +/// Python's `str.splitlines`. +pub(crate) fn split_lines(text: &str) -> Vec<&str> { + let mut lines = Vec::new(); + let mut start = 0; + let mut chars = text.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if matches!( + c, + '\n' | '\r' + | '\u{b}' + | '\u{c}' + | '\u{1c}' + | '\u{1d}' + | '\u{1e}' + | '\u{85}' + | '\u{2028}' + | '\u{2029}' + ) { + lines.push(&text[start..i]); + let mut end = i + c.len_utf8(); + if c == '\r' && chars.peek().is_some_and(|(_, n)| *n == '\n') { + chars.next(); + end += 1; + } + start = end; + } + } + if start < text.len() { + lines.push(&text[start..]); + } + lines +} + +pub(crate) fn open_zip(path: &Path) -> Result, String> { + let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", path.display())) +} + +pub(crate) fn zip_bytes( + archive: &mut zip::ZipArchive, + name: &str, +) -> Result, String> { + let mut entry = archive.by_name(name).map_err(|e| format!("{name}: {e}"))?; + let mut data = Vec::with_capacity(entry.size() as usize); + entry + .read_to_end(&mut data) + .map_err(|e| format!("{name}: {e}"))?; + Ok(data) +} + +pub(crate) fn zip_text( + archive: &mut zip::ZipArchive, + name: &str, +) -> Result { + String::from_utf8(zip_bytes(archive, name)?).map_err(|e| format!("{name}: {e}")) +} + +/// The archive's member names in its own order (Python's `namelist`). +fn zip_names(archive: &zip::ZipArchive) -> Vec { + (0..archive.len()) + .filter_map(|i| archive.name_for_index(i).map(str::to_string)) + .collect() +} + +/// `{"minecraft:": text}` for every `.json`, sorted by member name +/// (the comprehension the Python preparer used for tags, worldgen and damage resources). +fn json_resources(archive: &mut zip::ZipArchive, prefix: &str) -> Result { + let mut names: Vec = zip_names(archive) + .into_iter() + .filter(|n| n.starts_with(prefix) && n.ends_with(".json")) + .collect(); + names.sort(); + let mut resources = Value::Object(Vec::new()); + for name in names { + let text = zip_text(archive, &name)?; + let key = format!("minecraft:{}", &name[prefix.len()..name.len() - 5]); + resources.insert(&key, Value::Str(text)); + } + Ok(resources) +} + +/// A relative member path with no `..` and not absolute (Python's `Path(name)` checks). +fn member_path(name: &str, what: &str) -> Result { + let path = Path::new(name); + if path.is_absolute() + || name.starts_with('/') + || path.components().any(|c| { + !matches!( + c, + std::path::Component::Normal(_) | std::path::Component::CurDir + ) + }) + { + return Err(what.to_string()); + } + Ok(path.to_path_buf()) +} + +/// `{relative path: sha256}` of exporter sources, in the order given +/// (tools/test_rust_parity.py's `source_hashes`). +fn source_hashes(root: &Path, sources: &[&Path]) -> Result { + let mut hashes = Value::Object(Vec::new()); + for source in sources { + hashes.insert( + &relative_display(source, root)?, + Value::Str(digest(source, "sha256")?), + ); + } + Ok(hashes) +} + +/// A classpath entry list with the platform's separator. +fn classpath_join(head: &Path, rest: &[PathBuf]) -> String { + java::classpath(std::iter::once(head).chain(rest.iter().map(PathBuf::as_path))) +} + +struct Run<'a> { + root: PathBuf, + local: PathBuf, + resources: PathBuf, + jdk: java::Jdk, + java_major: i64, + server: PathBuf, + client: PathBuf, + /// The server jar and its libraries: the classpath of the server-side exporters. + server_classpath: String, + /// The client jar and its libraries: the classpath of the client-side exporters. + client_classpath: String, + previous: Value, + origin: Value, + log: Log<'a>, +} + +const PARITY: &str = "mods/horizon/src/test/java/dev/horizonlab/parity"; + +impl Run<'_> { + fn oracle(&self, name: &str) -> PathBuf { + self.root.join(PARITY).join(name) + } + + fn previous(&self, key: &str) -> Option<&Value> { + self.previous.get(key) + } + + fn same(&self, key: &str) -> bool { + self.previous(key) == self.origin.get(key) + } + + fn file_hash(&self, name: &str) -> Result { + Ok(Value::Str(digest(&self.resources.join(name), "sha256")?)) + } + + /// Every file exists and has the hash the previous manifest recorded under `key`. + fn files_unchanged(&self, key: &str, names: &[&str]) -> Result { + for name in names { + if !self.resources.join(name).exists() + || self.previous(key).and_then(|h| h.get(name)) != Some(&self.file_hash(name)?) + { + return Ok(false); + } + } + Ok(true) + } + + fn log_file(&self, path: &Path) -> Result { + fs::File::create(path).map_err(|e| format!("{}: {e}", path.display())) + } + + /// `javac --release -proc:none -cp [extra] -d `. + fn compile( + &self, + classpath: &str, + extra: &[String], + classes: &Path, + sources: &[&Path], + log: &fs::File, + ) -> Result<(), String> { + let mut args = vec!["-cp".to_string(), classpath.to_string()]; + args.extend_from_slice(extra); + args.push("-d".into()); + args.push(classes.display().to_string()); + args.extend(sources.iter().map(|s| s.display().to_string())); + self.jdk.javac(self.java_major, &args, log) + } + + /// `java -Xmx -cp : dev.horizonlab.parity.
`. + fn run( + &self, + heap: &str, + classes: &Path, + classpath: &str, + main: &str, + args: &[String], + log: &fs::File, + ) -> Result<(), String> { + let separator = if cfg!(windows) { ";" } else { ":" }; + let mut all = vec![ + format!("-Xmx{heap}"), + "-cp".into(), + format!("{}{separator}{classpath}", classes.display()), + format!("dev.horizonlab.parity.{main}"), + ]; + all.extend_from_slice(args); + self.jdk.java(&all, None, log) + } + + /// Compiles `sources` into `classes` and runs each of `mains` with `args`, their output in + /// the log at `log`: the shape of every exporter step. + #[allow(clippy::too_many_arguments)] + fn export( + &self, + what: &str, + classpath: &str, + classes: &Path, + sources: &[&Path], + mains: &[&str], + heap: &str, + args: &[String], + log: &Path, + ) -> Result<(), String> { + (self.log)(&format!("Exporting {what} ({})", mains.join(", "))); + mkdir(classes)?; + let file = self.log_file(log)?; + let fail = |e: String| format!("{e} while exporting {what}; see {}", log.display()); + self.compile(classpath, &[], classes, sources, &file) + .map_err(fail)?; + for main in mains { + self.run(heap, classes, classpath, main, args, &file) + .map_err(fail)?; + } + Ok(()) + } +} + +/// Prepares the resources; returns their folder (`.local/horizon-client/`). +pub fn prepare(options: &Options, log: Log) -> Result { + let root = &options.root; + let lock = artifacts::Lock::read(root)?; + // Java first: nothing below can finish without it, and the player should hear it at once. + let jdk = java::find(lock.java_major)?; + if options.import { + artifacts::import( + root, + &lock, + options.minecraft_dir.as_deref(), + options.server_jar.as_deref(), + log, + )?; + } + let found = artifacts::verify(&lock)?; + let local = root.join(".local"); + let resources = local.join("horizon-client").join(&lock.version); + mkdir(&resources)?; + let manifest_path = resources.join("horizon-resources.json"); + let oracle = root.join(PARITY).join("VanillaHeightmapOracle.java"); + let origin = Value::Object(vec![ + ("minecraft".into(), Value::Str(lock.version.clone())), + ( + "client_sha256".into(), + Value::Str(digest(&found.jars["client"], "sha256")?), + ), + ( + "server_sha256".into(), + Value::Str(digest(&found.jars["server"], "sha256")?), + ), + ( + "exporter_sha256".into(), + Value::Str(digest(&oracle, "sha256")?), + ), + ]); + let previous = if manifest_path.exists() { + read_json(&manifest_path)? + } else { + Value::Object(Vec::new()) + }; + let client_libraries = artifacts::client_libraries(&lock, &found.manifest)?; + let run = Run { + root: root.clone(), + local, + resources: resources.clone(), + jdk, + java_major: lock.java_major, + server: found.jars["server"].clone(), + client: found.jars["client"].clone(), + server_classpath: classpath_join(&found.jars["server"], &found.libraries), + client_classpath: classpath_join(&found.jars["client"], &client_libraries), + previous, + origin, + log, + }; + steps(&run, &lock, &oracle)?; + log(&format!( + "Prepared Horizon native-client resources: {}", + resources.display() + )); + Ok(resources) +} + +fn arg(path: &Path) -> String { + path.display().to_string() +} + +fn steps(run: &Run, lock: &artifacts::Lock, oracle: &Path) -> Result<(), String> { + let root = &run.resources; + let repo = &run.root; + let server_cp = run.server_classpath.as_str(); + let client_cp = run.client_classpath.as_str(); + + // Every block state and its facts. + let facts = root.join("facts.json"); + let origin_same = run + .origin + .as_object() + .unwrap() + .iter() + .all(|(k, v)| run.previous(k) == Some(v)); + if !(origin_same + && facts.exists() + && run.previous("facts_sha256") == Some(&run.file_hash("facts.json")?)) + { + run.export( + "block states", + server_cp, + &root.join("classes"), + &[oracle], + &["VanillaHeightmapOracle"], + "512M", + &["export".into(), arg(&facts)], + &root.join("export.log"), + )?; + } + + // Block state to model bindings, from the client. + let binding = run.oracle("VanillaBlockStateBindingOracle.java"); + let helper = run.oracle("VanillaCuboidModelOracle.java"); + let binding_sources = source_hashes(repo, &[&binding, &helper])?; + let model_states = root.join("model-states.json"); + if !(run.previous("model_state_exporters_sha256") == Some(&binding_sources) + && run.same("client_sha256") + && model_states.exists() + && run.previous("model_states_sha256") == Some(&run.file_hash("model-states.json")?)) + { + run.export( + "model bindings", + client_cp, + &root.join("client-classes"), + &[&binding, &helper], + &["VanillaBlockStateBindingOracle"], + "512M", + &["export".into(), arg(&model_states)], + &root.join("model-state-export.log"), + )?; + } + + let block_tags = "data/minecraft/tags/block/"; + let tags = json_resources(&mut open_zip(&run.server)?, block_tags)?; + if tags != json_resources(&mut open_zip(&run.client)?, block_tags)? { + return Err("Reference block tags disagree".into()); + } + write_json(&root.join("block-tags.json"), &tags)?; + + let visibility = run.oracle("VanillaFaceVisibilityOracle.java"); + let collision = run.oracle("VanillaCollisionOracle.java"); + let collision_sources = source_hashes(repo, &[&collision])?; + let movement = run.oracle("VanillaMovementRegistryOracle.java"); + let attributes = run.oracle("VanillaEntityAttributeOracle.java"); + let landing = run.oracle("VanillaBlockLandingOracle.java"); + let motion_sources = source_hashes( + repo, + &[&movement, &attributes, oracle, &landing, &collision], + )?; + let motion_files = [ + "movement-properties.nbt", + "attributes.json", + "landing-definitions.json", + ]; + if !(run.previous("motion_exporters_sha256") == Some(&motion_sources) + && run.same("server_sha256") + && run.previous("block_tags_sha256") == Some(&run.file_hash("block-tags.json")?) + && run.files_unchanged("motion_files_sha256", &motion_files)?) + { + let export = run.local.join("horizon-client-motion"); + mkdir(&export)?; + write_json(&export.join("tags.json"), &tags)?; + run.export( + "movement and attributes", + server_cp, + &export.join("classes"), + &[&movement, &attributes, oracle, &landing, &collision], + &["VanillaBlockLandingOracle", "VanillaEntityAttributeOracle"], + "768M", + &["export".into(), arg(&export)], + &export.join("export.log"), + )?; + copy( + &export.join("movement-properties.nbt"), + &root.join("movement-properties.nbt"), + )?; + copy(&export.join("catalog.json"), &root.join("attributes.json"))?; + copy( + &export.join("landing-definitions.json"), + &root.join("landing-definitions.json"), + )?; + } + + let damage = run.oracle("VanillaDamageSourceOracle.java"); + let health = run.oracle("VanillaPlayerHealthOracle.java"); + let health_sources = source_hashes(repo, &[&damage, &health, &attributes])?; + let health_files = [ + "damage-types.json", + "damage-tags.json", + "damage-catalog.json", + "player-float-ids.json", + ]; + if !(run.previous("health_exporters_sha256") == Some(&health_sources) + && run.same("server_sha256") + && run.files_unchanged("health_files_sha256", &health_files)?) + { + let export = run.local.join("horizon-client-health"); + mkdir(&export)?; + let mut server = open_zip(&run.server)?; + let mut client = open_zip(&run.client)?; + for (file, prefix) in [ + ("types.json", "data/minecraft/damage_type/"), + ("tags.json", "data/minecraft/tags/damage_type/"), + ] { + let resources = json_resources(&mut server, prefix)?; + if resources != json_resources(&mut client, prefix)? { + return Err("Reference damage resources disagree".into()); + } + write_json(&export.join(file), &resources)?; + } + run.export( + "damage and health", + server_cp, + &export.join("classes"), + &[&damage, &health, &attributes], + &["VanillaPlayerHealthOracle", "VanillaDamageSourceOracle"], + "768M", + &["export".into(), arg(&export)], + &export.join("export.log"), + )?; + for (source, target) in [ + ("types.json", "damage-types.json"), + ("tags.json", "damage-tags.json"), + ("catalog.json", "damage-catalog.json"), + ("ids.json", "player-float-ids.json"), + ] { + copy(&export.join(source), &root.join(target))?; + } + } + + let collision_file = root.join("cached-collision.nbt"); + if !(run.previous("collision_exporters_sha256") == Some(&collision_sources) + && run.same("server_sha256") + && collision_file.exists() + && run.previous("collision_sha256") == Some(&run.file_hash("cached-collision.nbt")?)) + { + let export = run.local.join("horizon-client-collision"); + mkdir(&export)?; + run.export( + "collision shapes", + server_cp, + &export.join("classes"), + &[&collision], + &["VanillaCollisionOracle"], + "768M", + &["generate".into(), arg(&export)], + &export.join("export.log"), + )?; + copy(&export.join("cached-collision.nbt"), &collision_file)?; + } + + let render_sources = source_hashes(repo, &[&visibility, &collision, oracle])?; + let render_files = ["render-definitions.json", "occlusion.nbt"]; + if !(run.previous("render_exporters_sha256") == Some(&render_sources) + && run.same("server_sha256") + && run.previous("block_tags_sha256") == Some(&run.file_hash("block-tags.json")?) + && run.files_unchanged("render_files_sha256", &render_files)?) + { + let export = run.local.join("horizon-client-render"); + mkdir(&export)?; + write_json(&export.join("tags.json"), &tags)?; + run.export( + "face visibility", + server_cp, + &export.join("classes"), + &[&visibility, &collision, oracle], + &["VanillaFaceVisibilityOracle"], + "768M", + &["export".into(), arg(&export)], + &export.join("export.log"), + )?; + copy( + &export.join("definitions.json"), + &root.join("render-definitions.json"), + )?; + copy(&export.join("occlusion.nbt"), &root.join("occlusion.nbt"))?; + } + + // The playable client needs every client asset (textures, models, fonts, GUI) + // and every data-pack resource (worldgen, recipes, loot tables, tags). + (run.log)("Copying the client's assets and data"); + let mut count = 0usize; + let mut client = open_zip(&run.client)?; + let version = pyjson::loads(&zip_text(&mut client, "version.json")?)?; + for name in zip_names(&client) { + if !(name.starts_with("assets/") || name.starts_with("data/")) || name.ends_with('/') { + continue; + } + let relative = member_path(&name, "Invalid resource path")?; + let data = zip_bytes(&mut client, &name)?; + write_if_changed(&root.join(relative), &data)?; + count += 1; + } + + // One file each, exported again when the exporter or the jar it reads changed. + let single = |what: &str, + file: &str, + oracles: &[&str], + key: &str, + jar: &str, + classes: &str, + heap: &str, + extra: &[String], + log: &str| + -> Result { + let target = root.join(file); + let sources: Vec = oracles.iter().map(|o| run.oracle(o)).collect(); + let sources: Vec<&Path> = sources.iter().map(PathBuf::as_path).collect(); + let hashes = source_hashes(repo, &sources)?; + if !(run.previous(key) == Some(&hashes) && target.exists() && run.same(jar)) { + let main = oracles[0].strip_suffix(".java").unwrap(); + let mut args = vec![arg(&target)]; + args.extend_from_slice(extra); + run.export( + what, + if jar == "client_sha256" { + client_cp + } else { + server_cp + }, + &run.local.join(classes), + &sources, + &[main], + heap, + &args, + &root.join(log), + )?; + } + Ok(hashes) + }; + let gameplay_sources = single( + "gameplay facts", + "gameplay-facts.json", + &["VanillaGameplayFactsExporter.java"], + "gameplay_exporters_sha256", + "server_sha256", + "gameplay-facts/classes", + "1G", + &[], + "gameplay-export.log", + )?; + // Entity dimensions, categories and default attributes for the client's mobs. + let entity_types_sources = single( + "entity types", + "entity-types.json", + &["VanillaEntityTypesExporter.java"], + "entity_types_exporters_sha256", + "server_sha256", + "entity-types/classes", + "1G", + &[], + "entity-types-export.log", + )?; + // Block classes, instance configuration and per-state support/signal/fluid + // facts for horizon-world's level behaviour (level::Behaviours::load). + let behaviour_sources = single( + "block behaviours", + "block-behaviours.json", + &["VanillaBlockBehaviourExporter.java"], + "behaviour_exporters_sha256", + "server_sha256", + "block-behaviours/classes", + "1G", + &[], + "behaviour-export.log", + )?; + + let items = root.join("items.json"); + if !items.exists() || !run.same("server_sha256") { + // Vanilla's own data generator reports every item's default components. + (run.log)("Running vanilla's data generator reports"); + let datagen = run.local.join("datagen"); + mkdir(&datagen)?; + let log_path = datagen.join("datagen.log"); + let log = run.log_file(&log_path)?; + run.jdk + .java( + &[ + "-DbundlerMainClass=net.minecraft.data.Main".into(), + "-jar".into(), + arg(&lock.directory.join("jars").join("server.jar")), + "--reports".into(), + "--output".into(), + "out".into(), + ], + Some(&datagen), + &log, + ) + .map_err(|e| format!("{e} in the data generator; see {}", log_path.display()))?; + let reports = datagen.join("out").join("reports"); + let mut components = Value::Object(Vec::new()); + for file in json_files(&reports.join("minecraft/components/item"))? { + let stem = file.file_stem().unwrap().to_string_lossy().into_owned(); + let report = read_json(&file)?; + let component = report + .get("components") + .ok_or_else(|| format!("{} has no components", file.display()))?; + components.insert(&format!("minecraft:{stem}"), component.clone()); + } + write_text(&items, &pyjson::dumps(&components, &pyjson::DEFAULT))?; + let biome_parameters = root.join("biome-parameters"); + mkdir(&biome_parameters)?; + for file in json_files(&reports.join("biome_parameters/minecraft"))? { + copy(&file, &biome_parameters.join(file.file_name().unwrap()))?; + } + } + + // Biome parameter tables come from the data generator reports above. + prepare_worldgen(run)?; + + let entity_sources = single( + "entity models", + "entity-models.json", + &["VanillaEntityModelExporter.java"], + "entity_model_exporters_sha256", + "client_sha256", + "entity-models/classes", + "1G", + &[], + "entity-model-export.log", + )?; + // Mob AI and animation facts: per-state path types, spawn placements and the + // client's keyframe animation definitions (needs the client jar). + let mob_sources = single( + "mob data", + "mob-data.json", + &["VanillaMobDataExporter.java"], + "mob_data_exporters_sha256", + "client_sha256", + "mob-data/classes", + "1G", + &[arg(&run.client)], + "mob-data-export.log", + )?; + + // Vanilla's built-in registries for in-game command parsing (mob effects, + // data component types, dialogs, block entity and tag members). + let command_registries = root.join("command-registries.json"); + let command_oracle = run.oracle("VanillaCommandParseOracle.java"); + let command_sources = source_hashes(repo, &[&command_oracle])?; + if !(run.previous("command_registries_exporters_sha256") == Some(&command_sources) + && command_registries.exists() + && run.same("server_sha256")) + { + let export = run.local.join("command-registries"); + run.export( + "command registries", + server_cp, + &export.join("classes"), + &[&command_oracle], + &["VanillaCommandParseOracle"], + "1G", + &["registries".into(), arg(&export)], + &root.join("command-registries-export.log"), + )?; + copy(&export.join("registries.json"), &command_registries)?; + } + + // The creative inventory (creative-inventory.json): every tab built by vanilla's + // CreativeModeTabs over the vanilla data pack's registries, with the search + // tab's tooltip lines and tags. + let creative_sources = single( + "the creative inventory", + "creative-inventory.json", + &["VanillaCreativeTabsExporter.java", "ParityData.java"], + "creative_exporters_sha256", + "server_sha256", + "creative-inventory/classes", + "2G", + &[], + "creative-export.log", + )?; + + let file_hashes = |names: &[&str]| -> Result { + Ok(Value::Object( + names + .iter() + .map(|n| Ok((n.to_string(), run.file_hash(n)?))) + .collect::>()?, + )) + }; + let mut manifest = vec![("schema".to_string(), Value::Int(SCHEMA.to_string()))]; + manifest.extend(run.origin.as_object().unwrap().iter().cloned()); + manifest.extend([ + ("health_exporters_sha256".into(), health_sources), + ("health_files_sha256".into(), file_hashes(&health_files)?), + ("motion_exporters_sha256".into(), motion_sources), + ("motion_files_sha256".into(), file_hashes(&motion_files)?), + ("collision_exporters_sha256".into(), collision_sources), + ( + "collision_sha256".into(), + run.file_hash("cached-collision.nbt")?, + ), + ("render_exporters_sha256".into(), render_sources), + ("render_files_sha256".into(), file_hashes(&render_files)?), + ("model_state_exporters_sha256".into(), binding_sources), + ("gameplay_exporters_sha256".into(), gameplay_sources), + ("entity_model_exporters_sha256".into(), entity_sources), + ("creative_exporters_sha256".into(), creative_sources), + ("mob_data_exporters_sha256".into(), mob_sources), + ("entity_types_exporters_sha256".into(), entity_types_sources), + ("behaviour_exporters_sha256".into(), behaviour_sources), + ( + "command_registries_exporters_sha256".into(), + command_sources, + ), + ( + "model_states_sha256".into(), + run.file_hash("model-states.json")?, + ), + ( + "data_version".into(), + version + .get("world_version") + .cloned() + .ok_or("version.json has no world_version")?, + ), + ("facts_sha256".into(), run.file_hash("facts.json")?), + ( + "block_tags_sha256".into(), + run.file_hash("block-tags.json")?, + ), + ("resource_files".into(), Value::Int(count.to_string())), + ]); + write_json( + &root.join("horizon-resources.json"), + &Value::Object(manifest), + ) +} + +/// `sorted(directory.glob('*.json'))`: glob skips names starting with a dot. +fn json_files(directory: &Path) -> Result, String> { + let mut files: Vec = fs::read_dir(directory) + .map_err(|e| format!("{}: {e}", directory.display()))? + .filter_map(Result::ok) + .filter(|e| { + let name = e.file_name().to_string_lossy().into_owned(); + name.ends_with(".json") && !name.starts_with('.') + }) + .map(|e| e.path()) + .collect(); + files.sort(); + Ok(files) +} + +const WORLDGEN_BUNDLES: [(&str, &str); 19] = [ + ("noises", "worldgen/noise"), + ("densities", "worldgen/density_function"), + ("rules", "worldgen/material_rule"), + ("conditions", "worldgen/material_condition"), + ("settings", "worldgen/noise_settings"), + ("carvers", "worldgen/carver"), + ("biomes", "worldgen/biome"), + ("world_presets", "worldgen/world_preset"), + ("features", "worldgen/feature"), + ("placed_features", "worldgen/placed_feature"), + ("state_providers", "worldgen/block_state_provider"), + ("biome_tags", "tags/worldgen/biome"), + ("feature_tags", "tags/worldgen/feature"), + ("block_tags", "tags/block"), + ("fluid_tags", "tags/fluid"), + ("processor_lists", "worldgen/processor_list"), + ("template_pools", "worldgen/template_pool"), + ("structures", "worldgen/structure"), + ("structure_sets", "worldgen/structure_set"), +]; + +const BLOCK_BEHAVIOR_FILES: [&str; 6] = [ + "block-properties.nbt", + "cached-collision.nbt", + "cached-support.nbt", + "survival-rules.json", + "survival-extra-definitions.json", + "placement-definitions.json", +]; + +/// The chunk generator's resource bundle in `/worldgen` (see GeneratorData::load). +fn prepare_worldgen(run: &Run) -> Result<(), String> { + (run.log)("Writing the world generator's bundle"); + let root = &run.resources; + let local = &run.local; + let out = root.join("worldgen"); + mkdir(&out)?; + // Structure templates: gzip NBT files under structure//.nbt. + let mut server = open_zip(&run.server)?; + let prefix = "data/minecraft/structure/"; + for name in zip_names(&server) { + if name.starts_with(prefix) && name.ends_with(".nbt") { + let relative = member_path(&name[prefix.len()..], "Invalid structure path")?; + let data = zip_bytes(&mut server, &name)?; + write_if_changed(&out.join("structure/minecraft").join(relative), &data)?; + } + } + let mut client = open_zip(&run.client)?; + for (name, path) in WORLDGEN_BUNDLES { + let prefix = format!("data/minecraft/{path}/"); + let resources = json_resources(&mut server, &prefix)?; + if resources.as_object().is_none_or(<[_]>::is_empty) + || resources != json_resources(&mut client, &prefix)? + { + return Err(format!("Reference worldgen resources disagree: {path}")); + } + write_text( + &out.join(format!("{name}.json")), + &pyjson::dumps(&resources, &pyjson::COMPACT), + )?; + } + let facts = read_json(&root.join("facts.json"))?; + let short = || "A block state in facts.json is short".to_string(); + let flags = facts + .get("states") + .and_then(Value::as_array) + .ok_or("facts.json has no states")? + .iter() + .map(|s| { + Ok(Value::Array(vec![ + s.index(1).cloned().ok_or_else(short)?, + s.index(2).cloned().ok_or_else(short)?, + ])) + }) + .collect::, String>>()?; + write_text( + &out.join("block_flags.json"), + &pyjson::dumps(&Value::Array(flags), &pyjson::COMPACT), + )?; + let reports = out.join("biome_parameters"); + mkdir(&reports)?; + let mut presets = false; + for source in [ + root.join("biome-parameters"), + local.join("datagen/out/reports/biome_parameters/minecraft"), + ] { + if source.join("overworld.json").exists() { + for report in json_files(&source)? { + copy(&report, &reports.join(report.file_name().unwrap()))?; + } + presets = true; + break; + } + } + // Block behavior used by feature placement checks (survival, support, collision). + // These come from the Java exporters of the simple-block parity run, or a direct export. + let all_present = |dir: &Path| BLOCK_BEHAVIOR_FILES.iter().all(|n| dir.join(n).exists()); + let mut behavior = local.join("rust-simple-block-parity"); + if !all_present(&behavior) { + behavior = local.join("horizon-client-block-behavior"); + export_block_behavior(run, &behavior)?; + } + let blocks = out.join("blocks"); + if all_present(&behavior) { + mkdir(&blocks)?; + for name in BLOCK_BEHAVIOR_FILES { + copy(&behavior.join(name), &blocks.join(name))?; + } + } + mkdir(&blocks)?; + let structures = local.join("horizon-client-structures"); + run.export( + "structure blocks", + &run.server_classpath, + &structures.join("classes"), + &[&run.oracle("VanillaStructureBlockExporter.java")], + &["VanillaStructureBlockExporter"], + "1G", + &[arg(&blocks.join("structure-blocks.json"))], + &structures.join("export.log"), + )?; + if !presets { + // Fall back to the Java-exported quantized tables from the material-stage parity run. + let tables = local.join("rust-material-stage-parity/presets.json"); + if !tables.exists() { + return Err( + "No multi-noise biome parameter tables; run the data generator reports".into(), + ); + } + copy(&tables, &out.join("presets.json"))?; + } + Ok(()) +} + +/// The vanilla exporters of block properties, support, collision and survival definitions. +/// Feature placement needs them: without these files the generator skips every placed feature +/// whose blocks are checked for survival or support (trees, flowers, grass, kelp, ...). +fn export_block_behavior(run: &Run, export: &Path) -> Result<(), String> { + (run.log)("Exporting block behavior (VanillaSimpleBlockOracle)"); + let tests = run.root.join("mods/horizon/src/test/java"); + let classes = export.join("classes"); + mkdir(&classes)?; + let log_path = export.join("export.log"); + let log = run.log_file(&log_path)?; + let fail = |e: String| { + format!( + "{e} while exporting block behavior; see {}", + log_path.display() + ) + }; + // The oracle's helper classes are compiled on demand from the source path. + run.compile( + &run.server_classpath, + &["-sourcepath".into(), arg(&tests)], + &classes, + &[&tests.join("dev/horizonlab/parity/VanillaSimpleBlockOracle.java")], + &log, + ) + .map_err(fail)?; + run.run( + "1G", + &classes, + &run.server_classpath, + "VanillaSimpleBlockOracle", + &["export".into(), arg(export)], + &log, + ) + .map_err(fail)?; + let rules = survival::bind_definitions( + &read_json(&export.join("survival-classes.json"))?, + &read_json(&export.join("survival-placement-classes.json"))?, + &read_json(&export.join("survival-support-tags.json"))?, + )?; + write_text( + &export.join("survival-rules.json"), + &pyjson::dumps(&rules, &pyjson::COMPACT), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_source_digest_is_the_one_build_rs_computed() { + assert_eq!( + sources_sha256(Path::new(env!("CARGO_MANIFEST_DIR"))).as_deref(), + Some(SOURCES_SHA256) + ); + assert_eq!(sources_sha256(Path::new("/nonexistent")), None); + } + + #[test] + fn lines_split_as_python_splits_them() { + assert_eq!(split_lines("a\r\nb\rc\n\nd"), ["a", "b", "c", "", "d"]); + assert_eq!(split_lines("a\n"), ["a"]); + } + + #[test] + fn member_paths_stay_inside() { + assert!(member_path("assets/a.png", "bad").is_ok()); + assert!(member_path("../a", "bad").is_err()); + assert!(member_path("/a", "bad").is_err()); + } +} diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs new file mode 100644 index 000000000..d56ee8175 --- /dev/null +++ b/crates/horizon-prepare/src/main.rs @@ -0,0 +1,109 @@ +//! `horizon-prepare`: prepares Horizon's resources from your own Minecraft Java Edition. +//! Its flags are the ones tools/prepare_native_client.py took. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +const HELP: &str = "\ +horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition + +Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [--root PATH] + + --prepare Import the pinned game files from your own copy first + --server-jar PATH The pinned server jar you downloaded yourself + (default: HORIZON_SERVER_JAR, or the copy imported before) + --minecraft-dir PATH The official launcher's game directory with your installed copy + (default: HORIZON_MINECRAFT_DIR, or the launcher's own) + --root PATH The Horizon folder to prepare (default: the folder this program is + in, else the nearest folder above the current one with research-lock.json) + +Needs Minecraft played once from the official launcher, and Java (a JDK) of the version +research-lock.json pins: JAVA_HOME, else javac and java on the PATH. +The resources go to /.local/horizon-client/; pass that to horizon-client --resources. +"; + +/// The folder with research-lock.json: beside the executable in a release folder, else the +/// current folder or one above it (a checkout, with the binary in target/). +fn default_root() -> Option { + let beside = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(Path::to_path_buf)); + if let Some(dir) = beside.filter(|d| d.join("research-lock.json").is_file()) { + return Some(dir); + } + let cwd = std::env::current_dir().ok()?; + cwd.ancestors() + .find(|d| d.join("research-lock.json").is_file()) + .map(Path::to_path_buf) +} + +fn main() -> ExitCode { + let mut options = horizon_prepare::Options { + root: PathBuf::new(), + import: false, + minecraft_dir: None, + server_jar: None, + }; + let mut root = None; + let mut args = std::env::args_os().skip(1); + while let Some(arg) = args.next() { + let text = arg.to_string_lossy().into_owned(); + let (flag, inline) = match text.split_once('=') { + Some((flag, value)) if flag.starts_with("--") => { + (flag.to_string(), Some(value.to_string())) + } + _ => (text.clone(), None), + }; + let mut value = |name: &str| -> Result { + match &inline { + Some(v) => Ok(PathBuf::from(v)), + None => args + .next() + .map(PathBuf::from) + .ok_or_else(|| format!("{name} needs a path")), + } + }; + let parsed = match flag.as_str() { + "--prepare" if inline.is_none() => { + options.import = true; + Ok(()) + } + "--server-jar" => value("--server-jar").map(|v| options.server_jar = Some(v)), + "--minecraft-dir" => value("--minecraft-dir").map(|v| options.minecraft_dir = Some(v)), + "--root" => value("--root").map(|v| root = Some(v)), + "-h" | "--help" => { + print!("{HELP}"); + return ExitCode::SUCCESS; + } + "-V" | "--version" => { + println!("horizon-prepare {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + _ => Err(format!("unrecognized argument: {text}")), + }; + if let Err(e) = parsed { + eprintln!("horizon-prepare: error: {e}\n\n{HELP}"); + return ExitCode::from(2); + } + } + let Some(root) = root.or_else(default_root) else { + eprintln!( + "horizon-prepare: error: no research-lock.json beside this program or above the current folder; pass --root" + ); + return ExitCode::from(2); + }; + options.root = root; + let log = |line: &str| { + let mut out = std::io::stdout().lock(); + let _ = writeln!(out, "{line}"); + let _ = out.flush(); + }; + match horizon_prepare::prepare(&options, &log) { + Ok(_) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} diff --git a/crates/horizon-prepare/src/pyjson.rs b/crates/horizon-prepare/src/pyjson.rs new file mode 100644 index 000000000..f8e98787c --- /dev/null +++ b/crates/horizon-prepare/src/pyjson.rs @@ -0,0 +1,541 @@ +//! JSON read and written exactly as Python's `json` module does, so the files this crate writes +//! are byte for byte the ones `tools/prepare_native_client.py` wrote: objects keep their key +//! order (a repeated key keeps its first place and its last value), integers keep every digit, +//! floats print as Python's `repr`, and strings are escaped as `ensure_ascii=True` escapes them. + +use std::fmt::Write; + +#[derive(Clone, Debug)] +pub enum Value { + Null, + Bool(bool), + /// A JSON integer, kept as its decimal digits (Python's integers have no size limit). + Int(String), + Float(f64), + Str(String), + Array(Vec), + Object(Vec<(String, Value)>), +} + +impl Value { + pub fn str(s: impl Into) -> Value { + Value::Str(s.into()) + } + + pub fn get(&self, key: &str) -> Option<&Value> { + match self { + Value::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + pub fn index(&self, i: usize) -> Option<&Value> { + match self { + Value::Array(items) => items.get(i), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Value::Str(s) => Some(s), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&[Value]> { + match self { + Value::Array(items) => Some(items), + _ => None, + } + } + + pub fn as_object(&self) -> Option<&[(String, Value)]> { + match self { + Value::Object(fields) => Some(fields), + _ => None, + } + } + + pub fn as_i64(&self) -> Option { + match self { + Value::Int(digits) => digits.parse().ok(), + _ => None, + } + } + + /// `dict[key] = value`: a new key goes last, an existing one keeps its place. + pub fn insert(&mut self, key: &str, value: Value) { + if let Value::Object(fields) = self { + match fields.iter_mut().find(|(k, _)| k == key) { + Some(field) => field.1 = value, + None => fields.push((key.to_string(), value)), + } + } + } +} + +/// Python's `==`: objects compare without regard to key order, and 1 == 1.0. +impl PartialEq for Value { + fn eq(&self, other: &Value) -> bool { + match (self, other) { + (Value::Null, Value::Null) => true, + (Value::Bool(a), Value::Bool(b)) => a == b, + (Value::Int(a), Value::Int(b)) => a == b, + (Value::Float(a), Value::Float(b)) => a == b, + (Value::Int(a), Value::Float(b)) | (Value::Float(b), Value::Int(a)) => { + a.parse::().is_ok_and(|a| a == *b && b.fract() == 0.0) + } + (Value::Str(a), Value::Str(b)) => a == b, + (Value::Array(a), Value::Array(b)) => a == b, + (Value::Object(a), Value::Object(b)) => { + a.len() == b.len() && a.iter().all(|(k, v)| other.get(k) == Some(v)) + } + _ => false, + } + } +} + +pub fn loads(text: &str) -> Result { + let mut parser = Parser { + text: text.as_bytes(), + at: 0, + }; + parser.space(); + let value = parser.value()?; + parser.space(); + if parser.at != parser.text.len() { + return Err(parser.error("Extra data")); + } + Ok(value) +} + +struct Parser<'a> { + text: &'a [u8], + at: usize, +} + +impl Parser<'_> { + fn error(&self, what: &str) -> String { + format!("{what} at byte {}", self.at) + } + + fn space(&mut self) { + while matches!(self.text.get(self.at), Some(b' ' | b'\t' | b'\n' | b'\r')) { + self.at += 1; + } + } + + fn literal(&mut self, word: &str) -> bool { + if self.text[self.at..].starts_with(word.as_bytes()) { + self.at += word.len(); + true + } else { + false + } + } + + fn value(&mut self) -> Result { + match self.text.get(self.at) { + Some(b'{') => { + self.at += 1; + let mut object = Value::Object(Vec::new()); + self.space(); + if self.text.get(self.at) == Some(&b'}') { + self.at += 1; + return Ok(object); + } + loop { + self.space(); + if self.text.get(self.at) != Some(&b'"') { + return Err(self.error("Expecting property name enclosed in double quotes")); + } + let key = self.string()?; + self.space(); + if self.text.get(self.at) != Some(&b':') { + return Err(self.error("Expecting ':' delimiter")); + } + self.at += 1; + self.space(); + let value = self.value()?; + object.insert(&key, value); + self.space(); + match self.text.get(self.at) { + Some(b',') => self.at += 1, + Some(b'}') => { + self.at += 1; + return Ok(object); + } + _ => return Err(self.error("Expecting ',' delimiter")), + } + } + } + Some(b'[') => { + self.at += 1; + let mut items = Vec::new(); + self.space(); + if self.text.get(self.at) == Some(&b']') { + self.at += 1; + return Ok(Value::Array(items)); + } + loop { + self.space(); + items.push(self.value()?); + self.space(); + match self.text.get(self.at) { + Some(b',') => self.at += 1, + Some(b']') => { + self.at += 1; + return Ok(Value::Array(items)); + } + _ => return Err(self.error("Expecting ',' delimiter")), + } + } + } + Some(b'"') => Ok(Value::Str(self.string()?)), + Some(b'n') if self.literal("null") => Ok(Value::Null), + Some(b't') if self.literal("true") => Ok(Value::Bool(true)), + Some(b'f') if self.literal("false") => Ok(Value::Bool(false)), + Some(b'N') if self.literal("NaN") => Ok(Value::Float(f64::NAN)), + Some(b'I') if self.literal("Infinity") => Ok(Value::Float(f64::INFINITY)), + Some(b'-') if self.literal("-Infinity") => Ok(Value::Float(f64::NEG_INFINITY)), + Some(b'-' | b'0'..=b'9') => self.number(), + _ => Err(self.error("Expecting value")), + } + } + + /// Python's NUMBER_RE: `(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?`. + fn number(&mut self) -> Result { + let start = self.at; + let digits = |p: &mut Self| { + let from = p.at; + while p.text.get(p.at).is_some_and(u8::is_ascii_digit) { + p.at += 1; + } + p.at - from + }; + if self.text.get(self.at) == Some(&b'-') { + self.at += 1; + } + if self.text.get(self.at) == Some(&b'0') { + self.at += 1; + } else if digits(self) == 0 { + self.at = start; + return Err(self.error("Expecting value")); + } + let integer_end = self.at; + let mut float = false; + if self.text.get(self.at) == Some(&b'.') { + let dot = self.at; + self.at += 1; + if digits(self) == 0 { + self.at = dot; + } else { + float = true; + } + } + if matches!(self.text.get(self.at), Some(b'e' | b'E')) { + let mark = self.at; + self.at += 1; + if matches!(self.text.get(self.at), Some(b'-' | b'+')) { + self.at += 1; + } + if digits(self) == 0 { + self.at = mark; + } else { + float = true; + } + } + let text = std::str::from_utf8(&self.text[start..self.at]).unwrap(); + if float { + text.parse::() + .map(Value::Float) + .map_err(|e| e.to_string()) + } else { + debug_assert_eq!(self.at, integer_end); + Ok(Value::Int(if text == "-0" { + "0".into() + } else { + text.into() + })) + } + } + + fn hex4(&mut self) -> Result { + let digits = self + .text + .get(self.at..self.at + 4) + .and_then(|d| std::str::from_utf8(d).ok()) + .filter(|d| d.bytes().all(|b| b.is_ascii_hexdigit())) + .ok_or_else(|| self.error("Invalid \\uXXXX escape"))?; + self.at += 4; + Ok(u32::from_str_radix(digits, 16).unwrap()) + } + + fn string(&mut self) -> Result { + self.at += 1; + let mut out = String::new(); + loop { + let run = self.at; + while self + .text + .get(self.at) + .is_some_and(|&b| b != b'"' && b != b'\\' && b >= 0x20) + { + self.at += 1; + } + out.push_str(std::str::from_utf8(&self.text[run..self.at]).map_err(|e| e.to_string())?); + match self.text.get(self.at) { + Some(b'"') => { + self.at += 1; + return Ok(out); + } + Some(b'\\') => { + self.at += 1; + let escape = *self + .text + .get(self.at) + .ok_or_else(|| self.error("Unterminated string"))?; + self.at += 1; + match escape { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\u{8}'), + b'f' => out.push('\u{c}'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + let mut code = self.hex4()?; + if (0xd800..0xdc00).contains(&code) + && self.text[self.at..].starts_with(b"\\u") + { + let back = self.at; + self.at += 2; + let low = self.hex4()?; + if (0xdc00..0xe000).contains(&low) { + code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00); + } else { + self.at = back; + } + } + out.push(char::from_u32(code).ok_or_else(|| { + self.error( + "Lone surrogate (Python keeps it; Horizon's files have none)", + ) + })?); + } + _ => return Err(self.error("Invalid \\escape")), + } + } + _ => return Err(self.error("Unterminated string or control character")), + } + } + } +} + +/// `json.dumps(value, indent=indent, separators=(item, key))` with `ensure_ascii=True`. +/// Python's defaults are `(", ", ": ")` without an indent and `(",", ": ")` with one. +pub struct Format { + pub indent: Option, + pub item: &'static str, + pub key: &'static str, +} + +/// `json.dumps(value)`. +pub const DEFAULT: Format = Format { + indent: None, + item: ", ", + key: ": ", +}; +/// `json.dumps(value, separators=(',', ':'))`. +pub const COMPACT: Format = Format { + indent: None, + item: ",", + key: ":", +}; +/// `json.dumps(value, indent=2)`. +pub const INDENT2: Format = Format { + indent: Some(2), + item: ",", + key: ": ", +}; + +pub fn dumps(value: &Value, format: &Format) -> String { + let mut out = String::new(); + write_value(&mut out, value, format, 0); + out +} + +fn newline(out: &mut String, format: &Format, level: usize) { + if let Some(indent) = format.indent { + out.push('\n'); + out.extend(std::iter::repeat_n(' ', indent * level)); + } +} + +fn write_value(out: &mut String, value: &Value, format: &Format, level: usize) { + match value { + Value::Null => out.push_str("null"), + Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), + Value::Int(digits) => out.push_str(digits), + Value::Float(f) => out.push_str(&float_repr(*f)), + Value::Str(s) => write_string(out, s), + Value::Array(items) => { + if items.is_empty() { + out.push_str("[]"); + return; + } + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push_str(format.item); + } + newline(out, format, level + 1); + write_value(out, item, format, level + 1); + } + newline(out, format, level); + out.push(']'); + } + Value::Object(fields) => { + if fields.is_empty() { + out.push_str("{}"); + return; + } + out.push('{'); + for (i, (key, item)) in fields.iter().enumerate() { + if i > 0 { + out.push_str(format.item); + } + newline(out, format, level + 1); + write_string(out, key); + out.push_str(format.key); + write_value(out, item, format, level + 1); + } + newline(out, format, level); + out.push('}'); + } + } +} + +/// Python's `py_encode_basestring_ascii`: every character outside space..`~` is escaped, +/// with lowercase hex and surrogate pairs above the BMP. +pub fn write_string(out: &mut String, s: &str) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + ' '..='~' => out.push(c), + _ => { + let mut units = [0u16; 2]; + for unit in c.encode_utf16(&mut units) { + let _ = write!(out, "\\u{unit:04x}"); + } + } + } + } + out.push('"'); +} + +/// Python's `repr(float)`: the shortest digits that read back the same, in fixed notation when +/// the decimal point falls between 10^-4 and 10^16, with `.0` on whole numbers. +pub fn float_repr(f: f64) -> String { + if f.is_nan() { + return "NaN".into(); + } + if f.is_infinite() { + return if f > 0.0 { "Infinity" } else { "-Infinity" }.into(); + } + // Rust's `{:e}` gives the same shortest round-trip digits: "d.ddde-x". + let scientific = format!("{:e}", f.abs()); + let (mantissa, exponent) = scientific.split_once('e').unwrap(); + let digits: String = mantissa.chars().filter(|c| *c != '.').collect(); + let exponent: i32 = exponent.parse().unwrap(); + let point = exponent + 1; // The value is 0.digits * 10^point. + let sign = if f.is_sign_negative() { "-" } else { "" }; + let n = digits.len() as i32; + if f == 0.0 { + return format!("{sign}0.0"); + } + if -4 < point && point <= 16 { + if point <= 0 { + format!("{sign}0.{}{digits}", "0".repeat((-point) as usize)) + } else if point >= n { + format!("{sign}{digits}{}.0", "0".repeat((point - n) as usize)) + } else { + let (whole, fraction) = digits.split_at(point as usize); + format!("{sign}{whole}.{fraction}") + } + } else { + let (first, rest) = digits.split_at(1); + let mantissa = if rest.is_empty() { + first.to_string() + } else { + format!("{first}.{rest}") + }; + let e = point - 1; + format!( + "{sign}{mantissa}e{}{:02}", + if e < 0 { '-' } else { '+' }, + e.abs() + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn floats_print_as_python_repr() { + for (f, repr) in [ + (0.0, "0.0"), + (-0.0, "-0.0"), + (1.0, "1.0"), + (0.1, "0.1"), + (1.5e-5, "1.5e-05"), + (0.0001, "0.0001"), + (1e16, "1e+16"), + (1234567890123456.0, "1234567890123456.0"), + (12345678901234567.0, "1.2345678901234568e+16"), + (-2.5, "-2.5"), + (1e-310, "1e-310"), + (f64::MAX, "1.7976931348623157e+308"), + (100.0, "100.0"), + (0.30000000000000004, "0.30000000000000004"), + ] { + assert_eq!(float_repr(f), repr, "{f}"); + } + } + + #[test] + fn strings_escape_as_ensure_ascii() { + let mut out = String::new(); + write_string(&mut out, "a\"\\\n\u{7f}รฉ\u{1F600}\u{1}"); + assert_eq!(out, "\"a\\\"\\\\\\n\\u007f\\u00e9\\ud83d\\ude00\\u0001\""); + } + + #[test] + fn objects_keep_first_place_and_last_value() { + let v = loads(r#"{"b": 1, "a": [1.0, -0, 1e2, true, null], "b": 2}"#).unwrap(); + assert_eq!( + dumps(&v, &DEFAULT), + r#"{"b": 2, "a": [1.0, 0, 100.0, true, null]}"# + ); + assert_eq!( + dumps(&v, &INDENT2), + "{\n \"b\": 2,\n \"a\": [\n 1.0,\n 0,\n 100.0,\n true,\n null\n ]\n}" + ); + assert_eq!( + dumps(&loads("{\"x\":{},\"y\":[]}").unwrap(), &INDENT2), + "{\n \"x\": {},\n \"y\": []\n}" + ); + } +} diff --git a/crates/horizon-prepare/src/survival.rs b/crates/horizon-prepare/src/survival.rs new file mode 100644 index 000000000..16c451c32 --- /dev/null +++ b/crates/horizon-prepare/src/survival.rs @@ -0,0 +1,146 @@ +//! Survival rules of the world generator's feature placement: each block's rule from the class +//! vanilla gives it and the class of its placement check (tools/test_block_survival_parity.py's +//! `bind_definitions` and its tables). + +use crate::pyjson::Value; + +const CLASS_RULES: &[(&str, &str)] = &[ + ("FireBlock", "Fire"), + ("CactusBlock", "Cactus"), + ("PathBlock", "Path"), + ("MushroomBlock", "Mushroom"), + ("MultifaceBlock", "Multiface"), + ("VineBlock", "Vine"), + ("HangingMossBlock", "HangingMoss"), + ("SeaPickleBlock", "SeaPickle"), + ("SnowLayerBlock", "SnowLayer"), + ("BellBlock", "Bell"), + ("ShelfMushroomBlock", "FullBehind"), + ("GrowingPlantBlock", "GrowingPlant"), + ("MangrovePropaguleBlock", "MangrovePropagule"), + ("SpeleothemBlock", "Speleothem"), + ("ScaffoldingBlock", "Scaffolding"), + ("PistonHeadBlock", "PistonHead"), + ("ChorusPlantBlock", "ChorusPlant"), + ("ChorusFlowerBlock", "ChorusFlower"), + ("PitcherCropBlock", "PitcherCrop"), + ("BigDripleafBlock", "BigDripleaf"), + ("BigDripleafStemBlock", "BigDripleafStem"), + ("FarmlandBlock", "Farmland"), + ("CocoaBlock", "Cocoa"), + ("SugarCaneBlock", "SugarCane"), + ("SporeBlossomBlock", "SporeBlossom"), + ("FrogspawnBlock", "Frogspawn"), + ("SmallDripleafBlock", "SmallDripleaf"), + ("TallSeagrassBlock", "TallSeagrass"), + ("DoorBlock", "Door"), + ("BaseRailBlock", "RigidBelow"), + ("LeafLitterBlock", "FullBelow"), + ("WallSignBlock", "SolidBehind"), + ("GrindstoneBlock", "Always"), + ("RedstoneWallTorchBlock", "FullBehind"), + ("BubbleColumnBlock", "BubbleColumn"), + ("RedstoneWireBlock", "RedstoneWire"), + ("SoulFireBlock", "TagBelow:minecraft:soul_fire_base_blocks"), + ("BlockBehaviour", "Always"), + ("CakeBlock", "SolidBelow"), + ("CandleCakeBlock", "SolidBelow"), + ("BannerBlock", "SolidBelow"), + ("StandingSignBlock", "SolidBelow"), + ("WallBannerBlock", "SolidBehind"), + ("CarpetBlock", "NonAirBelow"), + ("MossyCarpetBlock", "MossCarpet"), + ("BaseTorchBlock", "CenterBelow"), + ("CandleBlock", "CenterBelow"), + ("LanternBlock", "Lantern"), + ("HangingRootsBlock", "FullAbove"), + ("LadderBlock", "FullBehind"), + ("AmethystClusterBlock", "FullBehind"), + ("TripWireHookBlock", "FullBehind"), + ("BaseCoralWallFanBlock", "FullBehind"), + ("WallTorchBlock", "FullBehind"), + ("BasePressurePlateBlock", "RigidOrCenterBelow"), + ("DiodeBlock", "RigidBelow"), + ("BaseCoralPlantTypeBlock", "FullBelow"), + ("CeilingHangingSignBlock", "CenterAbove"), + ("FaceAttachedHorizontalDirectionalBlock", "FaceAttached"), + ("BambooSaplingBlock", "SupportsBamboo"), + ("BambooStalkBlock", "SupportsBamboo"), +]; + +const VEGETATION_RULES: &[(&str, &str)] = &[ + ("LilyPadBlock", "LilyPad"), + ("VegetationBlock", "TagBelow:minecraft:supports_vegetation"), + ("AzaleaBlock", "TagBelow:minecraft:supports_azalea"), + ( + "DryVegetationBlock", + "TagBelow:minecraft:supports_dry_vegetation", + ), + ( + "NetherSproutsBlock", + "TagBelow:minecraft:supports_nether_sprouts", + ), + ("NetherWartBlock", "TagBelow:minecraft:supports_nether_wart"), + ("WitherRoseBlock", "TagBelow:minecraft:supports_wither_rose"), + ("CactusFlowerBlock", "CactusFlower"), + ("SeagrassBlock", "Seagrass"), +]; + +fn lookup(table: &[(&str, &'static str)], key: &str) -> Option<&'static str> { + table.iter().find(|(k, _)| *k == key).map(|(_, v)| *v) +} + +/// `{block: rule}` from the exporter's `{block: class}`, `{block: placement class}` and +/// `{block: {field: support tag}}`, in the order Python's dict built it. +pub fn bind_definitions( + classes: &Value, + placement: &Value, + support_tags: &Value, +) -> Result { + let classes = classes + .as_object() + .ok_or("survival-classes.json is not an object")?; + let mut definitions = Value::Object(Vec::new()); + for (name, owner) in classes { + if let Some(rule) = owner.as_str().and_then(|o| lookup(CLASS_RULES, o)) { + definitions.insert(name, Value::str(rule)); + } + } + for (name, owner) in classes { + let owner = owner.as_str().unwrap_or(""); + let placed = placement.get(name).and_then(Value::as_str); + if owner == "CropBlock" && placed == Some("CropBlock") { + definitions.insert(name, Value::str("Crop")); + } + if owner == "DoublePlantBlock" && placed == Some("VegetationBlock") { + definitions.insert(name, Value::str("DoublePlant")); + } + if owner != "VegetationBlock" { + continue; + } + let method = placed.ok_or_else(|| format!("No placement class for {name}"))?; + if let Some(rule) = lookup(VEGETATION_RULES, method) { + definitions.insert(name, Value::str(rule)); + } else if [ + "AttachedStemBlock", + "StemBlock", + "NetherFungusBlock", + "NetherRootsBlock", + ] + .contains(&method) + { + let field = if method == "StemBlock" { + "stemSupportBlocks" + } else { + "supportBlocks" + }; + let tag = support_tags + .get(name) + .and_then(|t| t.get(field)) + .and_then(Value::as_str) + .ok_or_else(|| format!("No {field} support tag for {name}"))?; + definitions.insert(name, Value::Str(format!("TagBelow:{tag}"))); + } + } + Ok(definitions) +} diff --git a/tools/compare_prepare.py b/tools/compare_prepare.py new file mode 100644 index 000000000..58216af00 --- /dev/null +++ b/tools/compare_prepare.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Check that horizon-prepare (Rust) writes what the Python preparer wrote. + +Prepares the same jars three times in fresh folders made from the same tree (research-lock.json +and the vanilla exporters of --python-ref): twice with that ref's tools/prepare_native_client.py +and once with horizon-prepare. Every file under .local/ is compared by sha256: + +- identical: the same bytes in all three runs; +- exporter noise: differs between the two Python runs too, so the vanilla Java exporter itself + writes it differently each run (lambda addresses, hash-set order), not the preparer; +- port differences: identical between the Python runs but not in the Rust run. There must be none. + +The manifest (horizon-resources.json) is compared field by field: only the recorded hashes of +exporter-noise files may differ, and each must be the hash of its own run's file. + +Then each preparer runs again over the other's output (Rust over a Python tree, Python over the +Rust tree): the manifests are read the same way, so nothing is exported again and no resource +changes. Development tool: it needs Python 3.11+, Java and git. Report: /report.json. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +# The last commit whose tools/prepare_native_client.py is the Python preparer itself. +PYTHON_REF = '66ce394d2d6dc19ed5f5c53a97b650741af9be76' +# Written by tools the comparison is not about: the decompiler only lab.py fetches, logs with +# times in them, compiled classes, and the data generator's own dated cache. +IGNORED_PARTS = {'classes', 'client-classes', 'logs', '.cache'} + + +def tree(ref, destination): + destination.mkdir(parents=True) + archive = subprocess.run(['git', '-C', str(ROOT), 'archive', ref, 'tools', 'mods/horizon/src/test/java', + 'research-lock.json'], check=True, capture_output=True).stdout + subprocess.run(['tar', '-x', '-C', str(destination)], input=archive, check=True) + + +def hashes(folder): + local = folder / '.local' + result = {} + for path in sorted(local.rglob('*')): + relative = path.relative_to(local) + if path.is_file() and not (set(relative.parts) & IGNORED_PARTS) and path.suffix != '.log': + result[relative.as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + return result + + +def run(name, command, cwd, log): + started = time.monotonic() + with log.open('w') as stream: + subprocess.run(command, cwd=cwd, check=True, stdout=stream, stderr=subprocess.STDOUT) + seconds = round(time.monotonic() - started, 1) + print(f'{name}: {seconds} s', flush=True) + return seconds + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--server-jar', type=Path, required=True) + parser.add_argument('--minecraft-dir', type=Path, required=True) + parser.add_argument('--python-ref', default=PYTHON_REF) + parser.add_argument('--binary', type=Path, help='horizon-prepare to test (default: cargo build --release)') + parser.add_argument('--work', type=Path, default=ROOT / '.local/compare-prepare') + parser.add_argument('--keep', action='store_true', help='keep the prepared folders') + args = parser.parse_args() + binary = args.binary + if binary is None: + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-prepare'], cwd=ROOT, check=True) + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ( + 'horizon-prepare.exe' if os.name == 'nt' else 'horizon-prepare') + binary = binary.resolve() + work = args.work.resolve() + shutil.rmtree(work, ignore_errors=True) + work.mkdir(parents=True) + game = ['--prepare', '--server-jar', str(args.server_jar.resolve()), + '--minecraft-dir', str(args.minecraft_dir.resolve())] + python = [sys.executable, '-u', 'tools/prepare_native_client.py', *game] + folders = {name: work / name for name in ['python-1', 'python-2', 'rust']} + times = {} + for name, folder in folders.items(): + tree(args.python_ref, folder) + command = [str(binary), '--root', str(folder), *game] if name == 'rust' else python + times[name] = run(name, command, folder, work / f'{name}.log') + first, second, rust = (hashes(folders[n]) for n in ['python-1', 'python-2', 'rust']) + names = sorted(first.keys() | second.keys() | rust.keys()) + identical = [n for n in names if first.get(n) == second.get(n) == rust.get(n) is not None] + noise = [n for n in names if first.get(n) != second.get(n)] + port = [n for n in names if n not in identical and n not in noise] + # Only lab.py fetches the decompiler; preparing does not need it. + port = [n for n in port if not (n.startswith('tools/vineflower-') and n not in rust)] + manifest = 'horizon-client/' + json.loads((folders['rust'] / 'research-lock.json').read_text())[ + 'minecraft']['version'] + '/horizon-resources.json' + noisy = {n.rsplit('/', 1)[-1] for n in noise if n.startswith(manifest.rsplit('/', 1)[0] + '/')} + manifests = {n: json.loads((folders[n] / '.local' / manifest).read_text()) for n in folders} + manifest_differences = [] + + def walk(python, candidate, path): + if isinstance(python, dict) and isinstance(candidate, dict) and list(python) == list(candidate): + for key in python: + walk(python[key], candidate[key], path + [key]) + elif python != candidate: + name = path[-1] + expected = hashlib.sha256((folders['rust'] / '.local' / manifest).with_name(name).read_bytes()).hexdigest() \ + if name in noisy else None + if not (name in noisy and candidate == expected): + manifest_differences.append('.'.join(path)) + + walk(manifests['python-1'], manifests['rust'], []) + if manifest in port and not manifest_differences: + port.remove(manifest) + # Each preparer over the other's output: nothing to export again, no resource changes. + resources = 'horizon-client/' + before = {'python-2': second, 'rust': rust} + times['rust over python'] = run('rust over python', [str(binary), '--root', str(folders['python-2']), *game], + folders['python-2'], work / 'rust-over-python.log') + times['python over rust'] = run('python over rust', python, folders['rust'], work / 'python-over-rust.log') + rerun_changes = {} + for name in before: + after = hashes(folders[name]) + changed = [n for n in sorted(before[name].keys() | after.keys()) + if n.startswith(resources) and before[name].get(n) != after.get(n)] + rerun_changes[name] = changed + exported_again = {name: [line.strip() for line in (work / log).read_text().splitlines() if 'Exporting' in line] + for name, log in [('rust over python', 'rust-over-python.log')]} + report = {'python_ref': args.python_ref, 'binary': str(binary), 'seconds': times, + 'files': len(names), 'identical': len(identical), 'exporter_noise': noise, + 'port_differences': port, 'manifest_differences': manifest_differences, + 'rerun_resource_changes': rerun_changes, 'exported_again': exported_again} + (work / 'report.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2)) + if not args.keep: + for folder in folders.values(): + shutil.rmtree(folder, ignore_errors=True) + ok = not port and not manifest_differences + print('identical output' if ok else 'DIFFERENT OUTPUT', flush=True) + return 0 if ok else 1 + + +if __name__ == '__main__': + sys.exit(main()) From a995fd3b46a1e65650b0a3c8f4fdf5385ce8b672 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:03:26 +0200 Subject: [PATCH 05/11] Prepare with horizon-prepare: launcher, release folders, messages and docs The launcher prepares a version in-process when it ships the preparer sources the launcher was built with, with the version's own horizon-prepare when they differ, and with the Python script only for versions made before it. Release folders ship horizon-prepare and its sources; resources are reused between versions with the same preparer. The game's messages, PLAY.txt, the docs and release builds name horizon-prepare, and tools/prepare_native_client.py is a wrapper of it for the development tools. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 8 +- README.md | 2 +- crates/horizon-client/src/game.rs | 6 +- crates/horizon-client/src/game/remote.rs | 2 +- crates/horizon-client/src/vanillagen.rs | 2 +- crates/horizon-world/src/level/mod.rs | 2 +- .../src/worldgen/generator_blocks.rs | 2 +- docs/native-client.md | 13 +- docs/parity/meshing.md | 2 +- launcher/Cargo.lock | 22 + launcher/Cargo.toml | 1 + launcher/README.md | 7 +- launcher/src/backend.rs | 171 ++++++- launcher/src/cli.rs | 8 +- launcher/src/main.rs | 18 +- launcher/src/mcp.rs | 25 +- packaging/PLAY.txt | 9 +- packaging/package.sh | 27 +- tools/package_native_client.py | 2 +- tools/prepare_native_client.py | 463 +----------------- tools/rea_vanilla.py | 2 +- tools/test_creative_parity.py | 2 +- 22 files changed, 275 insertions(+), 521 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e36ce3685..3ea634cb6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,6 @@ name: release builds # Started by hand: gh workflow run release.yml --ref -# Builds the Windows x64 and Linux x86_64 clients (with horizon-ctl) and uploads the playable folders +# Builds the Windows x64 and Linux x86_64 clients (with horizon-ctl and horizon-prepare) and uploads the playable folders # as artifacts. # macOS builds are made on the development machines. Linux is built here, on an older Ubuntu, # so the binary uses the standard loader and runs on any recent distribution (and on NixOS @@ -20,13 +20,14 @@ jobs: # The C runtime linked in, so the game runs without the Visual C++ redistributable. env: RUSTFLAGS: -C target-feature=+crt-static - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl + run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare - name: Only system DLLs # Vulkan and the rest are loaded at run time; a linked non-system DLL is a # "DLL not found" dialog on some players' machines. run: | python tools/check_imports.py target/release/horizon-client.exe python tools/check_imports.py target/release/horizon-ctl.exe + python tools/check_imports.py target/release/horizon-prepare.exe - name: Package shell: bash run: packaging/package.sh target/release/horizon-client.exe dist/horizon-windows-x64 @@ -43,11 +44,12 @@ jobs: - name: ALSA headers run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev - name: Build the client - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl + run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare - name: Standard loader and libraries only run: | python3 tools/check_imports.py target/release/horizon-client python3 tools/check_imports.py target/release/horizon-ctl + python3 tools/check_imports.py target/release/horizon-prepare - name: Package run: packaging/package.sh target/release/horizon-client dist/horizon-linux-x86_64 - uses: actions/upload-artifact@v4 diff --git a/README.md b/README.md index e102924d5..cf56bd042 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ Horizon contains no game files and never downloads them. It builds its resources ```sh git clone https://github.com/ludovic111/horizon.git cd horizon -python3 tools/prepare_native_client.py --prepare --server-jar ~/Downloads/server.jar # needs JDK 25 +cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar # needs JDK 25 python3 tools/fetch_sounds.py # optional: sounds from your launcher install cargo run --release -p horizon-client ``` diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3cd8d5105..cc86da9e1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -243,7 +243,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon โ€” Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + "Horizon โ€” Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." ); return Ok(None); } @@ -5617,7 +5617,7 @@ impl Game<'_> { ) } else { let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), res.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { - format!("{e}\nPrepare the worldgen bundle with: python3 tools/prepare_native_client.py") + format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare") })?); self.end.set_locator(Some(inner.clone())); Streaming::new( @@ -8692,7 +8692,7 @@ pub fn run() -> Result<()> { } Err(e) => { return Err(format!( - "{e}\nPrepare resources with: python3 tools/prepare_native_client.py --prepare" + "{e}\nPrepare resources with the launcher, or: horizon-prepare --prepare" ) .into()); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 657f6e65c..cfb65fbeb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -154,7 +154,7 @@ impl Game<'_> { let root = self.options.resources.clone(); let builtin = Builtin::find(&root) .and_then(|p| Builtin::load(&p).ok()) - .ok_or("registries.json not found next to the resources; run the data generator reports (tools/prepare_native_client.py)")?; + .ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?; let lang = Arc::new(horizon_client::net::load_language(&root)); let view = self.settings.render_distance.clamp(2, 32) as i8; let session = Session::connect(address, name, view, lang.clone()); diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 9b48edb18..86d2a3922 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -62,7 +62,7 @@ impl VanillaTerrain { if !dir.join("blocks/block-properties.nbt").exists() { eprintln!( "Horizon: the worldgen bundle lacks the block behavior exports (worldgen/blocks/*.nbt); \ - run python3 tools/prepare_native_client.py to add them" + prepare again (the launcher, or horizon-prepare --prepare) to add them" ); } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3b8428131..f04c65941 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -8,7 +8,7 @@ //! [`Behaviours`] holds immutable tables loaded once from the pinned client //! resources (`block-behaviours.json`, `gameplay-facts.json`, //! `block-tags.json`, `cached-collision.nbt`; see -//! `tools/prepare_native_client.py`). +//! `crates/horizon-prepare`). //! //! # Driving a level //! diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs index 390fb338c..6085183ec 100644 --- a/crates/horizon-world/src/worldgen/generator_blocks.rs +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -1,6 +1,6 @@ //! Optional block-behavior registries used by feature placement: physical //! properties, face support, collision and survival rules. Loaded from the -//! bundle's `blocks/` directory (Java-exported, see prepare_native_client.py). +//! bundle's `blocks/` directory (Java-exported, see crates/horizon-prepare). use super::generator::GeneratorError; use crate::{ block_collision::BlockCollisionRegistry, diff --git a/docs/native-client.md b/docs/native-client.md index b6f2e0db5..f25067d64 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -14,7 +14,8 @@ missing; [Rust rewrite status](rust-parity.md) has the details. ## Run from a checkout -Use current stable Rust (1.90+), Python 3.10+ and JDK 25. Horizon never +Use current stable Rust (1.90+) and JDK 25 (Python 3.10+ for the sounds and the +development harnesses). Horizon never downloads the game: resource preparation imports **your own copy** (the 26.3 client from your official launcher install, and the 26.3 server jar you downloaded yourself; see [Build from source](../README.md#build-from-source)), @@ -23,8 +24,12 @@ exporters against those jars, and extracts the jar's assets and data into ignore `.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your launcher's asset store. Prepared resources are private; never commit them. +Preparation is `horizon-prepare` (`crates/horizon-prepare`, Rust): it needs no Python, only +the JDK, for the small exporters that call Mojang's own code. Release folders ship it beside +`horizon-client`, and the launcher prepares with it. + ```sh -python3 tools/prepare_native_client.py --prepare --server-jar ~/Downloads/server.jar +cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar python3 tools/fetch_sounds.py cargo run --release -p horizon-client -- --render-distance 12 ``` @@ -205,7 +210,7 @@ attribute. Sneaking invokes ledge backoff before collision resolution. The complete authoritative player tick remains unfinished. ```sh -python3 tools/prepare_native_client.py +cargo run --release -p horizon-prepare python3 tools/test_native_scene_collision.py ``` @@ -264,7 +269,7 @@ The [renderer startup check](../benchmarks/rust-native-walking-2026-10-07/startu also passes after the movement integration. ```sh -python3 tools/prepare_native_client.py +cargo run --release -p horizon-prepare python3 tools/test_native_scene_motion.py python3 tools/test_local_input_parity.py ``` diff --git a/docs/parity/meshing.md b/docs/parity/meshing.md index 919c67891..5b746e76c 100644 --- a/docs/parity/meshing.md +++ b/docs/parity/meshing.md @@ -82,7 +82,7 @@ python3 tools/test_section_mesh_parity.py --only fluids ``` It needs the pinned jars (`tools/lab.py prepare`) and prepared client resources -(`tools/prepare_native_client.py --prepare`). Outputs, logs and +(`cargo run --release -p horizon-prepare -- --prepare`). Outputs, logs and `report.json` go to `target/section-mesh-parity/`; nothing is written under `.local/`. The fixture is built with `--profile fast` and reports its meshing time. diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index af0228a97..be7ea5b7f 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2571,6 +2571,7 @@ dependencies = [ "dirs 5.0.1", "flate2", "gpui", + "horizon-prepare", "horizon-theme", "image", "pulldown-cmark", @@ -2582,6 +2583,16 @@ dependencies = [ "zip", ] +[[package]] +name = "horizon-prepare" +version = "0.1.0" +dependencies = [ + "regex", + "sha1", + "sha2 0.10.9", + "zip", +] + [[package]] name = "horizon-theme" version = "0.1.0" @@ -4964,6 +4975,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha1_smol" version = "1.0.1" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index f10d1ae50..466b3bc05 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -21,6 +21,7 @@ self-replace = "1" image = { version = "0.25", default-features = false, features = ["jpeg"] } clap = { version = "4", features = ["derive"] } horizon-theme = { path = "../crates/horizon-theme" } +horizon-prepare = { path = "../crates/horizon-prepare" } [profile.release] strip = true diff --git a/launcher/README.md b/launcher/README.md index 6b91a0a66..828903ab3 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -15,8 +15,11 @@ The opening, then Play ([clip](docs/opening.webm)): - **Versions**: lists the published releases of ludovic111/horizon, installs the build for this platform into its own folder, and removes it again. - **Play**: prepares resources as `PLAY.txt` describes (your launcher's 26.3 install, the - 26.3 server jar from that version's own json, Python 3.10+ and Java 25), then starts the - client, or a server (`--dedicated --nogui`) in a folder you choose, with a live console. + 26.3 server jar from that version's own json, and Java 25), then starts the client, or a + server (`--dedicated --nogui`) in a folder you choose, with a live console. Preparing is + horizon-prepare: linked into the launcher, used in-process when a version ships the same + preparer sources, else that version's own `horizon-prepare`; versions released before it + still prepare with their Python script and need Python 3.10+. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Join Discord" and "Website" links sit in the sidebar footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 4013d7ca0..4934c4819 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -380,12 +380,15 @@ pub fn is_prepared(tag: &str) -> bool { /// Whether the resources `from` prepared are the ones preparing `to` would make. The output /// depends on the Horizon version, not only on Minecraft's: the manifest records the hashes of -/// the vanilla exporters it was made with (mods/horizon/src/test/java/.../parity), and -/// prepare_native_client.py writes every file and the manifest's `schema`. So both need the -/// same pinned Minecraft jars (research-lock.json), the same prepare_native_client.py and the -/// same exporter sources. The helpers it imports (lab.py and the test_*_parity.py modules) -/// change between releases in how they find and check the player's files, which the output -/// does not depend on; they are not compared. +/// the vanilla exporters it was made with (mods/horizon/src/test/java/.../parity), and the +/// preparer writes every file and the manifest's `schema`. So both need the same pinned +/// Minecraft jars (research-lock.json), the same preparer and the same exporter sources. The +/// preparer is crates/horizon-prepare (its sources ship in the release folder beside the +/// binary) and tools/prepare_native_client.py (the Python preparer of older versions, a wrapper +/// of the binary since); a file only one of the two versions has is a different preparer. The +/// helpers the Python preparer imported (lab.py and the test_*_parity.py modules) change +/// between releases in how they find and check the player's files, which the output does not +/// depend on; they are not compared. fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) -> bool { let pins = |dir: &Path| { read_json(&dir.join("research-lock.json")).map(|lock| { @@ -401,10 +404,22 @@ fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) -> let Some(fields) = manifest.as_object() else { return false; }; - let mut sources = vec![ - "tools/prepare_native_client.py".to_string(), - "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java".to_string(), - ]; + let mut preparer = vec![PathBuf::from("tools/prepare_native_client.py")]; + for dir in [from, to] { + preparer.extend(files_under(dir, Path::new(PREPARER_CRATE))); + } + let same_or_absent = |path: &Path| match (fs::read(from.join(path)), fs::read(to.join(path))) { + (Ok(a), Ok(b)) => a == b, + (Err(a), Err(b)) => { + a.kind() == std::io::ErrorKind::NotFound && b.kind() == std::io::ErrorKind::NotFound + } + _ => false, + }; + if !preparer.iter().all(|p| same_or_absent(p)) { + return false; + } + let mut sources = + vec!["mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java".to_string()]; for (_, value) in fields .iter() .filter(|(key, _)| key.ends_with("_exporters_sha256")) @@ -425,6 +440,26 @@ fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) -> sources.iter().all(|s| same(s)) } +/// Where a version folder keeps the preparer's sources (packaging/package.sh copies them). +const PREPARER_CRATE: &str = "crates/horizon-prepare"; + +/// The files under `dir/relative`, as paths relative to `dir`. +fn files_under(dir: &Path, relative: &Path) -> Vec { + let Ok(entries) = fs::read_dir(dir.join(relative)) else { + return Vec::new(); + }; + let mut files = Vec::new(); + for entry in entries.flatten() { + let path = relative.join(entry.file_name()); + match entry.file_type() { + Ok(t) if t.is_dir() => files.extend(files_under(dir, &path)), + Ok(_) => files.push(path), + Err(_) => {} + } + } + files +} + fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { fs::create_dir_all(to)?; for entry in fs::read_dir(from)? { @@ -500,7 +535,7 @@ fn reuse_prepared_in(versions: &Path) -> Vec<(String, String)> { .collect() } -/// The official launcher's game directory, where prepare_native_client.py looks by default. +/// The official launcher's game directory, where horizon-prepare looks by default. pub fn default_minecraft_dir() -> Option { let home = dirs::home_dir()?; let dir = if cfg!(target_os = "macos") { @@ -531,13 +566,29 @@ fn python() -> Option<&'static str> { candidates.iter().copied().find(|p| found(p, "--version")) } -/// Checks what the preparation needs and builds its command. PLAY.txt describes the same steps: -/// the player's own launcher install, the server jar from that version's own json, Java and Python. -pub fn prepare_command( - tag: &str, - minecraft: &Path, - log: &dyn Fn(String), -) -> Result { +/// How a version's resources are prepared. +pub enum Preparer { + /// horizon-prepare, linked into the launcher: the version ships the same preparer sources. + InProcess(horizon_prepare::Options), + /// The version's own preparer: its horizon-prepare binary when its sources differ from the + /// launcher's (a newer or older release), or the Python script of versions made before it. + Process(Command), +} + +/// The version's horizon-prepare binary, when it ships one. +fn preparer_binary(dir: &Path) -> Option { + let binary = dir.join(if cfg!(windows) { + "horizon-prepare.exe" + } else { + "horizon-prepare" + }); + binary.is_file().then_some(binary) +} + +/// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same +/// steps: the player's own launcher install, the server jar from that version's own json, and +/// Java (and Python, for versions before horizon-prepare). +pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result { let version = game_version(tag); let manifest = minecraft .join("versions") @@ -549,12 +600,27 @@ pub fn prepare_command( minecraft.display() )); } - let python = python().ok_or("Python 3.10 or newer is needed. Install it and try again.")?; - if !found("java", "-version") { - return Err( - "Java 25 is needed (a JDK, e.g. Eclipse Temurin 25). Install it and try again.".into(), - ); - } + let dir = version_dir(tag); + let binary = preparer_binary(&dir); + let python = if binary.is_some() { + // The JDK the version pins, found as horizon-prepare finds it, so a missing one is + // reported before the server jar is downloaded. + let major = read_json(&dir.join("research-lock.json")) + .and_then(|lock| lock["minecraft"]["java_major"].as_i64()) + .ok_or("The version's research-lock.json has no java_major")?; + horizon_prepare::java::find(major)?; + None + } else { + let python = python() + .ok_or("This version prepares with Python: Python 3.10 or newer is needed. Install it, or pick a newer version.")?; + if !found("java", "-version") { + return Err( + "Java 25 is needed (a JDK, e.g. Eclipse Temurin 25). Install it and try again." + .into(), + ); + } + Some(python) + }; let jar = data_dir() .join("server-jars") .join(format!("{version}.jar")); @@ -577,8 +643,29 @@ pub fn prepare_command( .and_then(|_| fs::rename(&partial, &jar)) .map_err(|e| e.to_string())?; } - let mut cmd = Command::new(python); - cmd.current_dir(version_dir(tag)) + if let Some(binary) = binary { + if horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref() + == Some(horizon_prepare::SOURCES_SHA256) + { + return Ok(Preparer::InProcess(horizon_prepare::Options { + root: dir, + import: true, + minecraft_dir: Some(minecraft.to_path_buf()), + server_jar: Some(jar), + })); + } + let mut cmd = Command::new(binary); + cmd.current_dir(&dir) + .arg("--root") + .arg(&dir) + .args(["--prepare", "--server-jar"]) + .arg(&jar) + .arg("--minecraft-dir") + .arg(minecraft); + return Ok(Preparer::Process(cmd)); + } + let mut cmd = Command::new(python.unwrap()); + cmd.current_dir(&dir) .args([ "-u", "tools/prepare_native_client.py", @@ -588,7 +675,20 @@ pub fn prepare_command( .arg(&jar) .arg("--minecraft-dir") .arg(minecraft); - Ok(cmd) + Ok(Preparer::Process(cmd)) +} + +/// Runs `Preparer::InProcess` on this thread, each progress line to `log`. A panic is an +/// error like any other, so the window never waits on a preparation that died. +pub fn prepare_in_process( + options: &horizon_prepare::Options, + log: &dyn Fn(String), +) -> Result<(), String> { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + horizon_prepare::prepare(options, &|line| log(line.to_string())) + })) + .unwrap_or_else(|_| Err("The preparation stopped unexpectedly".into())) + .map(|_| ()) } /// Where the game keeps saves and options.txt: `HORIZON_HOME`, else `horizon` in the platform's @@ -1430,6 +1530,23 @@ mod tests { assert!(is_prepared("v2026.10.17")); assert!(!is_prepared("v2026.10.15") && !is_prepared("v2026.10.16")); assert!(reuse_prepared_in(&versions).is_empty()); + + // Versions with horizon-prepare: its sources are the preparer, so the same sources + // reuse each other's resources, and a change or a version without them prepares again. + let crate_file = "crates/horizon-prepare/src/lib.rs"; + release("v2026.10.18", "26.3"); + write("v2026.10.18", crate_file, "rust preparer"); + assert_eq!(reuse_prepared(&versions, "v2026.10.18"), None); + prepared("v2026.10.18", "26.3"); + release("v2026.10.19", "26.3"); + write("v2026.10.19", crate_file, "rust preparer"); + assert_eq!( + reuse_prepared(&versions, "v2026.10.19"), + Some("v2026.10.18".into()) + ); + release("v2026.10.20", "26.3"); + write("v2026.10.20", crate_file, "rust preparer, changed"); + assert_eq!(reuse_prepared(&versions, "v2026.10.20"), None); let _ = fs::remove_dir_all(&versions); } diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index df78436aa..db5b36deb 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -205,8 +205,12 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { Cmd::Prepare { minecraft, version } => { let tag = backend::resolve_version(version.as_deref())?; let minecraft = backend::minecraft_dir(minecraft)?; - let cmd = backend::prepare_command(&tag, &minecraft, &|line| eprintln!("{line}"))?; - attached(cmd)?; + match backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))? { + backend::Preparer::Process(cmd) => attached(cmd)?, + backend::Preparer::InProcess(options) => { + backend::prepare_in_process(&options, &|line| println!("{line}"))? + } + } println!("{tag} is prepared."); } Cmd::Play { version } => attached(backend::client(&backend::resolve_version( diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 7dbac7b5a..5f620fbe3 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -472,17 +472,27 @@ impl Launcher { self.prepare_log.clear(); self.prepare_error = None; self.prepare_log - .push_back("Checking Java, Python and your Minecraft install".into()); + .push_back("Checking Java and your Minecraft install".into()); let tx = self.tx.clone(); // The checks may download the server jar, so they run on the thread too. std::thread::spawn(move || { let log = |line| { let _ = tx.send(Msg::Line(Job::Prepare, line)); }; - let result = backend::prepare_command(&tag, &minecraft, &log) - .and_then(|cmd| backend::spawn(Job::Prepare, cmd, tx.clone())); + let result = backend::preparer(&tag, &minecraft, &log).and_then(|p| match p { + backend::Preparer::Process(cmd) => { + backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false) + } + backend::Preparer::InProcess(options) => { + backend::prepare_in_process(&options, &log).map(|_| true) + } + }); match result { - Ok(_running) => {} + // A process sends its own Exit when it ends. + Ok(false) => {} + Ok(true) => { + let _ = tx.send(Msg::Exit(Job::Prepare, Ok(()))); + } Err(e) => { let _ = tx.send(Msg::Exit(Job::Prepare, Err(e))); } diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index fa5145464..c590d066d 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -24,7 +24,7 @@ fn tools() -> Value { "inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "A release tag such as v2026.10.13, or \"latest\"." } }, "required": ["tag"] } }, { "name": "remove_version", "description": "Remove an installed Horizon version and its prepared resources.", "inputSchema": { "type": "object", "properties": { "tag": { "type": "string" } }, "required": ["tag"] } }, - { "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs Minecraft 26.3 played once in the official launcher, Java 25 and Python 3.10+). Can take several minutes; returns the end of the log.", + { "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs Minecraft 26.3 played once in the official launcher and Java 25; versions before horizon-prepare also need Python 3.10+). Can take several minutes; returns the end of the log.", "inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The official launcher's game folder. Default: the launcher's setting, else the platform default." } } } }, { "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen). Returns once it has started.", "inputSchema": { "type": "object", "properties": { "version": version } } }, @@ -95,10 +95,25 @@ impl Session { let tag = backend::resolve_version(arg_str(args, "version"))?; let minecraft = backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?; - let cmd = backend::prepare_command(&tag, &minecraft, &|_| {})?; - let run = Logged::start(Job::Prepare, cmd)?; - let result = run.wait(); - let tail = run.tail(20).join("\n"); + let (result, tail) = match backend::preparer(&tag, &minecraft, &|_| {})? { + backend::Preparer::Process(cmd) => { + let run = Logged::start(Job::Prepare, cmd)?; + let result = run.wait(); + (result, run.tail(20).join("\n")) + } + backend::Preparer::InProcess(options) => { + let lines = std::cell::RefCell::new(std::collections::VecDeque::new()); + let result = backend::prepare_in_process(&options, &|line| { + let mut lines = lines.borrow_mut(); + lines.push_back(line); + if lines.len() > 20 { + lines.pop_front(); + } + }); + let tail = lines.into_inner().into_iter().collect::>().join("\n"); + (result, tail) + } + }; result .map(|_| format!("{tag} is prepared.\n{tail}")) .map_err(|e| format!("{e}\n{tail}")) diff --git a/packaging/PLAY.txt b/packaging/PLAY.txt index e932c0db3..ea579d8af 100644 --- a/packaging/PLAY.txt +++ b/packaging/PLAY.txt @@ -17,11 +17,10 @@ Downloaded this archive directly? More about Horizon: https://playhorizon.dev To prepare this folder by hand you need Minecraft Java Edition 26.3, played - once from the official launcher, Python 3.10+ and Java 25 (a JDK). Then, - in this folder: - python3 tools/prepare_native_client.py --prepare --server-jar PATH/TO/server.jar - python3 tools/fetch_sounds.py (optional, for sound) - (Windows: py instead of python3.) The 26.3 server jar is the + once from the official launcher, and Java 25 (a JDK). Then, in this folder: + ./horizon-prepare --prepare --server-jar PATH/TO/server.jar + python3 tools/fetch_sounds.py (optional, for sound; needs Python 3.10+) + (Windows: horizon-prepare.exe, and py instead of python3.) The 26.3 server jar is the downloads.server.url in your launcher's versions/26.3/26.3.json. Add --minecraft-dir PATH if your launcher keeps the game elsewhere. Then run ./horizon-client (horizon-client.exe on Windows; on macOS the first time: diff --git a/packaging/package.sh b/packaging/package.sh index a289116a0..ba5545df0 100755 --- a/packaging/package.sh +++ b/packaging/package.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # packaging/package.sh BINARY OUTDIR: a playable Horizon folder with the game -# binary, horizon-ctl (built beside it: cargo build --release -p horizon-client --bins), -# the resource preparation tool and what it compiles, and PLAY.txt. +# binary, horizon-ctl and horizon-prepare (built beside it: cargo build --release +# -p horizon-client --bins -p horizon-prepare), the exporters horizon-prepare compiles, +# its sources (the launcher compares them to its own), and PLAY.txt. # It holds none of Minecraft's files: players prepare those from their own copy. set -euo pipefail bin=$1 @@ -9,14 +10,18 @@ out=$2 repo=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) rm -rf "$out" mkdir -p "$out" -git -C "$repo" archive HEAD tools mods/horizon/src/test/java research-lock.json LICENSE | tar -x -C "$out" +git -C "$repo" archive HEAD tools mods/horizon/src/test/java crates/horizon-prepare research-lock.json LICENSE \ + | tar -x -C "$out" cp "$bin" "$out/" -# horizon-ctl, the command line and MCP server that play the game, sits beside the client. -ctl="$(dirname "$bin")/horizon-ctl" -case "$bin" in *.exe) ctl="$ctl.exe" ;; esac -if [ ! -f "$ctl" ]; then - echo "package.sh: $ctl is missing; build it too: cargo build --release -p horizon-client --bins" >&2 - exit 1 -fi -cp "$ctl" "$out/" +# horizon-ctl, the command line and MCP server that play the game, and horizon-prepare, which +# prepares the resources from the player's own Minecraft, sit beside the client. +for tool in horizon-ctl horizon-prepare; do + path="$(dirname "$bin")/$tool" + case "$bin" in *.exe) path="$path.exe" ;; esac + if [ ! -f "$path" ]; then + echo "package.sh: $path is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare" >&2 + exit 1 + fi + cp "$path" "$out/" +done cp "$repo/packaging/PLAY.txt" "$out/PLAY.txt" diff --git a/tools/package_native_client.py b/tools/package_native_client.py index abda2210f..9b477c8f7 100644 --- a/tools/package_native_client.py +++ b/tools/package_native_client.py @@ -85,7 +85,7 @@ def main(): if not args.binary.is_file(): raise SystemExit(f'missing {args.binary}: run cargo build --release -p horizon-client') if not (args.resources / 'horizon-resources.json').is_file(): - raise SystemExit(f'missing prepared resources in {args.resources}: run tools/prepare_native_client.py --prepare') + raise SystemExit(f'missing prepared resources in {args.resources}: run horizon-prepare --prepare (cargo run --release -p horizon-prepare -- --prepare)') if not (args.resources / 'assets/minecraft/sounds.json').is_file(): print('warning: no sound assets; run tools/fetch_sounds.py for audio') diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 22c621b70..3ebdf0288 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -1,457 +1,28 @@ #!/usr/bin/env python3 -"""Prepare private pinned resources for Horizon's native development client.""" -import argparse -import json +"""Prepare private pinned resources for Horizon's native development client. + +The preparation itself is horizon-prepare (crates/horizon-prepare), the Rust port of what this +script did; this wrapper keeps its command line for the development tools that call it. It runs +the horizon-prepare beside this folder (a release folder), else builds it with cargo. Arguments +are passed through: --prepare, --server-jar PATH, --minecraft-dir PATH. +""" import os from pathlib import Path import subprocess -import zipfile -try: - from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen, test_model_baking_parity as baking -except ImportError: - import lab - import test_rust_parity as base - import test_worldgen_parity as worldgen - import test_model_baking_parity as baking +import sys - -WORLDGEN_BUNDLES = { - 'noises': 'worldgen/noise', 'densities': 'worldgen/density_function', 'rules': 'worldgen/material_rule', - 'conditions': 'worldgen/material_condition', 'settings': 'worldgen/noise_settings', 'carvers': 'worldgen/carver', - 'biomes': 'worldgen/biome', 'world_presets': 'worldgen/world_preset', 'features': 'worldgen/feature', - 'placed_features': 'worldgen/placed_feature', 'state_providers': 'worldgen/block_state_provider', - 'biome_tags': 'tags/worldgen/biome', 'feature_tags': 'tags/worldgen/feature', 'block_tags': 'tags/block', - 'fluid_tags': 'tags/fluid', 'processor_lists': 'worldgen/processor_list', - 'template_pools': 'worldgen/template_pool', 'structures': 'worldgen/structure', - 'structure_sets': 'worldgen/structure_set'} - - -def export_structure_blocks(target, jars, libraries): - """Run the vanilla exporter of per-state rotate/mirror results and template flags.""" - lock = json.loads((lab.ROOT/'research-lock.json').read_text()) - source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java' - export = lab.LOCAL/'horizon-client-structures' - classes = export/'classes' - classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (export/'export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, - '-d', str(classes), str(source)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaStructureBlockExporter', str(target)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - - -BLOCK_BEHAVIOR_FILES = ['block-properties.nbt', 'cached-collision.nbt', 'cached-support.nbt', 'survival-rules.json', - 'survival-extra-definitions.json', 'placement-definitions.json'] - - -def export_block_behavior(export, jars, libraries): - """Run the vanilla exporters of block properties, support, collision and survival definitions. - - Feature placement needs them: without these files the generator skips every placed feature - whose blocks are checked for survival or support (trees, flowers, grass, kelp, ...).""" - try: - from . import test_block_survival_parity as survival - except ImportError: - import test_block_survival_parity as survival - lock = json.loads((lab.ROOT/'research-lock.json').read_text()) - tests = lab.ROOT/'mods/horizon/src/test/java' - classes = export/'classes' - classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (export/'export.log').open('w') as log: - # The oracle's helper classes are compiled on demand from the source path. - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, - '-sourcepath', str(tests), '-d', str(classes), - str(tests/'dev/horizonlab/parity/VanillaSimpleBlockOracle.java')], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaSimpleBlockOracle', 'export', str(export)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - rules = survival.bind_definitions(*[json.loads((export/name).read_text()) for name in - ['survival-classes.json', 'survival-placement-classes.json', - 'survival-support-tags.json']]) - (export/'survival-rules.json').write_text(json.dumps(rules, separators=(',', ':'))) - - -def prepare_worldgen(root, jars, local, libraries=None): - """Write the chunk generator's resource bundle to root/worldgen (see GeneratorData::load).""" - out = root / 'worldgen' - out.mkdir(exist_ok=True) - # Structure templates: gzip NBT files under structure//.nbt. - with zipfile.ZipFile(jars['server']) as server: - prefix = 'data/minecraft/structure/' - for name in server.namelist(): - if name.startswith(prefix) and name.endswith('.nbt'): - relative = Path(name[len(prefix):]) - if relative.is_absolute() or '..' in relative.parts: - raise ValueError('Invalid structure path') - target = out/'structure'/'minecraft'/relative - data = server.read(name) - if not target.exists() or target.read_bytes() != data: - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(data) - with zipfile.ZipFile(jars['server']) as server, zipfile.ZipFile(jars['client']) as client: - for name, path in WORLDGEN_BUNDLES.items(): - prefix = f'data/minecraft/{path}/' - def extract(archive): - return {'minecraft:'+n[len(prefix):-5]: archive.read(n).decode('utf-8') - for n in sorted(archive.namelist()) if n.startswith(prefix) and n.endswith('.json')} - resources = extract(server) - if not resources or resources != extract(client): - raise ValueError('Reference worldgen resources disagree: '+path) - (out/(name+'.json')).write_text(json.dumps(resources, separators=(',', ':')), encoding='utf-8') - facts = json.loads((root/'facts.json').read_text()) - (out/'block_flags.json').write_text(json.dumps([[s[1], s[2]] for s in facts['states']], separators=(',', ':'))) - reports = out/'biome_parameters' - reports.mkdir(exist_ok=True) - presets = reports - for source in [root/'biome-parameters', local/'datagen/out/reports/biome_parameters/minecraft']: - if (source/'overworld.json').exists(): - for report in sorted(source.glob('*.json')): - (reports/report.name).write_bytes(report.read_bytes()) - break - else: - presets = None - # Block behavior used by feature placement checks (survival, support, collision). - # These come from the Java exporters of the simple-block parity run, or a direct export. - behavior = local/'rust-simple-block-parity' - blocks = out/'blocks' - names = BLOCK_BEHAVIOR_FILES - if libraries is not None and not all((behavior/name).exists() for name in names): - behavior = local/'horizon-client-block-behavior' - export_block_behavior(behavior, jars, libraries) - if all((behavior/name).exists() for name in names): - blocks.mkdir(exist_ok=True) - for name in names: - (blocks/name).write_bytes((behavior/name).read_bytes()) - if libraries is not None: - blocks.mkdir(exist_ok=True) - export_structure_blocks(blocks/'structure-blocks.json', jars, libraries) - else: - print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration') - if presets is None: - # Fall back to the Java-exported quantized tables from the material-stage parity run. - presets = local/'rust-material-stage-parity/presets.json' - if not presets.exists(): - raise FileNotFoundError('No multi-noise biome parameter tables; run the data generator reports') - (out/'presets.json').write_bytes(presets.read_bytes()) +ROOT = Path(__file__).resolve().parents[1] def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--prepare', action='store_true', - help='Import the pinned game files from your own copy first') - lab.add_game_arguments(parser) - args = parser.parse_args() - if args.prepare: - lab.prepare(args.minecraft_dir, args.server_jar) - lock, jars, libraries = base.verify_artifacts() - root = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] - root.mkdir(parents=True, exist_ok=True) - facts = root / 'facts.json' - manifest = root / 'horizon-resources.json' - oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java' - origin = {'minecraft': lock['minecraft']['version'], - 'client_sha256': lab.digest(jars['client'], 'sha256'), - 'server_sha256': lab.digest(jars['server'], 'sha256'), - 'exporter_sha256': lab.digest(oracle, 'sha256')} - previous = json.loads(manifest.read_text()) if manifest.exists() else {} - if not (all(previous.get(k) == v for k, v in origin.items()) and facts.exists() - and previous.get('facts_sha256') == lab.digest(facts, 'sha256')): - classes = root / 'classes' - classes.mkdir(exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (root / 'export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(oracle)], check=True, - stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaHeightmapOracle', 'export', str(facts)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - binding = oracle.with_name('VanillaBlockStateBindingOracle.java') - helper = oracle.with_name('VanillaCuboidModelOracle.java') - binding_sources = base.source_hashes([binding, helper]) - model_states = root / 'model-states.json' - if not (previous.get('model_state_exporters_sha256') == binding_sources - and previous.get('client_sha256') == origin['client_sha256'] - and model_states.exists() - and previous.get('model_states_sha256') == lab.digest(model_states, 'sha256')): - classes = root / 'client-classes'; classes.mkdir(exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) - with (root / 'model-state-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(binding), str(helper)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaBlockStateBindingOracle', 'export', str(model_states)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - tags = worldgen.tag_resources(jars['server']) - if tags != worldgen.tag_resources(jars['client']): - raise ValueError('Reference block tags disagree') - lab.write_json(root / 'block-tags.json', tags) - visibility = oracle.with_name('VanillaFaceVisibilityOracle.java') - collision = oracle.with_name('VanillaCollisionOracle.java') - collision_sources = base.source_hashes([collision]) - movement = oracle.with_name('VanillaMovementRegistryOracle.java') - attributes = oracle.with_name('VanillaEntityAttributeOracle.java') - landing = oracle.with_name('VanillaBlockLandingOracle.java') - motion_sources = base.source_hashes([movement, attributes, oracle, landing, collision]) - motion_files = ['movement-properties.nbt', 'attributes.json', 'landing-definitions.json'] - if not (previous.get('motion_exporters_sha256') == motion_sources - and previous.get('server_sha256') == origin['server_sha256'] - and previous.get('block_tags_sha256') == lab.digest(root/'block-tags.json', 'sha256') - and all((root/name).exists() and previous.get('motion_files_sha256', {}).get(name) - == lab.digest(root/name, 'sha256') for name in motion_files)): - export = lab.LOCAL/'horizon-client-motion'; export.mkdir(exist_ok=True) - lab.write_json(export/'tags.json', tags) - classes = export/'classes'; classes.mkdir(exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (export/'export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(movement), str(attributes), str(oracle), str(landing), str(collision)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - for name in ['VanillaBlockLandingOracle', 'VanillaEntityAttributeOracle']: - subprocess.run(['java', '-Xmx768M', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.'+name, 'export', str(export)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - (root/'movement-properties.nbt').write_bytes((export/'movement-properties.nbt').read_bytes()) - (root/'attributes.json').write_bytes((export/'catalog.json').read_bytes()) - (root/'landing-definitions.json').write_bytes((export/'landing-definitions.json').read_bytes()) - damage = oracle.with_name('VanillaDamageSourceOracle.java') - health = oracle.with_name('VanillaPlayerHealthOracle.java') - health_sources = base.source_hashes([damage, health, attributes]) - health_files = ['damage-types.json', 'damage-tags.json', 'damage-catalog.json', 'player-float-ids.json'] - if not (previous.get('health_exporters_sha256') == health_sources - and previous.get('server_sha256') == origin['server_sha256'] - and all((root/name).exists() and previous.get('health_files_sha256', {}).get(name) - == lab.digest(root/name, 'sha256') for name in health_files)): - export = lab.LOCAL/'horizon-client-health'; export.mkdir(exist_ok=True) - with zipfile.ZipFile(jars['server']) as archive, zipfile.ZipFile(jars['client']) as client_archive: - for file, prefix in [('types.json', 'data/minecraft/damage_type/'), ('tags.json', 'data/minecraft/tags/damage_type/')]: - def extract(source): - return {'minecraft:'+n[len(prefix):-5]: source.read(n).decode('utf-8') - for n in sorted(source.namelist()) if n.startswith(prefix) and n.endswith('.json')} - resources = extract(archive) - if resources != extract(client_archive): raise ValueError('Reference damage resources disagree') - lab.write_json(export/file, resources) - classes = export/'classes'; classes.mkdir(exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (export/'export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(damage), str(health), str(attributes)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - for name in ['VanillaPlayerHealthOracle', 'VanillaDamageSourceOracle']: - subprocess.run(['java', '-Xmx768M', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.'+name, 'export', str(export)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - for source, target in [('types.json','damage-types.json'), ('tags.json','damage-tags.json'), - ('catalog.json','damage-catalog.json'), ('ids.json','player-float-ids.json')]: - (root/target).write_bytes((export/source).read_bytes()) - collision_file = root / 'cached-collision.nbt' - if not (previous.get('collision_exporters_sha256') == collision_sources - and previous.get('server_sha256') == origin['server_sha256'] - and collision_file.exists() - and previous.get('collision_sha256') == lab.digest(collision_file, 'sha256')): - export = lab.LOCAL/'horizon-client-collision'; export.mkdir(exist_ok=True) - classes = export/'classes'; classes.mkdir(exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (export/'export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(collision)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx768M', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaCollisionOracle', 'generate', str(export)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - collision_file.write_bytes((export/'cached-collision.nbt').read_bytes()) - render_sources = base.source_hashes([visibility, collision, oracle]) - render_files = ['render-definitions.json', 'occlusion.nbt'] - tag_hash = lab.digest(root/'block-tags.json', 'sha256') - if not (previous.get('render_exporters_sha256') == render_sources - and previous.get('server_sha256') == origin['server_sha256'] - and previous.get('block_tags_sha256') == tag_hash - and all((root/name).exists() and previous.get('render_files_sha256', {}).get(name) - == lab.digest(root/name, 'sha256') for name in render_files)): - export = lab.LOCAL/'horizon-client-render'; export.mkdir(exist_ok=True) - lab.write_json(export/'tags.json', tags) - classes = export/'classes'; classes.mkdir(exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (export/'export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(visibility), str(collision), str(oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx768M', '-cp', str(classes)+os.pathsep+dependencies, - 'dev.horizonlab.parity.VanillaFaceVisibilityOracle', 'export', str(export)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - (root/'render-definitions.json').write_bytes((export/'definitions.json').read_bytes()) - (root/'occlusion.nbt').write_bytes((export/'occlusion.nbt').read_bytes()) - count = 0 - # The playable client needs every client asset (textures, models, fonts, GUI) - # and every data-pack resource (worldgen, recipes, loot tables, tags). - prefixes = ('assets/', 'data/') - with zipfile.ZipFile(jars['client']) as archive: - version = json.loads(archive.read('version.json')) - for name in archive.namelist(): - if not name.startswith(prefixes) or name.endswith('/'): - continue - relative = Path(name) - if relative.is_absolute() or '..' in relative.parts: - raise ValueError('Invalid resource path') - target = root / relative - data = archive.read(name) - if not target.exists() or target.read_bytes() != data: - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(data) - count += 1 - gameplay = root / 'gameplay-facts.json' - gameplay_oracle = oracle.with_name('VanillaGameplayFactsExporter.java') - gameplay_sources = base.source_hashes([gameplay_oracle]) - if not (previous.get('gameplay_exporters_sha256') == gameplay_sources and gameplay.exists() - and previous.get('server_sha256') == origin['server_sha256']): - classes = lab.LOCAL / 'gameplay-facts' / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (root / 'gameplay-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(gameplay_oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaGameplayFactsExporter', str(gameplay)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - # Entity dimensions, categories and default attributes for the client's mobs. - entity_types = root / 'entity-types.json' - entity_types_oracle = oracle.with_name('VanillaEntityTypesExporter.java') - entity_types_sources = base.source_hashes([entity_types_oracle]) - if not (previous.get('entity_types_exporters_sha256') == entity_types_sources and entity_types.exists() - and previous.get('server_sha256') == origin['server_sha256']): - classes = lab.LOCAL / 'entity-types' / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (root / 'entity-types-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(entity_types_oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaEntityTypesExporter', str(entity_types)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - # Block classes, instance configuration and per-state support/signal/fluid - # facts for horizon-world's level behaviour (level::Behaviours::load). - behaviours = root / 'block-behaviours.json' - behaviour_oracle = oracle.with_name('VanillaBlockBehaviourExporter.java') - behaviour_sources = base.source_hashes([behaviour_oracle]) - if not (previous.get('behaviour_exporters_sha256') == behaviour_sources and behaviours.exists() - and previous.get('server_sha256') == origin['server_sha256']): - classes = lab.LOCAL / 'block-behaviours' / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (root / 'behaviour-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(behaviour_oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaBlockBehaviourExporter', str(behaviours)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - items = root / 'items.json' - if not items.exists() or previous.get('server_sha256') != origin['server_sha256']: - # Vanilla's own data generator reports every item's default components. - datagen = lab.LOCAL / 'datagen'; datagen.mkdir(exist_ok=True) - with (datagen / 'datagen.log').open('w') as log: - subprocess.run(['java', '-DbundlerMainClass=net.minecraft.data.Main', '-jar', - str(jars['server'].with_name('server.jar')), '--reports', '--output', 'out'], - cwd=datagen, check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - reports = datagen / 'out' / 'reports' - components = {f'minecraft:{f.stem}': json.loads(f.read_text())['components'] - for f in sorted((reports / 'minecraft' / 'components' / 'item').glob('*.json'))} - items.write_text(json.dumps(components)) - (root / 'biome-parameters').mkdir(exist_ok=True) - for f in (reports / 'biome_parameters' / 'minecraft').glob('*.json'): - (root / 'biome-parameters' / f.name).write_bytes(f.read_bytes()) - # Biome parameter tables come from the data generator reports above. - prepare_worldgen(root, jars, lab.LOCAL, libraries) - entity_models = root / 'entity-models.json' - entity_oracle = oracle.with_name('VanillaEntityModelExporter.java') - entity_sources = base.source_hashes([entity_oracle]) - if not (previous.get('entity_model_exporters_sha256') == entity_sources and entity_models.exists() - and previous.get('client_sha256') == origin['client_sha256']): - classes = lab.LOCAL / 'entity-models' / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) - with (root / 'entity-model-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(entity_oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaEntityModelExporter', str(entity_models)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - # Mob AI and animation facts: per-state path types, spawn placements and the - # client's keyframe animation definitions (needs the client jar). - mob_data = root / 'mob-data.json' - mob_oracle = oracle.with_name('VanillaMobDataExporter.java') - mob_sources = base.source_hashes([mob_oracle]) - if not (previous.get('mob_data_exporters_sha256') == mob_sources and mob_data.exists() - and previous.get('client_sha256') == origin['client_sha256']): - classes = lab.LOCAL / 'mob-data' / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) - with (root / 'mob-data-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(mob_oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaMobDataExporter', str(mob_data), str(jars['client'])], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - # Vanilla's built-in registries for in-game command parsing (mob effects, - # data component types, dialogs, block entity and tag members). - command_registries = root / 'command-registries.json' - command_oracle = oracle.with_name('VanillaCommandParseOracle.java') - command_sources = base.source_hashes([command_oracle]) - if not (previous.get('command_registries_exporters_sha256') == command_sources and command_registries.exists() - and previous.get('server_sha256') == origin['server_sha256']): - export = lab.LOCAL / 'command-registries'; classes = export / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (root / 'command-registries-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(command_oracle)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaCommandParseOracle', 'registries', str(export)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - command_registries.write_bytes((export / 'registries.json').read_bytes()) - # The creative inventory (creative-inventory.json): every tab built by vanilla's - # CreativeModeTabs over the vanilla data pack's registries, with the search - # tab's tooltip lines and tags. - creative = root / 'creative-inventory.json' - creative_oracles = [oracle.with_name('VanillaCreativeTabsExporter.java'), oracle.with_name('ParityData.java')] - creative_sources = base.source_hashes(creative_oracles) - if not (previous.get('creative_exporters_sha256') == creative_sources and creative.exists() - and previous.get('server_sha256') == origin['server_sha256']): - classes = lab.LOCAL / 'creative-inventory' / 'classes'; classes.mkdir(parents=True, exist_ok=True) - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - with (root / 'creative-export.log').open('w') as log: - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), *map(str, creative_oracles)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaCreativeTabsExporter', str(creative)], - check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - lab.write_json(manifest, {'schema': 7, **origin, - 'health_exporters_sha256': health_sources, - 'health_files_sha256': {name: lab.digest(root/name, 'sha256') for name in health_files}, - 'motion_exporters_sha256': motion_sources, - 'motion_files_sha256': {name: lab.digest(root/name, 'sha256') for name in motion_files}, - 'collision_exporters_sha256': collision_sources, - 'collision_sha256': lab.digest(collision_file, 'sha256'), - 'render_exporters_sha256': render_sources, - 'render_files_sha256': {name: lab.digest(root/name, 'sha256') for name in render_files}, - 'model_state_exporters_sha256': binding_sources, - 'gameplay_exporters_sha256': gameplay_sources, - 'entity_model_exporters_sha256': entity_sources, - 'creative_exporters_sha256': creative_sources, - 'mob_data_exporters_sha256': mob_sources, - 'entity_types_exporters_sha256': entity_types_sources, - 'behaviour_exporters_sha256': behaviour_sources, - 'command_registries_exporters_sha256': command_sources, - 'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'], - 'facts_sha256': lab.digest(facts, 'sha256'), - 'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count}) - print(f'Prepared Horizon native-client resources: {root}') + arguments = ['--root', str(ROOT), *sys.argv[1:]] + beside = ROOT / ('horizon-prepare.exe' if os.name == 'nt' else 'horizon-prepare') + if beside.is_file(): + command = [str(beside), *arguments] + else: + command = ['cargo', 'run', '--quiet', '--release', '-p', 'horizon-prepare', '--', *arguments] + return subprocess.call(command, cwd=ROOT) if __name__ == '__main__': - main() + sys.exit(main()) diff --git a/tools/rea_vanilla.py b/tools/rea_vanilla.py index 9a2723716..96555c5ed 100644 --- a/tools/rea_vanilla.py +++ b/tools/rea_vanilla.py @@ -45,7 +45,7 @@ def target(game_dir, name): """REA admits JADX targets by their .apk name; JADX reads the class files either way.""" source = game_dir / "jars" / f"{name}.jar" if not source.exists(): - raise SystemExit(f"{source} is missing; run python3 tools/prepare_native_client.py --prepare") + raise SystemExit(f"{source} is missing; run cargo run --release -p horizon-prepare -- --prepare") copy = lab.LOCAL / "rea" / f"{name}-{lab.digest(source, 'sha256')[:16]}.apk" if not copy.exists(): copy.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/test_creative_parity.py b/tools/test_creative_parity.py index 6c6d21c75..aa23cbbc9 100644 --- a/tools/test_creative_parity.py +++ b/tools/test_creative_parity.py @@ -2,7 +2,7 @@ """Compare the creative inventory's tabs and search with the vanilla client's. The Java oracle (VanillaCreativeSearchOracle) writes the creative-inventory.json -that tools/prepare_native_client.py exports (VanillaCreativeTabsExporter: every +that horizon-prepare exports (VanillaCreativeTabsExporter: every tab built by vanilla's CreativeModeTabs over the vanilla data pack's registries), then what the vanilla client shows: every tab's display items and, for each search query, CreativeModeInventoryScreen.refreshSearchResults' From 63bb9bc37c4bebcee93c3c55f3f51af6646f4350 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:19:13 +0200 Subject: [PATCH 06/11] compare_prepare.py: a tar of the Python tree for machines without the repository; launcher formatting Co-Authored-By: Claude Opus 5.5 --- launcher/src/backend.rs | 5 +++-- launcher/src/mcp.rs | 6 +++++- tools/compare_prepare.py | 15 +++++++++++---- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 4934c4819..ac6fe3a4d 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -418,8 +418,9 @@ fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) -> if !preparer.iter().all(|p| same_or_absent(p)) { return false; } - let mut sources = - vec!["mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java".to_string()]; + let mut sources = vec![ + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java".to_string(), + ]; for (_, value) in fields .iter() .filter(|(key, _)| key.ends_with("_exporters_sha256")) diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index c590d066d..8573e2f62 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -110,7 +110,11 @@ impl Session { lines.pop_front(); } }); - let tail = lines.into_inner().into_iter().collect::>().join("\n"); + let tail = lines + .into_inner() + .into_iter() + .collect::>() + .join("\n"); (result, tail) } }; diff --git a/tools/compare_prepare.py b/tools/compare_prepare.py index 58216af00..7b53bc704 100644 --- a/tools/compare_prepare.py +++ b/tools/compare_prepare.py @@ -35,10 +35,14 @@ PYTHON_REF = '66ce394d2d6dc19ed5f5c53a97b650741af9be76' IGNORED_PARTS = {'classes', 'client-classes', 'logs', '.cache'} -def tree(ref, destination): +def tree(ref, destination, archive=None): + """The preparer's inputs at `ref`: research-lock.json, the exporters and the Python preparer.""" destination.mkdir(parents=True) - archive = subprocess.run(['git', '-C', str(ROOT), 'archive', ref, 'tools', 'mods/horizon/src/test/java', - 'research-lock.json'], check=True, capture_output=True).stdout + if archive is None: + archive = subprocess.run(['git', '-C', str(ROOT), 'archive', ref, 'tools', 'mods/horizon/src/test/java', + 'research-lock.json'], check=True, capture_output=True).stdout + else: + archive = archive.read_bytes() subprocess.run(['tar', '-x', '-C', str(destination)], input=archive, check=True) @@ -66,6 +70,9 @@ def main(): parser.add_argument('--server-jar', type=Path, required=True) parser.add_argument('--minecraft-dir', type=Path, required=True) parser.add_argument('--python-ref', default=PYTHON_REF) + parser.add_argument('--python-tree', type=Path, + help='a tar of that tree instead of git (git archive REF tools mods/horizon/src/test/java ' + 'research-lock.json), for a machine without the repository') parser.add_argument('--binary', type=Path, help='horizon-prepare to test (default: cargo build --release)') parser.add_argument('--work', type=Path, default=ROOT / '.local/compare-prepare') parser.add_argument('--keep', action='store_true', help='keep the prepared folders') @@ -87,7 +94,7 @@ def main(): folders = {name: work / name for name in ['python-1', 'python-2', 'rust']} times = {} for name, folder in folders.items(): - tree(args.python_ref, folder) + tree(args.python_ref, folder, args.python_tree) command = [str(binary), '--root', str(folder), *game] if name == 'rust' else python times[name] = run(name, command, folder, work / f'{name}.log') first, second, rust = (hashes(folders[n]) for n in ['python-1', 'python-2', 'rust']) From 158e0c634674f8f3da57e4bf7971a0f28acd9e0b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:33:02 +0200 Subject: [PATCH 07/11] Launcher: a self-update after the binary was replaced says it updated, and Restart re-runs it On Linux, once the launcher's file has been replaced under the running process (an update from the command line or another window), current_exe() is " (deleted)" and self_replace failed with "No such file or directory". The new binary now goes to the path the launcher started from (copy beside it, rename over it; Windows still uses self_replace), and an update the file already has is not downloaded again. The message reads "Updated to X. Restart the launcher to use it."; Restart execs the new binary with the same arguments (spawn and exit on Windows) and says so if it cannot start. Co-Authored-By: Claude Opus 5.5 --- launcher/src/backend.rs | 163 ++++++++++++++++++++++++++++++++++++---- launcher/src/cli.rs | 2 +- launcher/src/main.rs | 21 ++++-- 3 files changed, 163 insertions(+), 23 deletions(-) diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 4013d7ca0..acd6e619b 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -945,13 +945,74 @@ pub fn self_update_allowed() -> bool { !cfg!(debug_assertions) && std::env::var_os("HORIZON_LAUNCHER_NO_SELF_UPDATE").is_none() } +/// The version in `horizon-launcher --version`'s output (`horizon-launcher 0.1.5`). +fn parse_version_output(out: &str) -> Option<&str> { + out.trim() + .strip_prefix("horizon-launcher ") + .map(str::trim) + .filter(|v| !v.is_empty()) +} + +/// The version of the launcher binary now at `path`, which is not this process's once another +/// update (the command line, another window) has replaced the file. +fn installed_launcher_version(path: &Path) -> Option { + let mut cmd = Command::new(path); + cmd.arg("--version") + .stdin(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let out = cmd.output().ok()?; + parse_version_output(&String::from_utf8_lossy(&out.stdout)).map(String::from) +} + +/// Puts `new` at `exe`, the path this launcher started from. The running process keeps its +/// file (unlinked) and works on. Unix only: `self_replace` asks the system where the running +/// binary is, and Linux answers " (deleted)" once the file has been replaced, so a second +/// update in the same run failed with "No such file or directory". Windows keeps a running +/// binary locked, so there `self_replace` moves it aside first. +#[cfg(unix)] +fn replace_binary(new: &Path, exe: &Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let dir = exe.parent().ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::NotFound, "the launcher has no folder") + })?; + let name = exe.file_name().unwrap_or_default().to_string_lossy(); + let temp = dir.join(format!(".{name}.update-{}", std::process::id())); + let mode = fs::metadata(exe).map_or(0o755, |m| m.permissions().mode() | 0o111); + let result = fs::copy(new, &temp) + .and_then(|_| fs::set_permissions(&temp, fs::Permissions::from_mode(mode))) + .and_then(|_| fs::rename(&temp, exe)); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result +} + +#[cfg(not(unix))] +fn replace_binary(new: &Path, _exe: &Path) -> std::io::Result<()> { + self_replace::self_replace(new) +} + /// Downloads a launcher release and puts its binary in place of this one. The running process -/// keeps working; `restart` starts the new one. +/// keeps working; `restart` starts the new one. When the file there already is that release or +/// a newer one (updated from the command line or another window), there is nothing to do. pub fn self_update(release: &Release, progress: impl Fn(f32)) -> Result<(), String> { let (url, size) = release .asset .clone() .ok_or("This launcher release has no build for this platform.")?; + let target = launcher_version(&release.tag).unwrap_or("0"); + if installed_launcher_version(exe_path()) + .is_some_and(|v| v != VERSION && compare_versions(&v, target).is_ge()) + { + progress(1.0); + return Ok(()); + } let work = data_dir().join(".launcher-update"); let _ = fs::remove_dir_all(&work); fs::create_dir_all(&work).map_err(|e| e.to_string())?; @@ -961,13 +1022,12 @@ pub fn self_update(release: &Release, progress: impl Fn(f32)) -> Result<(), Stri unpack(&archive, &url, &unpacked)?; let binary = find_file(&unpacked, LAUNCHER_BINARY).ok_or("The download has no launcher binary.")?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)); - } - self_replace::self_replace(&binary) - .map_err(|e| format!("Could not replace the launcher: {e}"))?; + replace_binary(&binary, exe_path()).map_err(|e| { + format!( + "Could not replace the launcher at {}: {e}", + exe_path().display() + ) + })?; let _ = fs::remove_dir_all(&work); progress(1.0); Ok(()) @@ -987,12 +1047,26 @@ fn find_file(dir: &Path, name: &str) -> Option { None } -/// Starts the launcher again (the updated binary) with the same arguments, and exits. -pub fn restart() -> ! { - let _ = Command::new(exe_path()) - .args(std::env::args_os().skip(1)) - .spawn(); - std::process::exit(0) +/// Starts the launcher again (the updated binary) with the same arguments in place of this one: +/// on Unix the process becomes the new binary (exec), on Windows the new one starts and this one +/// exits. Returns only when the new binary could not start. +pub fn restart() -> String { + let mut cmd = Command::new(exe_path()); + cmd.args(std::env::args_os().skip(1)); + #[cfg(unix)] + let error = { + use std::os::unix::process::CommandExt; + cmd.exec() + }; + #[cfg(not(unix))] + let error = match cmd.spawn() { + Ok(_) => std::process::exit(0), + Err(e) => e, + }; + format!( + "Could not start {}: {error}. Close the launcher and open it again.", + exe_path().display() + ) } /// Plain text from markdown, for terminals: headings on their own lines, bullets as "- ", @@ -1433,6 +1507,67 @@ mod tests { let _ = fs::remove_dir_all(&versions); } + #[test] + fn launcher_versions_read_from_the_binary() { + assert_eq!( + parse_version_output("horizon-launcher 0.1.5\n"), + Some("0.1.5") + ); + assert_eq!(parse_version_output("something else"), None); + assert_eq!(parse_version_output(""), None); + // This test binary is not a launcher: no version, so an update goes ahead. + assert_eq!( + installed_launcher_version(&std::env::current_exe().unwrap()), + None + ); + assert_eq!( + installed_launcher_version(Path::new("/nonexistent/horizon-launcher")), + None + ); + } + + /// The launcher's file was replaced while it ran (an update from the command line, or an + /// earlier one): the next replacement still lands at the path it started from. + #[cfg(unix)] + #[test] + fn a_replaced_binary_is_replaced_again_at_its_path() { + use std::os::unix::fs::PermissionsExt; + let dir = + std::env::temp_dir().join(format!("horizon-launcher-replace-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let exe = dir.join("horizon-launcher"); + fs::write(&exe, "old").unwrap(); + // Another update swaps the file under the running launcher. + fs::write(dir.join("other"), "other update").unwrap(); + fs::rename(dir.join("other"), &exe).unwrap(); + fs::write(dir.join("new"), "new").unwrap(); + replace_binary(&dir.join("new"), &exe).unwrap(); + assert_eq!(fs::read_to_string(&exe).unwrap(), "new"); + // The file there keeps its mode, made executable (the swapped-in one was 0644). + assert_eq!( + fs::metadata(&exe).unwrap().permissions().mode() & 0o777, + 0o755 + ); + // Gone altogether: it is put back, executable. + fs::remove_file(&exe).unwrap(); + replace_binary(&dir.join("new"), &exe).unwrap(); + assert_eq!(fs::read_to_string(&exe).unwrap(), "new"); + assert_eq!( + fs::metadata(&exe).unwrap().permissions().mode() & 0o777, + 0o755 + ); + // No temporary file is left beside it. + let mut names: Vec = fs::read_dir(&dir) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert_eq!(names, ["horizon-launcher", "new"]); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn plain_notes() { let text = markdown_to_text( diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index df78436aa..db48b4095 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -301,7 +301,7 @@ fn update(check: bool, as_json: bool) -> Result<(), String> { println!("Launcher: {version} is available; this build does not replace itself."); } else { backend::self_update(r, progress(format!("Updating the launcher to {version}")))?; - println!("Launcher: updated to {version}; the next start uses it."); + println!("Launcher: updated to {version}. Restart the launcher to use it."); } } } diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 7dbac7b5a..f5959e635 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -882,7 +882,7 @@ impl Launcher { .flex() .flex_col() .gap(px(2.)) - .child(div().child(format!("Launcher {} โ†’ {version}", backend::VERSION))) + .child(div().child(format!("Launcher updated to {version}"))) .child( div() .id("restart") @@ -890,8 +890,11 @@ impl Launcher { .font_weight(FontWeight::MEDIUM) .cursor_pointer() .hover(|s| s.opacity(0.8)) - .child("Restart to update") - .on_click(|_, _, _| backend::restart()), + .child("Restart the launcher") + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.self_update = SelfUpdate::Failed(backend::restart()); + cx.notify(); + })), ), _ => div().child(format!("Launcher {}", backend::VERSION)), }; @@ -1513,9 +1516,7 @@ impl Launcher { SelfUpdate::Downloading(v, p) => { format!("{} ยท downloading {v}, {:.0}%", backend::VERSION, p * 100.) } - SelfUpdate::Ready(v) => { - format!("{} ยท {v} is ready, restart to use it", backend::VERSION) - } + SelfUpdate::Ready(v) => format!("Updated to {v}. Restart the launcher to use it."), SelfUpdate::Failed(e) => format!("{} ยท the update failed: {e}", backend::VERSION), SelfUpdate::Idle => match &self.updates.launcher { Some(r) => format!( @@ -1531,8 +1532,12 @@ impl Launcher { }; let launcher_action = match &self.self_update { SelfUpdate::Ready(_) => Some( - button("restart-settings", "Restart", Kind::Secondary, &t) - .on_click(|_, _, _| backend::restart()), + button("restart-settings", "Restart", Kind::Secondary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.self_update = SelfUpdate::Failed(backend::restart()); + cx.notify(); + }, + )), ), SelfUpdate::Downloading(..) => None, _ => Some( From 70583cbf2a92c9cb9f4af16567d9657c1b4ed060 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:38:38 +0200 Subject: [PATCH 08/11] Particle emitters: waxing, scraping, sparks, eating, snowballs, eggs, slimes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The new particle types now come from the events that spawn them in vanilla. - Level events 3003 (wax on), 3004 (wax off), 3005 (scrape): ParticleUtils.spawnParticlesOnBlockFaces, three to five particles on each face, from the client level's random. They are sent by honeycomb on a block (HoneycombItem.useOn), axe scraping and wax removal (BlockTransformer's TransformParticle.send), dispensed honeycomb, and copper golems being waxed or scraped. - Level event 3002: a struck lightning rod sends sparks along its axis (ParticleUtils.spawnParticlesAlongAxis); without an axis they cover the block's faces. - Eating: LivingEntity.spawnItemParticles, five crumbs every four ticks and sixteen when consumed (Consumable.onConsume), placed in front of the eyes and thrown along the look, as item particles in full colour. They were greyed terrain crumbs above the eyes. They now follow Consumable.shouldEmitParticlesAndSounds with the remaining ticks before the countdown, as LivingEntity does: six times over 32 ticks, not seven, each one a tick earlier. - Snowballs (Snowball.handleEntityEvent(3)): eight item crumbs at rest. Eggs (ThrownEgg): eight scattered by up to 0.04 a tick. - Slime, magma cube and sulfur cube landings (AbstractCubeMob.tick): size ร— 16 item_slime, flame or sulfur_cube_goo particles around the body, from draws the mob's random also makes on the server. New harness tools/test_emitter_particles_parity.py: the real ParticleUtils emitters and LivingEntity.spawnItemParticles. Part of #63 Co-Authored-By: Claude Opus 5.5 --- .../examples/emitter_particles_probe.rs | 74 ++++++++++++ crates/horizon-client/src/game.rs | 64 +++++------ .../horizon-client/src/game/copper_golems.rs | 7 ++ crates/horizon-client/src/game/creatures.rs | 34 +++--- .../horizon-client/src/game/item_particles.rs | 24 +++- .../src/game/level_particles.rs | 44 +++++++ crates/horizon-client/src/game/lightning.rs | 7 ++ crates/horizon-client/src/mobs/cube.rs | 30 ++++- crates/horizon-client/src/particles.rs | 108 ++++++++++++++++++ .../parity/VanillaEmitterParticlesOracle.java | 82 +++++++++++++ tools/test_emitter_particles_parity.py | 53 +++++++++ 11 files changed, 476 insertions(+), 51 deletions(-) create mode 100644 crates/horizon-client/examples/emitter_particles_probe.rs create mode 100644 crates/horizon-client/src/game/level_particles.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEmitterParticlesOracle.java create mode 100644 tools/test_emitter_particles_parity.py diff --git a/crates/horizon-client/examples/emitter_particles_probe.rs b/crates/horizon-client/examples/emitter_particles_probe.rs new file mode 100644 index 000000000..7469bb368 --- /dev/null +++ b/crates/horizon-client/examples/emitter_particles_probe.rs @@ -0,0 +1,74 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_emitter_particles_parity.py's emitters through +//! `particles::on_block_faces`, `particles::along_axis` and +//! `particles::item_use_particles`. +use horizon_client::{Result, particles}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn d(v: f64) -> String { + format!("{:016x}", v.to_bits()) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let mut random = LegacyRandom::new(c["seed"].as_i64().ok_or("seed")?); + let mut lines = Vec::new(); + let record = |kind: &str| { + let kind = kind.to_owned(); + move |p: [f64; 3], v: [f64; 3]| { + format!( + "+ {kind} {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(v[0]), + d(v[1]), + d(v[2]) + ) + } + }; + if c["kind"] == "item_use" { + let p: [f64; 3] = std::array::from_fn(|i| c["pos"][i].as_f64().unwrap_or(0.0)); + let f = |k: &str| c[k].as_f64().unwrap_or(0.0) as f32; + let line = record("item"); + particles::item_use_particles( + &mut random, + f("pitch"), + f("yaw"), + p, + p[1] + f64::from(f("eye")), + c["count"].as_u64().unwrap_or(0) as u32, + |p, v| lines.push(line(p, v)), + ); + } else { + let p: [i32; 3] = std::array::from_fn(|i| c["pos"][i].as_i64().unwrap_or(0) as i32); + match c["axis"].as_i64() { + Some(axis @ 0..=2) => { + let line = record("electric_spark"); + particles::along_axis(&mut random, axis as usize, p, |p, v| { + lines.push(line(p, v)) + }); + } + _ => { + let line = record("wax_on"); + particles::on_block_faces(&mut random, p, |p, v| lines.push(line(p, v))); + } + } + } + for l in lines { + writeln!(out, "{l}")?; + } + writeln!(out, "next {}", random.next_long())?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d6b027c57..536baf191 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -52,6 +52,7 @@ mod lan_actions; mod lan_screen; mod lan_trading; mod leads; +mod level_particles; mod lightning; mod llamas; mod loom; @@ -1578,6 +1579,11 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + LevelEvent::LevelEvent { + id: id @ 3002..=3005, + pos, + data, + } => self.block_particle_event(id, pos, data), LevelEvent::LevelEvent { id: 1500, pos, @@ -2326,11 +2332,13 @@ impl Game<'_> { return; } let duration = 32; - let ticks = ticks + 1; + // Consumable.shouldEmitParticlesAndSounds(useItemRemainingTicks), with + // the remaining ticks before this tick counts down: every 4 ticks once + // more than 21.875% of the time has passed (none on the last tick). let remaining = duration - ticks.min(duration); + let ticks = ticks + 1; let eye = self.eye_position().unwrap_or_default(); - // Consumable.shouldEmitParticlesAndSounds: every 4 ticks in the last 25. - if remaining <= 25 && remaining % 4 == 0 { + if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 { let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; self.audio.play( @@ -2339,38 +2347,12 @@ impl Game<'_> { 0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32, pitch, ); - // `ItemParticleOption`: the particle material of a random layer of - // the stack resolved for the ground (`BreakingItemParticle`). - let state = self.resolve_item( - &stack, - horizon_assets::item_model::DisplayContext::Ground, - None, - 0, - ); - if let Some(sprite) = state.pick_particle(&mut self.world.random) { - let (yaw, pitch) = ( - f64::from(self.yaw).to_radians(), - f64::from(self.pitch).to_radians(), - ); - let at = [ - eye[0] - yaw.sin() * pitch.cos() * 0.3, - eye[1] - 0.1, - eye[2] + yaw.cos() * pitch.cos() * 0.3, - ]; - for _ in 0..5 { - let v = [ - (f64::from(self.world.random.next_float()) - 0.5) * 0.1, - 0.1, - (f64::from(self.world.random.next_float()) - 0.5) * 0.1, - ]; - let p = - Particle::terrain(&mut self.world.random, at, v, sprite.clone(), 0xFFFFFF); - self.particles.push(p); - } - } + self.eat_particles(&stack, 5); } if ticks >= duration { self.using = None; + // Consumable.onConsume: emitParticlesAndSounds(..., 16). + self.eat_particles(&stack, 16); // Consumable.onConsume. self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player); if let Some((nutrition, saturation)) = info.food @@ -6293,7 +6275,7 @@ impl Game<'_> { _ => "east", }; let registry = self.res.assets.registry; - let (state, sound, loot, damage) = { + let (state, sound, loot, damage, particle) = { let around = Column { world: &self.world, registry, @@ -6306,12 +6288,25 @@ impl Game<'_> { else { return Ok(false); }; - (state, t.sound.clone(), t.loot.clone(), t.damage) + ( + state, + t.sound.clone(), + t.loot.clone(), + t.damage, + t.particle.clone(), + ) }; let Ok(new) = registry.resolve(&state) else { return Ok(false); }; self.level_set(pos, new)?; + // BlockTransformer.TransformParticle.send. + match particle.as_str() { + "scrape" => self.level_event_at(3005, pos, 0), + "wax_on" => self.level_event_at(3003, pos, 0), + "wax_off" => self.level_event_at(3004, pos, 0), + _ => {} + } if loot.as_deref() == Some("minecraft:till/rooted_dirt") { self.pop_resource( [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]], @@ -6494,6 +6489,7 @@ impl Game<'_> { && let Ok(state) = registry.resolve(&waxed) { self.level_set(hit.pos, state)?; + self.level_event_at(3003, hit.pos, 0); self.audio.play( "minecraft:item.honeycomb.wax_on", Some(at(hit.pos)), diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 59cc3c8b7..7cb6f946a 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -256,8 +256,13 @@ impl Game<'_> { self.damage_held_tool(); return true; } + let block = { + let p = self.mobs[index].position; + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] + }; if name == "minecraft:honeycomb" && !waxed { self.mobs[index].extra.vector[0] = -2.0; + self.level_event_at(3003, block, 0); self.audio .play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0); self.consume_held(); @@ -267,6 +272,7 @@ impl Game<'_> { self.mobs[index].extra.vector[0] = -1.0; self.audio .play("minecraft:item.axe.scrape", Some(at), 1.0, 1.0); + self.level_event_at(3004, block, 0); self.damage_held_tool(); return true; } @@ -276,6 +282,7 @@ impl Game<'_> { m.extra.variant = horizon_client::mobs::copper_golem::weather_previous(m.extra.variant); self.audio .play("minecraft:item.axe.scrape", Some(at), 1.0, 1.0); + self.level_event_at(3005, block, 0); self.damage_held_tool(); return true; } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 7aff7847f..2a8b4bf55 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -888,6 +888,9 @@ impl Game<'_> { MobEvent::Particles { kind, at, count } => { // Mob particle bursts (hearts, smoke, splashes) around a point. if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { + if kind.starts_with("item_") { + self.ensure_item_particle_sprites(); + } let options = horizon_client::particles::ParticleOptions::simple(ty); // Count 0: one particle exactly there, at rest. if count == 0 { @@ -1750,23 +1753,24 @@ impl Game<'_> { } Ok(()) } - /// Item break particles (snowballs, eggs). + /// `Snowball`/`ThrownEgg.handleEntityEvent(3)`: eight crumbs of the + /// thrown item where it broke, at rest for a snowball, scattered by the + /// client entity's random (the particle engine's here) for an egg. fn item_burst(&mut self, at: [f64; 3], item: &str) { - let sprite = format!("item/{}", item.trim_start_matches("minecraft:")); + let options = self.item_particle(&horizon_client::items::ItemStack::new(item, 1)); + let egg = item != "minecraft:snowball"; for _ in 0..8 { - let v = [ - (self.world.random.next_double() - 0.5) * 0.08, - self.world.random.next_double() * 0.1, - (self.world.random.next_double() - 0.5) * 0.08, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - at, - v, - sprite.clone(), - 0xFFFFFF, - ); - self.particles.push(p); + let v = if egg { + let r = self.particles.random(); + [ + (f64::from(r.next_float()) - 0.5) * 0.08, + (f64::from(r.next_float()) - 0.5) * 0.08, + (f64::from(r.next_float()) - 0.5) * 0.08, + ] + } else { + [0.0; 3] + }; + self.particles.add(&options, at, v); } } /// Right click on a mob (Mob.interact / mobInteract). Returns true when consumed. diff --git a/crates/horizon-client/src/game/item_particles.rs b/crates/horizon-client/src/game/item_particles.rs index a60fca68a..2122ae8e1 100644 --- a/crates/horizon-client/src/game/item_particles.rs +++ b/crates/horizon-client/src/game/item_particles.rs @@ -4,7 +4,7 @@ use super::Game; use horizon_assets::item_model::DisplayContext; use horizon_client::{ items::ItemStack, - particles::{ParticleOptions, ParticleType}, + particles::{self, ParticleOptions, ParticleType}, }; impl Game<'_> { @@ -14,6 +14,28 @@ impl Game<'_> { let state = self.resolve_item(stack, DisplayContext::Ground, None, 0); ParticleOptions::item(state.layers.iter().map(|l| l.particle.clone()).collect()) } + /// `LivingEntity.spawnItemParticles(stack, count)` for the local player, + /// drawing from the world random as its eating sounds do. + pub(super) fn eat_particles(&mut self, stack: &ItemStack, count: u32) { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let eye_y = self.eye_position().map_or(p.y, |e| e[1]); + let options = self.item_particle(stack); + let mut spawned = Vec::new(); + particles::item_use_particles( + &mut self.world.random, + self.pitch, + self.yaw, + [p.x, p.y, p.z], + eye_y, + count, + |p, v| spawned.push((p, v)), + ); + for (p, v) in spawned { + self.particles.add(&options, p, v); + } + } /// The slime ball, snowball and cobweb models behind `item_slime`, /// `item_snowball` and `item_cobweb`, resolved on first use. pub(super) fn ensure_item_particle_sprites(&mut self) { diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs new file mode 100644 index 000000000..678020712 --- /dev/null +++ b/crates/horizon-client/src/game/level_particles.rs @@ -0,0 +1,44 @@ +//! Level events whose client handler (`LevelEventHandler`) spawns particles +//! on a block: electric sparks (3002), waxing (3003), wax off (3004) and +//! scraping (3005). +use super::Game; +use horizon_client::particles::{self, ParticleOptions, ParticleType}; +use horizon_core::position::BlockPos; +use horizon_world::level::LevelEvent; + +impl Game<'_> { + /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client + /// level's random. + pub(super) fn block_particle_event(&mut self, id: i32, pos: BlockPos, data: i32) { + let ty = match id { + 3002 => ParticleType::ElectricSpark, + 3003 => ParticleType::WaxOn, + 3004 => ParticleType::WaxOff, + 3005 => ParticleType::Scrape, + _ => return, + }; + let p = [pos.x, pos.y, pos.z]; + let mut spawned = Vec::new(); + let random = self.particles.level_random(); + // 3002 with an axis: a lightning rod; otherwise copper cleaned by lightning. + match usize::try_from(data) { + Ok(axis) if id == 3002 && axis < 3 => { + particles::along_axis(random, axis, p, |p, v| spawned.push((p, v))); + } + _ => particles::on_block_faces(random, p, |p, v| spawned.push((p, v))), + } + let options = ParticleOptions::simple(ty); + for (p, v) in spawned { + self.particles.add(&options, p, v); + } + } + /// 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 { + id, + pos: BlockPos::new(pos[0], pos[1], pos[2]), + data, + }); + let _ = self.process_level_events(); + } +} diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index f85bebd28..8aa06ff4a 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -246,6 +246,13 @@ impl Game<'_> { // The rod's onPlace schedules the 8-tick unpowering. let _ = self.level_set(p, powered); } + // Level event 3002 with the rod's axis: sparks along it. + let axis = match s.properties.get("facing").map(String::as_str) { + Some("east" | "west") => 0, + Some("north" | "south") => 2, + _ => 1, + }; + self.level_event_at(3002, p, axis); } } /// `thunderHit` for entities within 3 blocks (up to 9 above). diff --git a/crates/horizon-client/src/mobs/cube.rs b/crates/horizon-client/src/mobs/cube.rs index bf65f5edc..3986ffb93 100644 --- a/crates/horizon-client/src/mobs/cube.rs +++ b/crates/horizon-client/src/mobs/cube.rs @@ -7,7 +7,10 @@ use super::{ control::{MoveKind, Operation, rotlerp}, goals::{Cx, Goal, JUMP, LOOK, MOVE, NearestTarget, Prey, goal_clone, reduced}, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{ + geometry::{Vec3, trig}, + random::RandomSource, +}; // AnimState slots. const SQUISH: usize = 0; @@ -144,6 +147,31 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { v[SQUISH] += (v[TARGET_SQUISH] - v[SQUISH]) * 0.5; let was = m.extra.flag2; if m.on_ground && !was { + // The landing splash: drawn on the server too, where it spawns nothing. + let size = m.width() * 2.0; + let radius = size / 2.0; + let kind = match m.species() { + Species::MagmaCube => "flame", + Species::SulfurCube => "sulfur_cube_goo", + _ => "item_slime", + }; + let mut i = 0; + while (i as f32) < size * 16.0 { + let dir = m.random.next_float() * std::f64::consts::TAU as f32; + let d = m.random.next_float() * 0.5 + 0.5; + let xd = trig::sin(f64::from(dir)) * radius * d; + let zd = trig::cos(f64::from(dir)) * radius * d; + events.push(MobEvent::Particles { + kind, + at: [ + m.position.x + f64::from(xd), + m.position.y, + m.position.z + f64::from(zd), + ], + count: 0, + }); + i += 1; + } let squish = match (m.species(), tiny(m)) { (Species::SulfurCube, _) => super::sulfur_cube::squish_sound(m), (Species::MagmaCube, true) => "entity.magma_cube.squish_small", diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 34d0957de..0c7c63c0d 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -554,6 +554,110 @@ pub fn destroy_positions( } } +/// `LivingEntity.spawnItemParticles(stack, count)` (eating, drinking, an item +/// breaking): `count` crumbs in front of the eyes, thrown up and forwards, +/// both turned by the pitch and yaw in degrees. +pub fn item_use_particles( + random: &mut impl RandomSource, + pitch: f32, + yaw: f32, + position: [f64; 3], + eye_y: f64, + count: u32, + mut emit: impl FnMut([f64; 3], [f64; 3]), +) { + let (x_rot, y_rot) = (-pitch * trig::DEG_TO_RAD, -yaw * trig::DEG_TO_RAD); + for _ in 0..count { + let d = Vec3::new( + (f64::from(random.next_float()) - 0.5) * 0.1, + f64::from(random.next_float()) * 0.1 + 0.1, + 0.0, + ) + .rotate_x(x_rot) + .rotate_y(y_rot); + let y = f64::from(-random.next_float()) * 0.6 - 0.3; + let p = Vec3::new((f64::from(random.next_float()) - 0.5) * 0.3, y, 0.6) + .rotate_x(x_rot) + .rotate_y(y_rot); + emit( + [p.x + position[0], p.y + eye_y, p.z + position[2]], + [d.x, d.y + 0.05, d.z], + ); + } +} + +/// `Mth.nextDouble(random, min, max)`. +fn next_double_between(random: &mut impl RandomSource, min: f64, max: f64) -> f64 { + if min >= max { + min + } else { + random.next_double() * (max - min) + min + } +} +/// `ParticleUtils.spawnParticlesOnBlockFaces(level, pos, particle, UniformInt.of(3, 5))` +/// (level events 3002 without an axis, 3003 wax on, 3004 wax off, 3005 scrape): +/// three to five particles on each face, in `Direction.values()` order, moving +/// along the face at up to half a block a tick. +pub fn on_block_faces( + random: &mut impl RandomSource, + pos: [i32; 3], + mut emit: impl FnMut([f64; 3], [f64; 3]), +) { + const FACES: [[i32; 3]; 6] = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ]; + for face in FACES { + let count = random.next_int_bound(5 - 3 + 1).unwrap_or(0) + 3; + for _ in 0..count { + // getRandomSpeedRanges, then spawnParticleOnFace with step factor 0.55. + let speed: [f64; 3] = std::array::from_fn(|_| next_double_between(random, -0.5, 0.5)); + let mut p = [0.0; 3]; + let mut v = [0.0; 3]; + for i in 0..3 { + let center = f64::from(pos[i]) + 0.5; + if face[i] == 0 { + p[i] = center + next_double_between(random, -0.5, 0.5); + v[i] = speed[i]; + } else { + p[i] = center + f64::from(face[i]) * 0.55; + } + } + emit(p, v); + } + } +} +/// `ParticleUtils.spawnParticlesAlongAxis(axis, level, pos, 0.125, particle, +/// UniformInt.of(10, 19))` (level event 3002 on a lightning rod): sparks along +/// the rod, moving along it. `axis` is 0, 1, 2 for X, Y, Z. +pub fn along_axis( + random: &mut impl RandomSource, + axis: usize, + pos: [i32; 3], + mut emit: impl FnMut([f64; 3], [f64; 3]), +) { + let count = random.next_int_bound(19 - 10 + 1).unwrap_or(0) + 10; + for _ in 0..count { + let p: [f64; 3] = std::array::from_fn(|i| { + f64::from(pos[i]) + + 0.5 + + next_double_between(random, -1.0, 1.0) * if i == axis { 0.5 } else { 0.125 } + }); + let v: [f64; 3] = std::array::from_fn(|i| { + if i == axis { + next_double_between(random, -1.0, 1.0) + } else { + 0.0 + } + }); + emit(p, v); + } +} + impl Particle { /// `Particle(level, x, y, z)` + `SingleQuadParticle` (no initial velocity). fn at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self { @@ -1033,6 +1137,10 @@ impl ParticleEngine { pub fn random(&mut self) -> &mut LegacyRandom { &mut self.random } + /// `ClientLevel.random` as client effects use it (`LevelEventHandler`). + pub fn level_random(&mut self) -> &mut LegacyRandom { + &mut self.level_random + } /// `ClientLevel.addParticle`: dropped beyond 32 blocks of the camera unless /// the type overrides the limiter. pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEmitterParticlesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEmitterParticlesOracle.java new file mode 100644 index 000000000..47c7cde16 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEmitterParticlesOracle.java @@ -0,0 +1,82 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.Bootstrap; +import net.minecraft.util.ParticleUtils; +import net.minecraft.util.RandomSource; +import net.minecraft.util.valueproviders.UniformInt; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.animal.cow.Cow; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + +/** Runs the real particle emitters of level events 3002 to 3005 (ParticleUtils + * spawnParticlesOnBlockFaces and spawnParticlesAlongAxis, as LevelEventHandler + * calls them) and LivingEntity.spawnItemParticles (eating, drinking, breaking) + * against a stand-in level that records what they spawn. */ +public final class VanillaEmitterParticlesOracle { + static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); } + static Field field(Class type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f; + } + static final class Level0 extends ClientLevel { + List events; + Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + @Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) { + events.add("+ " + BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()).getPath() + " " + d(x) + " " + d(y) + " " + d(z) + + " " + d(xd) + " " + d(yd) + " " + d(zd)); + } + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); ParityData.init(); + var u = Class.forName("sun.misc.Unsafe"); var unsafe = field(u, "theUnsafe").get(null); + var allocate = u.getMethod("allocateInstance", Class.class); + var level = (Level0) allocate.invoke(unsafe, Level0.class); level.events = new ArrayList<>(); + Field levelRandom = field(Level.class, "random"); + Field levelField = field(Entity.class, "level"), position = field(Entity.class, "position"), random = field(Entity.class, "random"), + xRot = field(Entity.class, "xRot"), yRot = field(Entity.class, "yRot"), eyeHeight = field(Entity.class, "eyeHeight"); + try (var output = Files.newBufferedWriter(Path.of(args[1]))) { + int n = 0; + for (String line : Files.readAllLines(Path.of(args[0]))) { + var c = JsonParser.parseString(line).getAsJsonObject(); + output.write("== " + n++); output.newLine(); + level.events.clear(); + var r = RandomSource.create(c.get("seed").getAsLong()); + var p = c.getAsJsonArray("pos"); + var kind = c.get("kind").getAsString(); + if (kind.equals("item_use")) { + var entity = (Cow) allocate.invoke(unsafe, Cow.class); + levelField.set(entity, level); + position.set(entity, new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble())); + random.set(entity, r); + xRot.setFloat(entity, c.get("pitch").getAsFloat()); + yRot.setFloat(entity, c.get("yaw").getAsFloat()); + eyeHeight.setFloat(entity, c.get("eye").getAsFloat()); + var item = BuiltInRegistries.ITEM.getValue(Identifier.parse(c.get("item").getAsString())); + entity.spawnItemParticles(new ItemStack(item), c.get("count").getAsInt()); + } else { + levelRandom.set(level, r); + var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt()); + int axis = c.get("axis").getAsInt(); + if (axis >= 0) ParticleUtils.spawnParticlesAlongAxis(Direction.Axis.VALUES[axis], level, pos, 0.125, ParticleTypes.ELECTRIC_SPARK, UniformInt.of(10, 19)); + else ParticleUtils.spawnParticlesOnBlockFaces(level, pos, ParticleTypes.WAX_ON, UniformInt.of(3, 5)); + } + for (var e : level.events) { output.write(e); output.newLine(); } + output.write("next " + r.nextLong()); output.newLine(); + } + } + } +} diff --git a/tools/test_emitter_particles_parity.py b/tools/test_emitter_particles_parity.py new file mode 100644 index 000000000..50de9d642 --- /dev/null +++ b/tools/test_emitter_particles_parity.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Compare particle emitters with the real vanilla ones: ParticleUtils +spawnParticlesOnBlockFaces and spawnParticlesAlongAxis as LevelEventHandler +calls them for level events 3002 (electric sparks), 3003 (wax on), 3004 (wax +off) and 3005 (scrape), and LivingEntity.spawnItemParticles (eating, drinking): +particle, count, positions, motion and every random draw.""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def cases(rng): + for _ in range(600): + pos = [rng.randrange(-30000, 30000), rng.randrange(-64, 320), rng.randrange(-30000, 30000)] + yield dict(kind='block', pos=pos, axis=rng.choice([-1, -1, 0, 1, 2]), seed=rng.randrange(-2**63, 2**63)) + angles = [0.0, 90.0, -90.0, 45.0, -45.0, 180.0, -180.0, 12.5, 359.75, -721.5] + for _ in range(900): + # Dyadic values: serde_json's decimal parsing may round others a unit off. + pos = [rng.randrange(-2**20, 2**20) / 64 for _ in range(3)] + yield dict(kind='item_use', pos=pos, pitch=rng.choice(angles + [rng.randrange(-5760, 5760) / 64]), + yaw=rng.choice(angles + [rng.randrange(-23040, 23040) / 64]), + eye=rng.choice([1.62, 1.27, 0.4, 1.74]), count=rng.choice([5, 16, 1, 0]), + item=rng.choice(['minecraft:apple', 'minecraft:cooked_beef', 'minecraft:potion', 'minecraft:honey_bottle']), + seed=rng.randrange(-2**63, 2**63)) + + +def make_cases(build): + path = build / 'cases.jsonl' + count = 0 + with path.open('w') as out: + for case in cases(random.Random(0x454d4954)): + out.write(json.dumps(case, separators=(',', ':')) + '\n') + count += 1 + return path, count + + +def main(): + scope = ('The real ParticleUtils.spawnParticlesOnBlockFaces (UniformInt 3..5 per face) and spawnParticlesAlongAxis ' + '(radius 0.125, UniformInt 10..19) on a stand-in level with a seeded random, as LevelEventHandler runs ' + 'them for level events 3002-3005, and the real LivingEntity.spawnItemParticles on an entity given a ' + 'position, rotation, eye height and seeded random. Which code sends those events, and the particles ' + 'once spawned, are covered elsewhere.') + harness.differential( + 'rust-emitter-particles-parity', 'VanillaEmitterParticlesOracle', 'emitter_particles_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/particles.rs']) + + +if __name__ == '__main__': + main() From 832a8e3f46e2ceb56b0842cf5614d5d5f8232315 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:55:15 +0200 Subject: [PATCH 09/11] Keep the compositor's fullscreen, and copy/paste in every text field Fullscreen: applying settings (any option button, joining a world, travelling, reloading packs) compared the Fullscreen option with what the window reported and forced the window back to the option. A window made fullscreen by the compositor (a Hyprland keybind or window rule) left fullscreen on the next button click. The window now follows blaze3d Window's fullscreenRequested/fullscreen pair: it is only asked to change when the option changes (updateFullscreenIfChanged), a change the window system makes is adopted by the option (updateFullscreenState -> Minecraft.fullscreenStateChanged), and the window is created fullscreen when options.txt says so. Clipboard: Ctrl+A/C/V/X (Cmd on macOS) in the chat, signs, book and quill (page and title), anvil, creative and recipe-book searches, the language and pack searches, the LAN port, world name and seed, and the server name and address boxes, through the arboard clipboard (Wayland data-control, falling back to X11). Shortcuts follow InputWithModifiers.isCopy/isPaste/ isCut/isSelectAll on the modifier state and the layout's letter; pasted text goes through each field's own vanilla rules: StringUtil.filterText and setMaxLength for EditBox, line breaks kept and the 1024-character and 14-line limits for MultiLineEditBox, formatting stripped and whole-or- nothing width checks for TextFieldHelper on signs. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/chat.rs | 12 + crates/horizon-client/src/clipboard.rs | 455 ++++++++++++++++++ crates/horizon-client/src/game.rs | 82 ++-- crates/horizon-client/src/game/books.rs | 82 +++- crates/horizon-client/src/game/chat.rs | 11 + crates/horizon-client/src/game/clipboard.rs | 106 ++++ crates/horizon-client/src/game/control.rs | 2 +- crates/horizon-client/src/game/debug_keys.rs | 12 +- crates/horizon-client/src/game/lan_screen.rs | 5 + crates/horizon-client/src/game/options.rs | 32 +- crates/horizon-client/src/game/recipe_book.rs | 10 + crates/horizon-client/src/game/remote.rs | 19 +- crates/horizon-client/src/game/sign_edit.rs | 64 ++- crates/horizon-client/src/game/stations.rs | 32 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/multiplayer.rs | 10 + crates/horizon-client/src/options_ui.rs | 25 + crates/horizon-client/src/pack_screen.rs | 15 + crates/horizon-client/src/screen_draw.rs | 34 ++ crates/horizon-client/src/title.rs | 14 + crates/horizon-client/src/ui.rs | 30 +- crates/horizon-client/src/window.rs | 78 ++- 22 files changed, 1063 insertions(+), 68 deletions(-) create mode 100644 crates/horizon-client/src/clipboard.rs create mode 100644 crates/horizon-client/src/game/clipboard.rs diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index fe31c4e01..2a5dc53e0 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -432,6 +432,18 @@ impl ChatScreen { self.allow_suggestions = true; self.update_command_info(m, c); } + /// Ctrl+A/C/V/X in the input box. + pub fn shortcut( + &mut self, + m: &Measure, + c: &Commands, + shortcut: crate::clipboard::EditShortcut, + clipboard: &mut dyn crate::clipboard::Clipboard, + ) { + if self.input.shortcut(m, shortcut, clipboard) { + self.edited(m, c); + } + } /// Typed text (`charTyped` per character). pub fn type_text(&mut self, m: &Measure, c: &Commands, text: &str) { for ch in text.chars() { diff --git a/crates/horizon-client/src/clipboard.rs b/crates/horizon-client/src/clipboard.rs new file mode 100644 index 000000000..2f3d7b002 --- /dev/null +++ b/crates/horizon-client/src/clipboard.rs @@ -0,0 +1,455 @@ +//! The system clipboard and the text-editing shortcuts of 26.3: +//! `KeyboardHandler.getClipboard`/`setClipboard`, `InputWithModifiers.isSelectAll`, +//! `isCopy`, `isPaste` and `isCut`, `StringUtil.filterText` and +//! `ChatFormatting.stripFormatting`. + +use winit::keyboard::{Key, KeyCode, PhysicalKey}; + +/// A text-editing shortcut (`InputWithModifiers.isSelectAll`, `isCopy`, +/// `isPaste`, `isCut`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EditShortcut { + SelectAll, + Copy, + Paste, + Cut, +} + +/// The letter a key stands for in shortcuts (`KeyEvent.shortcutKey`, SDL's +/// keycode): the layout's letter, or the key's US-layout letter when the +/// layout's is not a Latin one (SDL's default `latin_letters` keycode option). +pub fn shortcut_letter(logical: &Key, physical: PhysicalKey) -> Option { + if let Key::Character(s) = logical { + let mut chars = s.chars(); + if let (Some(c), None) = (chars.next(), chars.next()) + && c.is_ascii_alphabetic() + { + return Some(c.to_ascii_lowercase()); + } + } + let PhysicalKey::Code(code) = physical else { + return None; + }; + Some(match code { + KeyCode::KeyA => 'a', + KeyCode::KeyC => 'c', + KeyCode::KeyV => 'v', + KeyCode::KeyX => 'x', + _ => return None, + }) +} + +/// `InputWithModifiers.isSelectAll`/`isCopy`/`isPaste`/`isCut`: A, C, V or X +/// with the edit modifier (`InputQuirks.EDIT_SHORTCUT_KEY_MODIFIER`: Cmd on +/// macOS, Ctrl elsewhere) and neither Shift nor Alt. +pub fn edit_shortcut( + letter: Option, + edit_modifier: bool, + shift: bool, + alt: bool, +) -> Option { + if !edit_modifier || shift || alt { + return None; + } + Some(match letter? { + 'a' => EditShortcut::SelectAll, + 'c' => EditShortcut::Copy, + 'v' => EditShortcut::Paste, + 'x' => EditShortcut::Cut, + _ => return None, + }) +} + +/// `StringUtil.isAllowedChatCharacter`. +pub fn is_allowed_chat_character(c: char) -> bool { + c != 'ยง' && c >= ' ' && c != '\u{7f}' +} + +/// `StringUtil.filterText`: the allowed characters, and line breaks where +/// the field takes several lines. +pub fn filter_text(input: &str, multiline: bool) -> String { + input + .chars() + .filter(|&c| is_allowed_chat_character(c) || (multiline && c == '\n')) + .collect() +} + +/// `ChatFormatting.stripFormatting`: `ยง` followed by a format code removed. +pub fn strip_formatting(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + let mut chars = input.chars().peekable(); + while let Some(c) = chars.next() { + if c == 'ยง' + && chars.peek().is_some_and( + |n| matches!(n.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r'), + ) + { + chars.next(); + continue; + } + out.push(c); + } + out +} + +/// `TextFieldHelper.getClipboardContents`: formatting and carriage returns +/// removed (signs). +pub fn helper_clipboard_contents(clipboard: &str) -> String { + strip_formatting(&clipboard.replace('\r', "")) +} + +/// A clipboard: the system's, or an in-memory one in tests. +pub trait Clipboard { + /// `KeyboardHandler.getClipboard`: empty when there is no text. + fn get(&mut self) -> String; + /// `KeyboardHandler.setClipboard`: empty text is not copied. + fn set(&mut self, text: &str); +} + +/// The system clipboard (`ClipboardManager`). On Wayland, arboard uses the +/// data-control protocol and falls back to X11 (XWayland) on compositors +/// without it. When no system clipboard can be reached, text copied in the +/// game can still be pasted in the game. +#[derive(Default)] +pub struct SystemClipboard { + system: Option, + /// The text Horizon last copied (`horizon-ctl status`). + copied: Option, +} + +impl SystemClipboard { + /// The text last copied by the game. + pub fn copied(&self) -> Option<&str> { + self.copied.as_deref() + } + fn system(&mut self) -> Option<&mut arboard::Clipboard> { + if self.system.is_none() { + self.system = arboard::Clipboard::new().ok(); + } + self.system.as_mut() + } +} + +impl Clipboard for SystemClipboard { + fn get(&mut self) -> String { + let Some(system) = self.system() else { + return self.copied.clone().unwrap_or_default(); + }; + match system.get_text() { + Ok(text) => text, + Err(arboard::Error::ContentNotAvailable) => String::new(), + Err(_) => { + // A lost connection (a restarted compositor): reconnect next time. + self.system = None; + String::new() + } + } + } + fn set(&mut self, text: &str) { + if text.is_empty() { + return; + } + self.copied = Some(text.to_owned()); + if let Some(system) = self.system() + && system.set_text(text.to_owned()).is_err() + { + self.system = None; + } + } +} + +/// A clipboard in memory. +#[derive(Default, Debug)] +pub struct MemoryClipboard(pub String); + +impl Clipboard for MemoryClipboard { + fn get(&mut self) -> String { + self.0.clone() + } + fn set(&mut self, text: &str) { + if !text.is_empty() { + self.0 = text.to_owned(); + } + } +} + +/// A text field with a cursor and a selection (`EditBox`). +pub trait Editable { + /// Select All: the cursor at the end, the selection from the start. + fn select_all(&mut self); + /// `getHighlighted`. + fn selected_text(&self) -> String; + /// `insertText`, with the field's own filter and length limit. True when + /// the value changed. + fn insert(&mut self, text: &str) -> bool; +} + +/// `EditBox.keyPressed`'s shortcuts. True when the value changed. +pub fn apply( + field: &mut dyn Editable, + shortcut: EditShortcut, + clipboard: &mut dyn Clipboard, +) -> bool { + match shortcut { + EditShortcut::SelectAll => { + field.select_all(); + false + } + EditShortcut::Copy => { + clipboard.set(&field.selected_text()); + false + } + EditShortcut::Paste => field.insert(&clipboard.get()), + EditShortcut::Cut => { + clipboard.set(&field.selected_text()); + field.insert("") + } + } +} + +/// Which append-only field a Select All covers: a name and an index (a +/// sign line, a book page). +pub type FieldId = (&'static str, usize); + +/// The selection of Horizon's append-only fields, whose cursor stays at the +/// end: Select All selects the whole value, which the next copy, cut, paste, +/// typed text or backspace replaces. It is forgotten as soon as the field or +/// its value changes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AppendSelection(Option<(FieldId, String)>); + +impl AppendSelection { + /// Whether `value` of field `id` is wholly selected. + pub fn covers(&self, id: FieldId, value: &str) -> bool { + self.0.as_ref().is_some_and(|(i, v)| *i == id && v == value) + } + /// Before typing or a backspace: an all-selected value is cleared (true). + pub fn take(&mut self, id: FieldId, value: &mut String) -> bool { + let covered = self.covers(id, value); + self.0 = None; + if covered { + value.clear(); + } + covered + } + /// A shortcut in an append-only field. `insert` adds pasted text to a + /// value the field's own way and says whether it accepted it (a field + /// that rejects it keeps its value, as `TextFieldHelper.insertText`). + /// True when the value changed. + pub fn apply( + &mut self, + id: FieldId, + value: &mut String, + shortcut: EditShortcut, + clipboard: &mut dyn Clipboard, + insert: impl FnOnce(&mut String, &str) -> bool, + ) -> bool { + let covered = self.covers(id, value); + match shortcut { + EditShortcut::SelectAll => { + self.0 = Some((id, value.clone())); + false + } + EditShortcut::Copy => { + if covered { + clipboard.set(value); + } + false + } + EditShortcut::Cut => { + self.0 = None; + if !covered { + return false; + } + clipboard.set(value); + let changed = !value.is_empty(); + value.clear(); + changed + } + EditShortcut::Paste => { + self.0 = None; + let text = clipboard.get(); + let mut next = if covered { + String::new() + } else { + value.clone() + }; + if !insert(&mut next, &text) || next == *value { + return false; + } + *value = next; + true + } + } + } +} + +/// `EditBox.insertText` for a field without a cursor: the filtered text, +/// cut to the room left by `max_chars`. +pub fn append_limited(value: &mut String, text: &str, max_chars: usize) -> bool { + let room = max_chars.saturating_sub(value.chars().count()); + if room == 0 { + return false; + } + value.extend(filter_text(text, false).chars().take(room)); + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shortcuts_need_the_edit_modifier_alone() { + let c = Some('c'); + assert_eq!( + edit_shortcut(c, true, false, false), + Some(EditShortcut::Copy) + ); + assert_eq!( + edit_shortcut(Some('v'), true, false, false), + Some(EditShortcut::Paste) + ); + assert_eq!( + edit_shortcut(Some('x'), true, false, false), + Some(EditShortcut::Cut) + ); + assert_eq!( + edit_shortcut(Some('a'), true, false, false), + Some(EditShortcut::SelectAll) + ); + assert_eq!(edit_shortcut(c, false, false, false), None); + assert_eq!(edit_shortcut(c, true, true, false), None); + assert_eq!(edit_shortcut(c, true, false, true), None); + assert_eq!(edit_shortcut(Some('b'), true, false, false), None); + } + + #[test] + fn the_layout_letter_decides_and_non_latin_layouts_use_the_position() { + let q = PhysicalKey::Code(KeyCode::KeyQ); + // AZERTY: the key at Q's position types an A. + assert_eq!(shortcut_letter(&Key::Character("a".into()), q), Some('a')); + // Russian: the key at C's position types ั. + let c = PhysicalKey::Code(KeyCode::KeyC); + assert_eq!(shortcut_letter(&Key::Character("ั".into()), c), Some('c')); + assert_eq!(shortcut_letter(&Key::Character("C".into()), q), Some('c')); + } + + #[test] + fn filter_text_keeps_line_breaks_only_for_multiline_fields() { + let s = "a\u{7}bยงc\nd\re\u{80}"; + assert_eq!(filter_text(s, false), "abcde\u{80}"); + assert_eq!(filter_text(s, true), "abc\nde\u{80}"); + assert_eq!(strip_formatting("ยงaRedยงr ยงzxยง"), "Red ยงzxยง"); + assert_eq!(helper_clipboard_contents("ยงlone\r\ntwo"), "one\ntwo"); + } + + struct Field { + value: String, + cursor: usize, + highlight: usize, + } + impl Editable for Field { + fn select_all(&mut self) { + self.cursor = self.value.len(); + self.highlight = 0; + } + fn selected_text(&self) -> String { + let (a, b) = ( + self.cursor.min(self.highlight), + self.cursor.max(self.highlight), + ); + self.value[a..b].to_owned() + } + fn insert(&mut self, text: &str) -> bool { + let (a, b) = ( + self.cursor.min(self.highlight), + self.cursor.max(self.highlight), + ); + self.value.replace_range(a..b, text); + self.cursor = a + text.len(); + self.highlight = self.cursor; + true + } + } + + #[test] + fn edit_box_shortcuts() { + let mut clip = MemoryClipboard("old".into()); + let mut f = Field { + value: "hello".into(), + cursor: 5, + highlight: 5, + }; + // Nothing selected: copying leaves the clipboard alone (setClipboard skips ""). + apply(&mut f, EditShortcut::Copy, &mut clip); + assert_eq!(clip.0, "old"); + apply(&mut f, EditShortcut::SelectAll, &mut clip); + apply(&mut f, EditShortcut::Copy, &mut clip); + assert_eq!(clip.0, "hello"); + assert!(apply(&mut f, EditShortcut::Cut, &mut clip)); + assert_eq!(f.value, ""); + assert!(apply(&mut f, EditShortcut::Paste, &mut clip)); + assert!(apply(&mut f, EditShortcut::Paste, &mut clip)); + assert_eq!(f.value, "hellohello"); + } + + #[test] + fn append_only_fields_select_everything_or_nothing() { + let id = ("search", 0); + let mut clip = MemoryClipboard("stone".into()); + let mut sel = AppendSelection::default(); + let mut value = String::from("dirt"); + let insert = |v: &mut String, t: &str| append_limited(v, t, 6); + // Without Select All, copy and cut do nothing and paste appends. + sel.apply(id, &mut value, EditShortcut::Copy, &mut clip, insert); + assert_eq!(clip.0, "stone"); + assert!(!sel.apply(id, &mut value, EditShortcut::Cut, &mut clip, insert)); + assert!(sel.apply(id, &mut value, EditShortcut::Paste, &mut clip, insert)); + assert_eq!(value, "dirtst"); + // Select All then paste replaces the value. + sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert); + assert!(sel.apply(id, &mut value, EditShortcut::Paste, &mut clip, insert)); + assert_eq!(value, "stone"); + // Select All then cut empties it and copies it. + sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert); + clip.0 = "x".into(); + assert!(sel.apply(id, &mut value, EditShortcut::Cut, &mut clip, insert)); + assert_eq!((value.as_str(), clip.0.as_str()), ("", "stone")); + // A selection is forgotten once the value changes or another field is used. + value = "ab".into(); + sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert); + assert!(!sel.covers(("other", 0), &value)); + value.push('c'); + assert!(!sel.take(id, &mut value)); + assert_eq!(value, "abc"); + sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert); + assert!(sel.take(id, &mut value)); + assert_eq!(value, ""); + } + + #[test] + fn a_rejected_paste_keeps_the_selected_value() { + // TextFieldHelper.insertText: a line too wide is not set at all. + let id = ("sign", 1); + let mut clip = MemoryClipboard("far too long".into()); + let mut sel = AppendSelection::default(); + let mut value = String::from("ok"); + sel.apply( + id, + &mut value, + EditShortcut::SelectAll, + &mut clip, + |_, _| true, + ); + let fits = |v: &mut String, t: &str| { + let next = format!("{v}{t}"); + next.len() <= 5 && { + *v = next; + true + } + }; + assert!(!sel.apply(id, &mut value, EditShortcut::Paste, &mut clip, fits)); + assert_eq!(value, "ok"); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f0dff5c4d..d2926747a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -16,6 +16,7 @@ mod bossbars; mod breezes; mod cartography; mod chat; +mod clipboard; mod combat; mod command_harness; mod commands; @@ -626,6 +627,10 @@ struct Game<'a> { cursor: (f32, f32), captured: bool, focused: bool, + /// The keyboard's modifier state (`KeyEvent.modifiers`). + modifiers: winit::keyboard::ModifiersState, + /// The window's fullscreen request and reported state. + fullscreen: horizon_client::window::FullscreenState, /// MouseHandler's accumulated look and wheel state. mouse: MouseLook, /// `Options.smoothCamera` (cinematic camera), not persisted. @@ -841,9 +846,10 @@ struct Game<'a> { pause_menu: bool, /// MultiPlayerGameMode.previousLocalPlayerMode (F3+N goes back to it). previous_mode: Option, - clipboard: Option, - /// The text last put on the clipboard (reported by `horizon-ctl status`). - copied: Option, + /// The system clipboard (`KeyboardHandler.clipboardManager`). + clipboard: horizon_client::clipboard::SystemClipboard, + /// Select All in the append-only text fields. + text_selection: horizon_client::clipboard::AppendSelection, /// The world was saved for the application ending (`save_for_exit`). saved_for_exit: bool, /// The block a guest is acting on (game/lan_actions.rs). @@ -8046,10 +8052,14 @@ impl ApplicationHandler for Game<'_> { if self.window.is_some() { return; } + // The Window constructor: created fullscreen when options.txt says so. + let fullscreen = self.settings.fullscreen; + self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen); let window = match event_loop.create_window( Window::default_attributes() .with_title("Horizon") - .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0)), + .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0)) + .with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))), ) { Ok(w) => Arc::new(w), Err(e) => { @@ -8085,6 +8095,9 @@ impl ApplicationHandler for Game<'_> { if let WindowEvent::Focused(false) = &event { self.physical_keys.clear(); } + if let WindowEvent::ModifiersChanged(m) = &event { + self.modifiers = m.state(); + } // KeyboardHandler.keyPress: the debug keys come before the game's. if let WindowEvent::KeyboardInput { event: key_event, .. @@ -8130,6 +8143,7 @@ impl ApplicationHandler for Game<'_> { if let Some(r) = &mut self.renderer { r.resize(size.width, size.height); } + self.observe_fullscreen(); } WindowEvent::Focused(focused) => { self.focused = focused; @@ -8367,19 +8381,12 @@ impl ApplicationHandler for Game<'_> { && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => { - match event.physical_key { - PhysicalKey::Code(KeyCode::Backspace) => { - self.creative_screen.search.pop(); - } - _ => { - if let Some(text) = &event.text { - self.creative_screen - .search - .extend(text.chars().filter(|c| !c.is_control())); - } - } + if let Some(shortcut) = self.edit_shortcut(&event) { + self.creative_search_shortcut(shortcut); + } else { + let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); + self.creative_search_edit(event.text.as_deref(), backspace); } - self.creative_screen.scroll = 0.0; } WindowEvent::KeyboardInput { event, .. } if self.recipe_search_focused() @@ -8395,8 +8402,12 @@ impl ApplicationHandler for Game<'_> { && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => { // The anvil rename box takes every key but Escape (AnvilScreen.keyPressed). - let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); - self.station_text(event.text.as_deref(), backspace); + if let Some(shortcut) = self.edit_shortcut(&event) { + self.station_shortcut(shortcut); + } else { + let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); + self.station_text(event.text.as_deref(), backspace); + } } WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => { self.remote_chat_key(&event) @@ -8405,6 +8416,11 @@ impl ApplicationHandler for Game<'_> { self.world_options_key(&event) } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => { + if let Some(shortcut) = self.edit_shortcut(&event) + && self.options_shortcut(shortcut) + { + return Ok(()); + } if event.state == ElementState::Pressed && let PhysicalKey::Code(key) = event.physical_key { @@ -8413,18 +8429,25 @@ impl ApplicationHandler for Game<'_> { } WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => { if event.state == ElementState::Pressed - && let Some(title) = self.title.as_mut() - && !title.skip_opening() + && self.title.as_ref().is_some_and(|t| !t.skip_opening()) { + if let Some(shortcut) = self.edit_shortcut(&event) { + self.title_shortcut(shortcut); + return Ok(()); + } match event.physical_key { - PhysicalKey::Code(KeyCode::Backspace) => title.backspace(), - PhysicalKey::Code(KeyCode::Tab) => title.tab(), - PhysicalKey::Code(KeyCode::Escape) => title.escape(), - _ => { - if let Some(text) = &event.text { - title.type_text(text); + PhysicalKey::Code(KeyCode::Backspace) => self.title_edit(None, true), + PhysicalKey::Code(KeyCode::Tab) => { + if let Some(t) = self.title.as_mut() { + t.tab(); } } + PhysicalKey::Code(KeyCode::Escape) => { + if let Some(t) = self.title.as_mut() { + t.escape(); + } + } + _ => self.title_edit(event.text.as_deref(), false), } } } @@ -8484,6 +8507,7 @@ impl ApplicationHandler for Game<'_> { self.key_pressed(key)?; } WindowEvent::RedrawRequested => { + self.observe_fullscreen(); let now = Instant::now(); let elapsed = now.duration_since(self.previous); self.frame_ticks = elapsed.as_secs_f32() * 20.0; @@ -8870,6 +8894,8 @@ pub fn run() -> Result<()> { cursor: (0.0, 0.0), captured: false, focused: true, + modifiers: winit::keyboard::ModifiersState::empty(), + fullscreen: horizon_client::window::FullscreenState::new(false), mouse: MouseLook::default(), smooth_camera: false, toggles: Default::default(), @@ -9027,8 +9053,8 @@ pub fn run() -> Result<()> { show_chunk_borders: false, pause_menu: true, previous_mode: None, - clipboard: None, - copied: None, + clipboard: Default::default(), + text_selection: Default::default(), saved_for_exit: false, forced_hit: None, lan_events: Vec::new(), diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index f275da402..b276b9a88 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -24,6 +24,8 @@ const BLACK: u32 = 0xFF00_0000; const PAGE_CHARS: usize = 1024; const MAX_PAGES: usize = 100; const LINES: usize = 14; +/// `BookSignScreen`'s title box. +const BOOK_TITLE: horizon_client::clipboard::FieldId = ("book.title", 0); pub(super) enum BookScreen { Edit { @@ -128,6 +130,10 @@ impl Game<'_> { if event.state != ElementState::Pressed { return; } + if let Some(shortcut) = self.edit_shortcut(event) { + self.book_shortcut(shortcut); + return; + } let key = match event.physical_key { PhysicalKey::Code(k) => Some(k), _ => None, @@ -150,7 +156,9 @@ impl Game<'_> { } } Some(KeyCode::Backspace) => { - title.pop(); + if !self.text_selection.take(BOOK_TITLE, title) { + title.pop(); + } } Some(KeyCode::Enter | KeyCode::NumpadEnter) => { if !title.trim().is_empty() { @@ -159,6 +167,7 @@ impl Game<'_> { } _ => { if let Some(typed) = event.text.as_ref() { + self.text_selection.take(BOOK_TITLE, title); for c in typed.chars().filter(|c| !c.is_control()) { if title.chars().count() < 15 { title.push(c); @@ -171,13 +180,23 @@ impl Game<'_> { Some(KeyCode::Escape) => self.save_book(false), Some(KeyCode::PageUp) => self.turn_page(false), Some(KeyCode::PageDown) => self.turn_page(true), - Some(KeyCode::Backspace) => self.edit_page(|p| { - p.pop(); - }), - Some(KeyCode::Enter | KeyCode::NumpadEnter) => self.type_into_page("\n"), + Some(KeyCode::Backspace) => { + if !self.take_page_selection() { + self.edit_page(|p| { + p.pop(); + }) + } + } + Some(KeyCode::Enter | KeyCode::NumpadEnter) => { + self.take_page_selection(); + self.type_into_page("\n") + } _ => { if let Some(typed) = event.text.as_ref().map(|t| t.to_string()) { let typed: String = typed.chars().filter(|c| !c.is_control()).collect(); + if !typed.is_empty() { + self.take_page_selection(); + } self.type_into_page(&typed); } } @@ -204,6 +223,59 @@ impl Game<'_> { _ => {} } } + /// Before typing on a page: Select All's selection is cleared (true). + fn take_page_selection(&mut self) -> bool { + match self.book.as_mut() { + Some(BookScreen::Edit { pages, page, .. }) => self + .text_selection + .take(("book.page", *page), &mut pages[*page]), + _ => false, + } + } + /// Ctrl+A/C/V/X: the title box (an `EditBox` of 15) while signing, else + /// the page (`MultilineTextField.insertText`: line breaks kept, cut to + /// the 1024 characters left, rejected when it overflows the 14 lines). + fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + let font = &self.res.atlas.font; + match self.book.as_mut() { + Some(BookScreen::Edit { + signing: true, + title, + .. + }) => { + Self::append_shortcut( + &mut self.text_selection, + &mut self.clipboard, + BOOK_TITLE, + title, + shortcut, + 15, + ); + } + Some(BookScreen::Edit { pages, page, .. }) => { + // truncateInsertionText counts the whole value, selection included. + let room = PAGE_CHARS.saturating_sub(pages[*page].chars().count()); + self.text_selection.apply( + ("book.page", *page), + &mut pages[*page], + shortcut, + &mut self.clipboard, + |value, pasted| { + let text: String = horizon_client::clipboard::filter_text(pasted, true) + .chars() + .take(room) + .collect(); + let next = format!("{value}{text}"); + font.split(&Text::literal(&next), 114.0).len() <= LINES && { + *value = next; + true + } + }, + ); + } + _ => {} + } + } fn edit_page(&mut self, f: impl FnOnce(&mut String)) { if let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_mut() { f(&mut pages[*page]); diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 0e063abc2..720f56c66 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -418,6 +418,17 @@ impl Game<'_> { } /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { + if let Some(shortcut) = self.edit_shortcut(event) { + let m = Measure(&self.res.atlas.font); + let c = Commands { + dispatcher: vanilla::game_dispatcher(), + registries: &self.ui.registries, + }; + if let Some(screen) = self.ui.chat_screen.as_mut() { + screen.shortcut(&m, &c, shortcut, &mut self.clipboard); + } + return; + } let PhysicalKey::Code(key) = event.physical_key else { return; }; diff --git a/crates/horizon-client/src/game/clipboard.rs b/crates/horizon-client/src/game/clipboard.rs new file mode 100644 index 000000000..6b6b338ab --- /dev/null +++ b/crates/horizon-client/src/game/clipboard.rs @@ -0,0 +1,106 @@ +//! Copy and paste in the text fields: `KeyboardHandler`'s clipboard and the +//! shortcuts of `EditBox`, `MultiLineEditBox` and `TextFieldHelper`. +use super::*; +use horizon_client::clipboard::{self, EditShortcut}; +use winit::event::KeyEvent; + +impl Game<'_> { + /// `InputWithModifiers.isSelectAll`/`isCopy`/`isPaste`/`isCut` of a key + /// press (or repeat): the keyboard's modifier state, or a modifier key an + /// agent holds. + pub(super) fn edit_shortcut(&self, event: &KeyEvent) -> Option { + if event.state != ElementState::Pressed { + return None; + } + let m = self.modifiers; + let held = |keys: [KeyCode; 2]| keys.iter().any(|k| self.keys.contains(k)); + // InputQuirks.EDIT_SHORTCUT_KEY_MODIFIER: Cmd on macOS, Ctrl elsewhere. + let edit = if cfg!(target_os = "macos") { + m.super_key() || held([KeyCode::SuperLeft, KeyCode::SuperRight]) + } else { + m.control_key() || held([KeyCode::ControlLeft, KeyCode::ControlRight]) + }; + clipboard::edit_shortcut( + clipboard::shortcut_letter(&event.logical_key, event.physical_key), + edit, + m.shift_key() || held([KeyCode::ShiftLeft, KeyCode::ShiftRight]), + m.alt_key() || held([KeyCode::AltLeft, KeyCode::AltRight]), + ) + } + /// A shortcut in an append-only field limited to `max_chars` characters + /// (an `EditBox` with `setMaxLength`). True when the value changed. + pub(super) fn append_shortcut( + selection: &mut clipboard::AppendSelection, + board: &mut clipboard::SystemClipboard, + id: clipboard::FieldId, + value: &mut String, + shortcut: EditShortcut, + max_chars: usize, + ) -> bool { + selection.apply(id, value, shortcut, board, |v, t| { + clipboard::append_limited(v, t, max_chars) + }) + } + /// Shortcuts on the title, world creation and server screens. + pub(super) fn title_shortcut(&mut self, shortcut: EditShortcut) { + let Some(title) = self.title.as_mut() else { + return; + }; + if let Some((id, value, max)) = title.focused_field() { + Self::append_shortcut( + &mut self.text_selection, + &mut self.clipboard, + id, + value, + shortcut, + max, + ); + } + } + /// Typing or a backspace in an append-only field of the title screens: + /// Select All's selection is replaced first. + pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) { + let Some(title) = self.title.as_mut() else { + return; + }; + let cleared = title + .focused_field() + .is_some_and(|(id, value, _)| self.text_selection.take(id, value)); + if backspace { + if !cleared { + title.backspace(); + } + } else if let Some(text) = typed { + title.type_text(text); + } + } + /// Shortcuts in the creative inventory's search box (an `EditBox` of 50). + pub(super) fn creative_search_shortcut(&mut self, shortcut: EditShortcut) { + if Self::append_shortcut( + &mut self.text_selection, + &mut self.clipboard, + ("creative.search", 0), + &mut self.creative_screen.search, + shortcut, + CREATIVE_SEARCH_CHARS, + ) { + self.creative_screen.scroll = 0.0; + } + } + /// Typing or a backspace in the creative search box. + pub(super) fn creative_search_edit(&mut self, typed: Option<&str>, backspace: bool) { + let search = &mut self.creative_screen.search; + let cleared = self.text_selection.take(("creative.search", 0), search); + if backspace { + if !cleared { + search.pop(); + } + } else if let Some(text) = typed { + clipboard::append_limited(search, text, CREATIVE_SEARCH_CHARS); + } + self.creative_screen.scroll = 0.0; + } +} + +/// `CreativeModeInventoryScreen`'s search box: `setMaxLength(50)`. +const CREATIVE_SEARCH_CHARS: usize = 50; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 57d3abaa4..38a93c56b 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -589,7 +589,7 @@ impl Game<'_> { "pause_menu": self.pause_menu, "advanced_tooltips": self.settings.file.bool("advancedItemTooltips"), "pause_on_lost_focus": self.settings.file.bool("pauseOnLostFocus"), - "clipboard": self.copied, + "clipboard": self.clipboard.copied(), }, "dimension": self.dim.id(), "creative": self.creative, diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 1fb4004b9..f695f3c3f 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -409,16 +409,8 @@ impl Game<'_> { } /// `KeyboardHandler.setClipboard`. fn set_clipboard(&mut self, text: &str) { - if text.is_empty() { - return; - } - if self.clipboard.is_none() { - self.clipboard = arboard::Clipboard::new().ok(); - } - if let Some(c) = self.clipboard.as_mut() { - let _ = c.set_text(text.to_owned()); - } - self.copied = Some(text.to_owned()); + use horizon_client::clipboard::Clipboard; + self.clipboard.set(text); } /// The debug renderers' gizmos for a frame (`DebugRenderer.emitGizmos`). pub(super) fn debug_gizmos(&self, alpha: f32) -> Gizmos { diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 884db7fd4..4183596eb 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -321,12 +321,17 @@ impl Game<'_> { return; }; let ctrl = self.keys.contains(&winit::keyboard::KeyCode::ControlLeft); + let shortcut = self.edit_shortcut(event); let Some(o) = self.world_options.as_mut() else { return; }; if !o.port.focused { return; } + if let Some(shortcut) = shortcut { + o.port.shortcut(shortcut, &mut self.clipboard); + return; + } if !o.port.key(key, ctrl, false) && !ctrl && let Some(text) = &event.text diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index b6767bade..f9f7fc617 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -81,6 +81,15 @@ impl Game<'_> { self.ui.options = ui; self.handle_option_events(events) } + /// Ctrl+A/C/V/X in the options' search boxes; false when none has focus. + pub(super) fn options_shortcut( + &mut self, + shortcut: horizon_client::clipboard::EditShortcut, + ) -> bool { + self.ui + .options + .shortcut(&self.res.atlas, shortcut, &mut self.clipboard) + } pub(super) fn options_scroll(&mut self, amount: f32) { self.ui.options.scroll_at(self.cursor, amount); } @@ -145,11 +154,13 @@ impl Game<'_> { r.set_mipmap_levels(s.mipmap_levels.max(0) as u32); r.set_world_post(s.horizon.resolution_scale as f32 / 100.0, s.horizon.fxaa); } - if let Some(w) = &self.window { - let want = s.fullscreen; - if want != w.fullscreen().is_some() { - w.set_fullscreen(want.then_some(Fullscreen::Borderless(None))); - } + // Window.updateFullscreenIfChanged: only a changed option asks the + // window to change, so applying settings never undoes a fullscreen + // the compositor set up. + if let Some(w) = &self.window + && let Some(want) = self.fullscreen.request(s.fullscreen) + { + w.set_fullscreen(want.then_some(Fullscreen::Borderless(None))); } let mut volumes = s.volumes; volumes[0] = 1.0; @@ -171,6 +182,17 @@ impl Game<'_> { self.ui.chat.rescale(&self.res.atlas); } } + /// `Window.updateFullscreenState`: a fullscreen change made by the window + /// system is adopted by the option (`Minecraft.fullscreenStateChanged`). + pub(super) fn observe_fullscreen(&mut self) { + let Some(w) = &self.window else { return }; + if let Some(now) = self.fullscreen.observe(w.fullscreen().is_some()) + && self.settings.fullscreen != now + { + self.settings.fullscreen = now; + self.settings.save(&Self::options_path()); + } + } /// F11 (key.fullscreen): Window.toggleFullScreen, remembered in options.txt. pub(super) fn toggle_fullscreen(&mut self) { self.settings.fullscreen = !self.settings.fullscreen; diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 60746db79..6c24fef40 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -165,9 +165,19 @@ impl Game<'_> { search.insert_text(text); } } + /// Ctrl+A/C/V/X in the search box. + pub(super) fn recipe_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + if let Some(search) = self.recipe_ui.search.as_mut() { + search.shortcut(shortcut, &mut self.clipboard); + } + } /// A key press while the search box has focus. pub(super) fn recipe_key(&mut self, event: &winit::event::KeyEvent) { use winit::keyboard::{KeyCode, PhysicalKey}; + if let Some(shortcut) = self.edit_shortcut(event) { + self.recipe_shortcut(shortcut); + return; + } let ctrl = self.keys.contains(&KeyCode::ControlLeft); let shift = self.has_shift_down(); let Some(search) = self.recipe_ui.search.as_mut() else { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index cfb65fbeb..f7288bb80 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2206,12 +2206,26 @@ impl Game<'_> { if event.state != winit::event::ElementState::Pressed { return; } + let shortcut = self.edit_shortcut(event); let Some(r) = self.remote.as_mut() else { return; }; let Some(input) = r.chat_input.as_mut() else { return; }; + // ChatScreen's input: an EditBox of 256. + const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0); + if let Some(shortcut) = shortcut { + Self::append_shortcut( + &mut self.text_selection, + &mut self.clipboard, + INPUT, + input, + shortcut, + 256, + ); + return; + } // Logical keys: the text, not the scancode, decides (layouts, virtual keyboards). match &event.logical_key { Key::Named(NamedKey::Escape) => { @@ -2219,7 +2233,9 @@ impl Game<'_> { self.capture(true); } Key::Named(NamedKey::Backspace) => { - input.pop(); + if !self.text_selection.take(INPUT, input) { + input.pop(); + } } Key::Named(NamedKey::Enter) => { let message = r.chat_input.take().unwrap_or_default(); @@ -2228,6 +2244,7 @@ impl Game<'_> { } _ => { if let Some(text) = &event.text { + self.text_selection.take(INPUT, input); for c in text.chars().filter(|c| !c.is_control()) { if input.chars().count() < 256 { input.push(c); diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index c67a3e880..8226b7837 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -5,7 +5,7 @@ use super::Game; use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, - signs::{SignData, wood_type}, + signs::wood_type, }; use std::time::Instant; use winit::{ @@ -21,13 +21,6 @@ pub(super) struct SignEditor { } impl Game<'_> { - fn edited_sign(&mut self) -> Option<&mut SignData> { - let key = self.sign_edit.as_ref()?.pos; - match self.world.block_entities.get_mut(&key) { - Some(BlockEntity::Sign(sign)) => Some(sign), - _ => None, - } - } /// `SignBlock.openTextEdit` for the front side after placement. pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { self.sign_edit = Some(SignEditor { @@ -52,10 +45,15 @@ impl Game<'_> { if event.state != ElementState::Pressed { return; } + if let Some(shortcut) = self.edit_shortcut(event) { + self.sign_shortcut(shortcut); + return; + } let Some(edit) = self.sign_edit.as_mut() else { return; }; let front = edit.front; + let id = sign_line_id(front, edit.line); match event.physical_key { PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(), PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3, @@ -63,14 +61,17 @@ impl Game<'_> { edit.line = (edit.line + 1) & 3 } PhysicalKey::Code(KeyCode::Backspace) => { - let line = edit.line; - if let Some(sign) = self.edited_sign() { + let (line, key) = (edit.line, edit.pos); + if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) { let text = if front { &mut sign.front } else { &mut sign.back }; - text.lines[line].pop(); + let value = &mut text.lines[line]; + if !self.text_selection.take(id, value) { + value.pop(); + } } } _ => { @@ -90,6 +91,7 @@ impl Game<'_> { } else { &mut sign.back }; + self.text_selection.take(id, &mut text.lines[line]); for ch in typed.chars().filter(|c| !c.is_control()) { let mut next = text.lines[line].clone(); next.push(ch); @@ -102,6 +104,41 @@ impl Game<'_> { } } } + /// `TextFieldHelper.keyPressed`'s shortcuts on the edited line: a paste + /// (formatting and carriage returns removed) is taken whole or not at + /// all, as the line must stay within the sign's width. + fn sign_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + let Some(edit) = self.sign_edit.as_ref() else { + return; + }; + let (key, front, line) = (edit.pos, edit.front, edit.line); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let max = sign.max_line_width(); + let text = if front { + &mut sign.front + } else { + &mut sign.back + }; + let atlas = &self.res.atlas; + self.text_selection.apply( + sign_line_id(front, line), + &mut text.lines[line], + shortcut, + &mut self.clipboard, + |value, pasted| { + let next = format!( + "{value}{}", + horizon_client::clipboard::helper_clipboard_contents(pasted) + ); + HudBatch::text_width(atlas, &next) <= max && { + *value = next; + true + } + }, + ); + } /// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20). pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) { let b = HudBatch::new(size); @@ -206,3 +243,8 @@ impl Game<'_> { ); } } + +/// The sign line being edited, for Select All. +fn sign_line_id(front: bool, line: usize) -> horizon_client::clipboard::FieldId { + (if front { "sign.front" } else { "sign.back" }, line) +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index bdf8ae4a7..17374f9eb 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1158,17 +1158,41 @@ impl Game<'_> { let Some(s) = self.station.as_mut() else { return; }; + let cleared = self.text_selection.take(ANVIL_NAME, &mut s.name); if backspace { - s.name.pop(); + if !cleared { + s.name.pop(); + } } else if let Some(t) = text { for c in t.chars().filter(|c| !c.is_control()) { - if s.name.chars().count() < 50 { + if s.name.chars().count() < ANVIL_NAME_CHARS { s.name.push(c); } } } self.station_changed(); } + /// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the + /// recipe book's search box. + pub(super) fn station_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + if self.recipe_search_focused() { + self.recipe_shortcut(shortcut); + return; + } + let Some(s) = self.station.as_mut() else { + return; + }; + if Self::append_shortcut( + &mut self.text_selection, + &mut self.clipboard, + ANVIL_NAME, + &mut s.name, + shortcut, + ANVIL_NAME_CHARS, + ) { + self.station_changed(); + } + } // ---------------------------------------------------------------- drawing @@ -2063,3 +2087,7 @@ impl Game<'_> { Ok(()) } } + +/// The anvil's rename box (`AnvilScreen`: `setMaxLength(50)`). +const ANVIL_NAME: horizon_client::clipboard::FieldId = ("anvil.name", 0); +const ANVIL_NAME_CHARS: usize = 50; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7f60a690b..ea3e268e0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -25,6 +25,7 @@ pub mod camera; pub mod cauldron; pub mod chat; pub mod chunk; +pub mod clipboard; pub mod clock; pub mod clouds; pub mod collisions; diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 75f10140e..6b3646cb9 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -578,6 +578,16 @@ impl Screen { _ => None, } } + /// The focused text field, its id and maximum length (copy and paste). + pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> { + let id = match self { + Self::Edit { focus: 0, .. } => ("server.name", 0), + Self::Edit { .. } => ("server.address", 0), + Self::Direct { .. } => ("server.direct", 0), + _ => return None, + }; + self.focused_field().map(|f| (id, f, 128)) + } pub fn type_text(&mut self, text: &str) { if let Some(field) = self.focused_field() { for c in text.chars().filter(|c| !c.is_control()) { diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index cc23989de..aa9319ad2 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -1642,6 +1642,31 @@ impl OptionsUi { self.scroll = 0.0; } } + /// Ctrl+A/C/V/X in the language or pack search box; false when neither + /// is shown with the focus. + pub fn shortcut( + &mut self, + atlas: &HudAtlas, + shortcut: crate::clipboard::EditShortcut, + clipboard: &mut dyn crate::clipboard::Clipboard, + ) -> bool { + if self.selected_key.is_some() { + return false; + } + if self.page() == Page::Packs + && let Some(p) = &mut self.pack_screen + { + let m = crate::screen_draw::Measure(&atlas.font); + return p.shortcut(&m, shortcut, clipboard); + } + if self.page() == Page::Language { + if self.language_search.shortcut(shortcut, clipboard) { + self.scroll = 0.0; + } + return true; + } + false + } /// Keys while the options are open. Returns events; `handled` false lets /// Escape fall through. pub fn key( diff --git a/crates/horizon-client/src/pack_screen.rs b/crates/horizon-client/src/pack_screen.rs index b9c269f9c..628bbbe67 100644 --- a/crates/horizon-client/src/pack_screen.rs +++ b/crates/horizon-client/src/pack_screen.rs @@ -673,6 +673,21 @@ impl PackScreen { self.filter(None); } } + /// Ctrl+A/C/V/X in the search box; false when it does not have the focus. + pub fn shortcut( + &mut self, + m: &Measure, + shortcut: crate::clipboard::EditShortcut, + clipboard: &mut dyn crate::clipboard::Clipboard, + ) -> bool { + if !self.search_focused() { + return false; + } + if self.search.shortcut(m, shortcut, clipboard) { + self.filter(None); + } + true + } /// Backspace in the search box. pub fn erase(&mut self, m: &Measure, count: isize) { if self.confirm.is_none() diff --git a/crates/horizon-client/src/screen_draw.rs b/crates/horizon-client/src/screen_draw.rs index 55acdcb87..e21d61860 100644 --- a/crates/horizon-client/src/screen_draw.rs +++ b/crates/horizon-client/src/screen_draw.rs @@ -476,6 +476,23 @@ fn chars(s: &str) -> usize { fn sub(s: &str, from: usize, to: usize) -> String { s.chars().skip(from).take(to.saturating_sub(from)).collect() } +/// A text field with the font that scrolls it. +struct MeasuredField<'a, 'm>(&'a mut TextField, &'a Measure<'m>); +impl crate::clipboard::Editable for MeasuredField<'_, '_> { + fn select_all(&mut self) { + let len = chars(&self.0.value); + self.0.move_cursor_to(self.1, len, false); + self.0.set_highlight(self.1, 0); + } + fn selected_text(&self) -> String { + self.0.selected_text() + } + fn insert(&mut self, text: &str) -> bool { + let before = self.0.value.clone(); + self.0.insert_text(self.1, text); + self.0.value != before + } +} impl TextField { pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self { Self { @@ -668,6 +685,23 @@ impl TextField { } Some(false) } + /// Ctrl+A/C/V/X (`EditBox.keyPressed`). True when the value changed. + pub fn shortcut( + &mut self, + m: &Measure, + shortcut: crate::clipboard::EditShortcut, + clipboard: &mut dyn crate::clipboard::Clipboard, + ) -> bool { + crate::clipboard::apply(&mut MeasuredField(self, m), shortcut, clipboard) + } + /// `getHighlighted`. + pub fn selected_text(&self) -> String { + sub( + &self.value, + self.cursor.min(self.highlight), + self.cursor.max(self.highlight), + ) + } /// `getScreenX`: where a character index is drawn, from the box's left. pub fn screen_x(&self, m: &Measure, index: usize) -> i32 { if index > chars(&self.value) { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index bd783bfd2..1d21aa305 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -541,6 +541,20 @@ impl Title { _ => Action::None, } } + /// The focused text field, its id and maximum length (copy and paste). + pub fn focused_field(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> { + match &mut self.mode { + Mode::Multiplayer(screen) => screen.focused_text(), + Mode::Create { + name, seed, focus, .. + } => match focus { + 0 => Some((("world.name", 0), name, 32)), + 1 => Some((("world.seed", 0), seed, 32)), + _ => None, + }, + _ => None, + } + } pub fn type_text(&mut self, text: &str) { if let Mode::Multiplayer(screen) = &mut self.mode { screen.type_text(text); diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index 407504cbd..77243c6be 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -520,6 +520,20 @@ fn byte_index(s: &str, chars: usize) -> usize { pub fn char_len(s: &str) -> usize { s.chars().count() } +impl crate::clipboard::Editable for EditBox { + fn select_all(&mut self) { + self.move_cursor_to_end(false); + self.highlight = 0; + } + fn selected_text(&self) -> String { + EditBox::selected_text(self) + } + fn insert(&mut self, text: &str) -> bool { + let before = self.value.clone(); + self.insert_text(text); + self.value != before + } +} impl EditBox { pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self { Self { @@ -576,10 +590,7 @@ impl EditBox { /// EditBox.insertText: replace the selection, respecting the maximum length. pub fn insert_text(&mut self, text: &str) { let (a, b) = self.selected(); - let filtered: String = text - .chars() - .filter(|c| !c.is_control() && *c != 'ยง') - .collect(); + let filtered = crate::clipboard::filter_text(text, false); let room = self .max_length .saturating_sub(char_len(&self.value) - (b - a)); @@ -702,6 +713,17 @@ impl EditBox { } true } + /// Ctrl+A/C/V/X (`EditBox.keyPressed`). True when the value changed. + pub fn shortcut( + &mut self, + shortcut: crate::clipboard::EditShortcut, + clipboard: &mut dyn crate::clipboard::Clipboard, + ) -> bool { + let before = self.value.clone(); + crate::clipboard::apply(self, shortcut, clipboard); + self.reset_blink(); + self.value != before + } /// The first shown character after scrolling to the cursor, and the /// milliseconds since the field was focused (the cursor's blink). pub fn view_state(&mut self, atlas: &HudAtlas) -> (usize, u64) { diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index 6dc5c183b..3dbb74a21 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -1,6 +1,7 @@ //! Window sizing and frame pacing of 26.3: `Window.calculateScale` and //! `setGuiScale`, `MouseHandler`'s scaled positions, `FramerateLimitTracker`, -//! `FramerateLimiter` and the vsync present-mode choice. +//! `FramerateLimiter`, the vsync present-mode choice and the fullscreen +//! request/state pair. /// `Window.calculateScale`: the largest scale that leaves at least 320x240 /// GUI pixels, capped by `max_scale` (0 = automatic); an odd result is bumped @@ -263,10 +264,85 @@ impl FramerateLimiter { } } +/// blaze3d `Window`'s `fullscreenRequested` / `fullscreen` pair. The window +/// system has the last word: a change it makes on its own (a compositor +/// shortcut, a window rule) is adopted by the Fullscreen option +/// (`Window.updateFullscreenState` -> `Minecraft.fullscreenStateChanged`), and +/// the window is only asked to change when the option itself changes +/// (`Window.updateFullscreenIfChanged`), never re-forced to the option. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FullscreenState { + /// The state the window system last reported (`Window.fullscreen`). + actual: bool, + /// The state last asked of the window system, or adopted from it. + requested: bool, +} + +impl FullscreenState { + /// A window created windowed or, when `requested`, asked to be fullscreen. + pub fn new(requested: bool) -> Self { + Self { + actual: false, + requested, + } + } + + /// `Window.updateFullscreenIfChanged`: the state to ask of the window + /// when the option `wanted` differs from what was last asked or adopted. + pub fn request(&mut self, wanted: bool) -> Option { + (wanted != self.requested).then(|| { + self.requested = wanted; + wanted + }) + } + + /// `Window.updateFullscreenState`: the window now reports `now`; returns + /// it when it changed, for the option to adopt. + pub fn observe(&mut self, now: bool) -> Option { + (now != self.actual).then(|| { + self.actual = now; + self.requested = now; + now + }) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn fullscreen_follows_the_option_only_when_it_changes() { + let mut f = FullscreenState::new(false); + // Settings applied again with nothing changed: the window is left alone. + assert_eq!(f.request(false), None); + // The compositor makes the window fullscreen on its own: the option adopts it, + // and applying the settings afterwards does not undo it. + assert_eq!(f.observe(true), Some(true)); + assert_eq!(f.request(true), None); + assert_eq!(f.observe(true), None); + // F11: one request, not repeated while the compositor catches up. + assert_eq!(f.request(false), Some(false)); + assert_eq!(f.request(false), None); + assert_eq!(f.observe(false), Some(false)); + assert_eq!(f.request(false), None); + } + + #[test] + fn fullscreen_requests_changed_before_the_compositor_answers() { + // Created fullscreen from options.txt. + let mut f = FullscreenState::new(true); + assert_eq!(f.request(true), None); + assert_eq!(f.observe(true), Some(true)); + // Toggled twice before any configure: the second request cancels the first. + assert_eq!(f.request(false), Some(false)); + assert_eq!(f.request(true), Some(true)); + assert_eq!(f.observe(true), None); + // A compositor that refuses leaves the option where the player put it. + assert_eq!(f.request(false), Some(false)); + assert_eq!(f.request(false), None); + } + struct Virtual { now: i64, oversleep: i64, From 9bc9a1e1594f04ffdb8682bd7ad7ed2c9b8837e2 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:03:35 +0100 Subject: [PATCH 10/11] fix(website): allow clicks through decorative footer word --- website/src/style.css | 1 + 1 file changed, 1 insertion(+) diff --git a/website/src/style.css b/website/src/style.css index 6776ec7a3..edcd4f1ae 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -583,6 +583,7 @@ code { margin: 24px 0 -0.24em; text-align: center; white-space: nowrap; font: 400 27vw/0.9 var(--display); letter-spacing: -0.045em; color: transparent; -webkit-text-stroke: 1px #24242a; + pointer-events: none; user-select: none; } From 39e8bbb2f4d81e1046e88e96d5b0c06c4a3bd487 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:10:00 +0200 Subject: [PATCH 11/11] Cobwebs and sweet berry bushes slow the player Entity.applyEffectsFromBlocks now runs WebBlock.entityInside and SweetBerryBushBlock.entityInside for the player through Player.makeStuckInBlock (no slowdown while flying, impulse context reset), with Weaving's lighter cobweb hold and the sweet_berry_bush damage of a grown bush while the known movement is at least 0.003 on X or Z. The scene motion harness gains cobweb and berry-bush fixtures run through vanilla's real applyEffectsFromBlocks. Co-Authored-By: Claude Opus 5.5 --- .../examples/scene_motion_probe.rs | 6 ++ crates/horizon-client/src/effects.rs | 3 + crates/horizon-client/src/health.rs | 5 ++ crates/horizon-client/src/motion.rs | 71 +++++++++++++++++-- .../parity/VanillaSceneMotionOracle.java | 13 ++-- tools/test_native_scene_motion.py | 47 +++++++++++- 6 files changed, 133 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index e5309912b..a5c61c065 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -442,6 +442,12 @@ fn main() -> Result<()> { world.player.freeze_immune = boots; } "frozen" => world.player.ticks_frozen = op["value"].as_i64().unwrap() as i32, + "weaving" => world.player.status.weaving = op["value"].as_bool().unwrap(), + "flying" => { + let flying = op["value"].as_bool().unwrap(); + world.player.may_fly = flying; + world.player.flying = flying; + } "trigger" => world.player.jump_trigger_time = op["value"].as_i64().unwrap() as i32, "delay" => world.player.no_jump_delay = op["value"].as_i64().unwrap() as i32, "move" => world.move_self(vector(&op["value"]))?, diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 7c245987a..4e113bfbb 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -283,6 +283,7 @@ impl PlayerEffects { levitation: self.amplifier("levitation"), resistance: self.amplifier("resistance"), fire_resistance: self.get("fire_resistance").is_some(), + weaving: self.get("weaving").is_some(), water_breathing: self.get("water_breathing").is_some() || self.get("conduit_power").is_some(), protection: Vec::new(), @@ -378,6 +379,8 @@ pub struct StatusFlags { pub levitation: Option, pub resistance: Option, pub fire_resistance: bool, + /// Weaving: cobwebs hold half as much (`WebBlock.entityInside`). + pub weaving: bool, pub water_breathing: bool, /// Armor enchantment protection per damage type id (`EnchantmentHelper.getDamageProtection`). pub protection: Vec<(String, f32)>, diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index f9c0ed51c..46b4f4542 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -81,6 +81,8 @@ pub enum HealthEvent { StarvationDamage(f32), /// `LivingEntity.aiStep` hurting a fully frozen entity. FreezeDamage(f32), + /// `SweetBerryBushBlock.entityInside` pricking a moving entity. + SweetBerryBushDamage(f32), Updated { id: u8, value: f32, @@ -106,6 +108,9 @@ impl HealthEvent { match self { Self::StarvationDamage(amount) => format!("damage starve {:08x}", amount.to_bits()), Self::FreezeDamage(amount) => format!("damage freeze {:08x}", amount.to_bits()), + Self::SweetBerryBushDamage(amount) => { + format!("damage sweet_berry_bush {:08x}", amount.to_bits()) + } Self::Updated { id, value, dirty } => { format!("updated {id} {:08x} {dirty}", value.to_bits()) } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 779e50b8a..dde0b02af 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -775,7 +775,7 @@ impl MotionWorld<'_, '_, '_> { } /// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts /// to inside its movement path: powder snow (`PowderSnowBlock.entityInside` - /// and the FREEZE / EXTINGUISH effects). Pressure plates, tripwires and + /// and the FREEZE / EXTINGUISH effects), cobwebs and sweet berry bushes. Pressure plates, tripwires and /// rails are the world tick's scan. pub fn apply_effects_from_blocks(&mut self) -> Result<()> { use horizon_world::entity_move::MovementRecord; @@ -955,9 +955,14 @@ impl MotionWorld<'_, '_, '_> { } }; if inside && visited.insert(p.pack()) { - if powder_snow { - self.powder_snow_inside(p)?; - entered.push((step, p)); + match name { + "minecraft:powder_snow" => { + self.powder_snow_inside(p)?; + entered.push((step, p)); + } + "minecraft:cobweb" => self.web_inside(), + "minecraft:sweet_berry_bush" => self.sweet_berry_bush_inside(state)?, + _ => {} } // ServerPlayer.onInsideBlock self.player.events.push(MotionEvent::EnterBlock { state }); @@ -965,6 +970,60 @@ impl MotionWorld<'_, '_, '_> { } Ok(iterations + 1) } + /// `Player.makeStuckInBlock`: the next move is scaled by `multiplier` + /// (and the fall forgotten) unless flying; the impulse context resets + /// either way. + fn make_stuck_in_block(&mut self, multiplier: Vec3) { + if !self.player.flying { + self.player.fall_distance = 0.0; + self.player.stuck_multiplier = multiplier; + } + self.player.impulse.try_reset(); + } + /// `WebBlock.entityInside`: stuck at a quarter of the speed, half with + /// the Weaving effect. + fn web_inside(&mut self) { + let multiplier = if self.player.status.weaving { + Vec3::new(0.5, 0.25, 0.5) + } else { + Vec3::new(0.25, f64::from(0.05_f32), 0.25) + }; + self.make_stuck_in_block(multiplier); + } + /// `SweetBerryBushBlock.entityInside` for the player: slowed, and pricked + /// (`sweetBerryBush` damage, 1) by a grown bush while its known movement + /// is at least 0.003 on X or Z. + fn sweet_berry_bush_inside(&mut self, state: BlockStateId) -> Result<()> { + self.make_stuck_in_block(Vec3::new(f64::from(0.8_f32), 0.75, f64::from(0.8_f32))); + let age = self + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("age")) + .map_or("0", |a| a.as_str()); + if age == "0" { + return Ok(()); + } + // Player.isClientAuthoritative: ServerPlayer.getKnownMovement, this + // tick's movement. + let known = self.player.position.subtract(self.player.old_position); + if known.x * known.x + known.z * known.z > 0.0 + && (known.x.abs() >= f64::from(0.003_f32) || known.z.abs() >= f64::from(0.003_f32)) + { + let id = self + .resources + .health + .damage + .id("minecraft:sweet_berry_bush") + .ok_or("missing sweet_berry_bush damage type")?; + self.player.events.push(MotionEvent::Health( + crate::health::HealthEvent::SweetBerryBushDamage(1.0), + )); + let rules = self.scene.health_rules; + self.player.hurt(&self.resources.health, rules, id, 1.0)?; + } + Ok(()) + } /// `PowderSnowBlock.entityInside` for the player: stuck while the block /// at its feet is powder snow, with a snowflake now and then (server). fn powder_snow_inside(&mut self, p: BlockPos) -> Result<()> { @@ -977,9 +1036,7 @@ impl MotionWorld<'_, '_, '_> { if !in_block { return Ok(()); } - // Entity.makeStuckInBlock - EntityMoveWorld::reset_fall_distance(self)?; - self.player.stuck_multiplier = Vec3::new(f64::from(0.9_f32), 1.5, f64::from(0.9_f32)); + self.make_stuck_in_block(Vec3::new(f64::from(0.9_f32), 1.5, f64::from(0.9_f32))); // ServerPlayer.getKnownMovement: this tick's movement. let known = self.player.position.subtract(self.player.old_position); let random = &mut self.scene.random; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java index 446f40501..4ff64b7da 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java @@ -74,8 +74,9 @@ public final class VanillaSceneMotionOracle { return VanillaBlockLandingOracle.sound(s); } static final class Sources extends DamageSources { - DamageSource fall,stalagmite,starve,freeze;Sources(){super(null);} + DamageSource fall,stalagmite,starve,freeze,sweetBerryBush;Sources(){super(null);} @Override public DamageSource freeze(){return freeze;} + @Override public DamageSource sweetBerryBush(){return sweetBerryBush;} @Override public DamageSource starve(){return starve;} @Override public DamageSource fall(){return fall;} @Override public DamageSource stalagmite(){return stalagmite;} @@ -188,7 +189,9 @@ public final class VanillaSceneMotionOracle { @Override public boolean isAutoSpinAttack(){return false;} @Override public boolean isSpectator(){return false;} @Override public boolean isNoGravity(){return false;} - @Override public boolean hasEffect(Holder effect){return false;} + // No effects but Weaving (WebBlock.entityInside), set without the effect's callbacks. + boolean weaving; + @Override public boolean hasEffect(Holder effect){return weaving&&effect==net.minecraft.world.effect.MobEffects.WEAVING;} @Override public MobEffectInstance getEffect(Holder effect){return null;} @Override public MoveSimulationType getMoveSimulationType(){return MoveSimulationType.SERVER_AND_CLIENT;} @Override public boolean isClientAuthoritative(){return false;} @@ -205,7 +208,7 @@ public final class VanillaSceneMotionOracle { String name=stat==net.minecraft.stats.Stats.DAMAGE_ABSORBED?"absorbed":stat==net.minecraft.stats.Stats.DAMAGE_TAKEN?"taken":stat==net.minecraft.stats.Stats.DAMAGE_RESISTED?"resisted":null; if(name==null){name=stat.getPath();if(!Set.of("swim_one_cm","walk_under_water_one_cm","walk_on_water_one_cm","climb_one_cm","sprint_one_cm","crouch_one_cm","walk_one_cm","aviate_one_cm","fly_one_cm").contains(name))throw new AssertionError(stat);}events.add("health-stat "+name+" "+value); } - @Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,DamageSource source,float damage){var sources=((Level)level).sources;events.add(String.format("damage %s %08x",source==sources.fall?"fall":source==sources.stalagmite?"stalagmite":source==sources.starve?"starve":source==sources.freeze?"freeze":"unknown",Float.floatToIntBits(damage)));return super.hurtServer(level,source,damage);} + @Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,DamageSource source,float damage){var sources=((Level)level).sources;events.add(String.format("damage %s %08x",source==sources.fall?"fall":source==sources.stalagmite?"stalagmite":source==sources.starve?"starve":source==sources.freeze?"freeze":source==sources.sweetBerryBush?"sweet_berry_bush":"unknown",Float.floatToIntBits(damage)));return super.hurtServer(level,source,damage);} @Override public void teleportRelative(double x,double y,double z){setPos(getX()+x,getY()+y,getZ()+z);} @Override protected void playStepSound(BlockPos p,BlockState state){} @Override public void gameEvent(Holder event,Entity source){} @@ -283,7 +286,7 @@ public final class VanillaSceneMotionOracle { var trace=new Trace();trace.out=new PrintWriter(OutputStream.nullOutputStream());trace.fail=-1; var level=(Level)allocate.invoke(unsafe,Level.class);level.chunks=VanillaSceneCollisionOracle.scene(description,trace);level.border=new Border(); level.rng=net.minecraft.util.RandomSource.create(0);level.sources=(Sources)allocate.invoke(unsafe,Sources.class); - level.sources.fall=damageSources.get("minecraft:fall");level.sources.stalagmite=damageSources.get("minecraft:stalagmite");level.sources.starve=damageSources.get("minecraft:starve");level.sources.freeze=damageSources.get("minecraft:freeze"); + level.sources.fall=damageSources.get("minecraft:fall");level.sources.stalagmite=damageSources.get("minecraft:stalagmite");level.sources.starve=damageSources.get("minecraft:starve");level.sources.freeze=damageSources.get("minecraft:freeze");level.sources.sweetBerryBush=damageSources.get("minecraft:sweet_berry_bush"); level.waypoints=(Waypoints)allocate.invoke(unsafe,Waypoints.class);level.waypoints.level=level; level.rules=new Rules();level.difficulty=net.minecraft.world.Difficulty.NORMAL; var server=(VanillaBlockLandingOracle.Server)allocate.invoke(unsafe,VanillaBlockLandingOracle.Server.class); @@ -370,6 +373,8 @@ public final class VanillaSceneMotionOracle { ((EntityEquipment)field(LivingEntity.class,"equipment").get(p)).set(net.minecraft.world.entity.EquipmentSlot.FEET,stack); } case "frozen"->p.frozen=op.get("value").getAsInt(); + case "weaving"->p.weaving=op.get("value").getAsBoolean(); + case "flying"->{var a=p.getAbilities();a.mayfly=a.flying=op.get("value").getAsBoolean();} case "trigger"->trigger.setInt(p,op.get("value").getAsInt()); case "delay"->delay.setInt(p,op.get("value").getAsInt()); case "ack_attributes"->{p.attrs.getAttributesToUpdate().clear();p.attrs.getAttributesToSync().clear();} diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index 09eeee966..dd8270f7c 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -145,10 +145,55 @@ def powder_snow_corpus(): ops += restore(tower) yield dict(position=vec((25.5,4,23.5) if yaw in (0,180) else (23.5,4,25.5)),ops=ops) +def stuck_corpus(): + """Cobwebs and sweet berry bushes in the player's path ("snow_tick" runs + the real applyEffectsFromBlocks): WebBlock.entityInside with and without + Weaving, SweetBerryBushBlock.entityInside at every age (the slowdown, and + sweet_berry_bush damage while moving through a grown bush), falling into + them, crossing both, and flying through (Player.makeStuckInBlock).""" + def place(name,positions,properties=None): + return [op('block',name=name,position=list(p),**({'properties':properties} if properties else {})) for p in positions] + def restore(positions): + return [op('block',name='minecraft:stone' if p[1]<=3 else 'minecraft:air',position=list(p)) for p in positions] + def tick(forward=0.,strafe=0.,jump=False): + return op('snow_tick',vec((strafe,0,forward)),jumping=jump) + field=[(x,y,z) for x in range(24,27) for y in (4,5) for z in range(24,29)] + low=[(x,4,z) for x in range(24,27) for z in range(24,29)] + rng=random.Random(0x57454253) + walks=[(0,0,False),(.98,0,False),(.98,0,True),(0,.98,True),(-.98,.3,False),(.3,-.98,True)] + for block,blocks,variants in [('minecraft:cobweb',field,[{}]),('minecraft:sweet_berry_bush',low,[{'age':str(a)} for a in range(4)])]: + for properties in variants: + for weaving in ([False,True] if block=='minecraft:cobweb' else [False]): + for start in [(25.5,4,23.5),(25.5,4,25.5),(25.5,9,25.5),(24.2,4,26.7)]: + for walk in walks: + ops=[op('seed',rng.randrange(1<<31)),op('weaving',weaving),op('yaw',single(rng.choice([0,30,90,180,-135])))]+place(block,blocks,properties) + ops += [tick(*walk) if i<50 else tick() for i in range(70)] + ops += restore(blocks) + yield dict(position=vec(start),ops=ops) + # Damage cooldown and health: a long walk back and forth through ripe bushes. + for age in [1,2,3]: + for health in [20,3,1]: + ops=[op('health',single(health))]+place('minecraft:sweet_berry_bush',low,{'age':str(age)}) + ops += [tick(.98 if (i//25)%2==0 else -.98) for i in range(120)] + yield dict(position=vec((25.5,4,23.5)),ops=ops) + # A web beside a bush and powder snow under a web. + for yaw in [0,90,180,270]: + ops=[op('yaw',single(yaw))]+place('minecraft:cobweb',[(25,4,25),(25,5,25)])+place('minecraft:sweet_berry_bush',[(25,4,26),(24,4,25)],{'age':'3'}) + ops += place('minecraft:powder_snow',[(26,3,25),(26,2,25)])+place('minecraft:cobweb',[(26,4,25)]) + ops += [tick(.98,(.98 if i%20<10 else 0),i%15==0) for i in range(80)] + yield dict(position=vec((25.5,4,23.5) if yaw in (0,180) else (23.5,4,25.5)),ops=ops) + # Flying through: no slowdown or fall reset (Player.makeStuckInBlock). + for block,properties in [('minecraft:cobweb',None),('minecraft:sweet_berry_bush',{'age':'3'})]: + for walk in [(.98,0,False),(0,.98,False)]: + ops=[op('flying',True)]+place(block,field if block=='minecraft:cobweb' else low,properties) + ops += [tick(*walk) for _ in range(40)]+[op('flying',False)]+[tick(*walk) for _ in range(30)] + yield dict(position=vec((25.5,4.5,23.5)),ops=ops) + def corpus(): yield from attribute_corpus(False) yield from pose_corpus(False) yield from powder_snow_corpus() + yield from stuck_corpus() def food(level=20,saturation=5,exhaustion=0,timer=0): return op('food',food=level,saturation=single(saturation),exhaustion=single(exhaustion),timer=timer) # Actual ServerPlayer.checkMovementStatistics with all query contexts. These @@ -464,7 +509,7 @@ def main(): 'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'fixtures':len(fixtures), 'operations':operations,'sources_sha256':tested,'resources':resource_hash,'input_sha256':input_hash, 'references':references, - 'scope':('Client sprint scene executes the real LocalPlayer.aiStep prefix through sprint decisions, stopping at the riding/parent movement boundary, followed by real LocalPlayer.modifyInput and the native server actor simulation. Sprint setters dispatch to that server actor, sharing its actual FoodData and collision conditions. Compares local sprint timer/input history and actual attribute changes, movement, distance exhaustion and hunger. Actual local crouch selection precedes new keyboard input; slowdown, sprint eligibility and pose-dependent dimensions share resident state. No effects, equipment, vehicles or fluid physics. Full client/server tick and networking remain unfinished. ' if args.sprint_input else '')+'Stored PlayerMotion binds resident client chunks and registered attributes/coefficients to air travel, jumping, Entity.move, step resolution, ground/support updates, restitution and speed factors. Repeated native Player.travel/jump/move and actual Player.aiStep / direct LivingEntity.aiStep compare position, velocity, bounds, collision/ground flags, support, climb state, fall-reset field, both sync flags, speed, head yaw, jump trigger and jump delay by exact bits. Prepared-local-input Player.aiStep paths verify the stored speed refresh after movement, with empty inventory and no nearby entities. Travel uses the actual Player.getSpeed movement-attribute query, independently of that stored base-living speed field; both getter and setter execute native bodies. Dry aiStep includes small-velocity cleanup, input damping, held/released jump timing and server frost-modifier removal. Snapshots also compare all allocated attribute instances, base/cache/dirty state, modifier values/operations/permanence and pending update/sync membership. Per-reference JVM holder/instance hashes are replayed so pending callback order and resulting ordered events also match. Dry resident scene with standing, crouching and crawling bounds, cached eye height, native pose-fit selection and ledge backoff; zero frozen ticks, empty equipment, no interpolation, fluids, vehicles, effects or other entities. The oracle controls pose storage and invokes actual native refreshDimensions on changes; full synchronized pose schema and network notifications remain separate. Actual pending attribute refresh runs after player movement and before pose selection in simulation operations, clamping health/absorption and rebuilding scale-dependent dimensions. Native ServerPlayer waypoint-receive and inherited transmit callbacks are compared as ordered requests; the waypoint manager and its network delivery remain controlled consumers. Direct refresh operations and the full enclosing tick remain separate boundaries. Actual LivingEntity.checkFallDamage, registered Block.fallOn/bounceOn and Player/LivingEntity.causeFallDamage are composed, including float-narrowed fall-distance accumulation, reset, last-climb clearing, safe-fall and damage-multiplier attributes, impulse exemptions and ordered landing particle/sound/statistic/hit-ground/damage requests. Farmland pushes the stored player and replaces actual chunk state; repeated turtle-egg changes preserve hatch. Block state at the landing fixture is compared after every operation. World RNG is a seeded native legacy stream. Actual ServerPlayer/Player/LivingEntity hurt dispatch now updates native synchronized health and player absorption, modified armor/toughness reduction, exhaustion, damage cooldown/last-source state and velocity synchronization. Native health storage and dirty flags are compared after every operation. Damage sources use actual decoded/tagged pinned damage registries. ServerPlayer jump statistics and exhaustion are included; dead-or-dying state disables movement input and jumping. Empty equipment/hands/effects, configurable difficulty and natural regeneration, damage gamerules enabled, loaded client and no spawn-extra fall particles define this scene domain. Ordered health/statistic/combat-record/broadcast/sound/criterion/death requests are compared; criterion argument payloads retain the separate combat gate. Actual health changes are applied, but audiovisual playback, persistent statistics, combat tracker internals, full death/drop/respawn services, block neighbor/drop/block-entity callbacks, movement emission, block-inside and networking remain controlled consumers. Actual FoodData.tick and ServerPlayer.tickRegeneration now share the same stored health, attributes, exhaustion and registered starvation damage. Snapshots compare food level, saturation, exhaustion, timer and tick count. Cases cover all four difficulties, regeneration rule changes, absorption during starvation, Peaceful recovery, timer overflow and nonfinite food values. Simulation operations compose clock setup, actual player movement and actual food ticking in their native order, including fall damage followed by regeneration in the same tick. Explicit clock operations establish cooldown/hurt-time/game-time/tick-count state; full enclosing native tick/doTick methods are not invoked by those setup operations. Input preparation has its own client comparison. ServerPlayer.checkMovementStatistics executes on accepted resident deltas after movement and before food ticking. Additional direct method fixtures cover all 512 overlapping passenger/swim/eye-water/water/climb/ground/sprint/crouch/glide flag combinations, invulnerable abilities, centimeter rounding, overflow, signed zero and nonfinite deltas. Those query contexts apply only to the statistics method; fluid/vehicle/glide physics remain unbound. ServerGamePacketListener packet acceptance/rejection and scheduling are not executed. Powder snow operations (snow_tick) run the clock, the powder snow flags and old position of baseTick, then actual aiStep with the real Entity.applyEffectsFromBlocks (movement-path block sweep, StepBasedCollector, PowderSnowBlock.entityInside: stuck multiplier, ALTERNATIVE snowflake particles from the level random, FREEZE/EXTINGUISH, ServerPlayer.onInsideBlock criteria) and the server freezing phase (thaw, frost modifier, freeze damage every 40 ticks); leather boots are a component-less stack and #freeze_immune_wearables is emulated by them. Outside snow_tick block-inside effects stay disabled on both sides. No full Player.tick, consumable item-use lifecycle, local input lifecycle, nonempty inventory/equipment ticks, full freezing, complete death lifecycle or full gameplay parity claim.'}) + 'scope':('Client sprint scene executes the real LocalPlayer.aiStep prefix through sprint decisions, stopping at the riding/parent movement boundary, followed by real LocalPlayer.modifyInput and the native server actor simulation. Sprint setters dispatch to that server actor, sharing its actual FoodData and collision conditions. Compares local sprint timer/input history and actual attribute changes, movement, distance exhaustion and hunger. Actual local crouch selection precedes new keyboard input; slowdown, sprint eligibility and pose-dependent dimensions share resident state. No effects, equipment, vehicles or fluid physics. Full client/server tick and networking remain unfinished. ' if args.sprint_input else '')+'Stored PlayerMotion binds resident client chunks and registered attributes/coefficients to air travel, jumping, Entity.move, step resolution, ground/support updates, restitution and speed factors. Repeated native Player.travel/jump/move and actual Player.aiStep / direct LivingEntity.aiStep compare position, velocity, bounds, collision/ground flags, support, climb state, fall-reset field, both sync flags, speed, head yaw, jump trigger and jump delay by exact bits. Prepared-local-input Player.aiStep paths verify the stored speed refresh after movement, with empty inventory and no nearby entities. Travel uses the actual Player.getSpeed movement-attribute query, independently of that stored base-living speed field; both getter and setter execute native bodies. Dry aiStep includes small-velocity cleanup, input damping, held/released jump timing and server frost-modifier removal. Snapshots also compare all allocated attribute instances, base/cache/dirty state, modifier values/operations/permanence and pending update/sync membership. Per-reference JVM holder/instance hashes are replayed so pending callback order and resulting ordered events also match. Dry resident scene with standing, crouching and crawling bounds, cached eye height, native pose-fit selection and ledge backoff; zero frozen ticks, empty equipment, no interpolation, fluids, vehicles, effects or other entities. The oracle controls pose storage and invokes actual native refreshDimensions on changes; full synchronized pose schema and network notifications remain separate. Actual pending attribute refresh runs after player movement and before pose selection in simulation operations, clamping health/absorption and rebuilding scale-dependent dimensions. Native ServerPlayer waypoint-receive and inherited transmit callbacks are compared as ordered requests; the waypoint manager and its network delivery remain controlled consumers. Direct refresh operations and the full enclosing tick remain separate boundaries. Actual LivingEntity.checkFallDamage, registered Block.fallOn/bounceOn and Player/LivingEntity.causeFallDamage are composed, including float-narrowed fall-distance accumulation, reset, last-climb clearing, safe-fall and damage-multiplier attributes, impulse exemptions and ordered landing particle/sound/statistic/hit-ground/damage requests. Farmland pushes the stored player and replaces actual chunk state; repeated turtle-egg changes preserve hatch. Block state at the landing fixture is compared after every operation. World RNG is a seeded native legacy stream. Actual ServerPlayer/Player/LivingEntity hurt dispatch now updates native synchronized health and player absorption, modified armor/toughness reduction, exhaustion, damage cooldown/last-source state and velocity synchronization. Native health storage and dirty flags are compared after every operation. Damage sources use actual decoded/tagged pinned damage registries. ServerPlayer jump statistics and exhaustion are included; dead-or-dying state disables movement input and jumping. Empty equipment/hands/effects, configurable difficulty and natural regeneration, damage gamerules enabled, loaded client and no spawn-extra fall particles define this scene domain. Ordered health/statistic/combat-record/broadcast/sound/criterion/death requests are compared; criterion argument payloads retain the separate combat gate. Actual health changes are applied, but audiovisual playback, persistent statistics, combat tracker internals, full death/drop/respawn services, block neighbor/drop/block-entity callbacks, movement emission, block-inside and networking remain controlled consumers. Actual FoodData.tick and ServerPlayer.tickRegeneration now share the same stored health, attributes, exhaustion and registered starvation damage. Snapshots compare food level, saturation, exhaustion, timer and tick count. Cases cover all four difficulties, regeneration rule changes, absorption during starvation, Peaceful recovery, timer overflow and nonfinite food values. Simulation operations compose clock setup, actual player movement and actual food ticking in their native order, including fall damage followed by regeneration in the same tick. Explicit clock operations establish cooldown/hurt-time/game-time/tick-count state; full enclosing native tick/doTick methods are not invoked by those setup operations. Input preparation has its own client comparison. ServerPlayer.checkMovementStatistics executes on accepted resident deltas after movement and before food ticking. Additional direct method fixtures cover all 512 overlapping passenger/swim/eye-water/water/climb/ground/sprint/crouch/glide flag combinations, invulnerable abilities, centimeter rounding, overflow, signed zero and nonfinite deltas. Those query contexts apply only to the statistics method; fluid/vehicle/glide physics remain unbound. ServerGamePacketListener packet acceptance/rejection and scheduling are not executed. Powder snow operations (snow_tick) run the clock, the powder snow flags and old position of baseTick, then actual aiStep with the real Entity.applyEffectsFromBlocks (movement-path block sweep, StepBasedCollector, PowderSnowBlock.entityInside: stuck multiplier, ALTERNATIVE snowflake particles from the level random, FREEZE/EXTINGUISH, ServerPlayer.onInsideBlock criteria; WebBlock.entityInside with and without Weaving and SweetBerryBushBlock.entityInside at every age through Player.makeStuckInBlock, with sweet_berry_bush damage on the known movement) and the server freezing phase (thaw, frost modifier, freeze damage every 40 ticks); leather boots are a component-less stack and #freeze_immune_wearables is emulated by them. Outside snow_tick block-inside effects stay disabled on both sides. No full Player.tick, consumable item-use lifecycle, local input lifecycle, nonempty inventory/equipment ticks, full freezing, complete death lifecycle or full gameplay parity claim.'}) print(f'Scoped scene motion parity passed: {report}',flush=True) if __name__=='__main__':main()