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] 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); +}