diff --git a/Cargo.lock b/Cargo.lock index b95c1ab9a..2a9d0cd47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -316,6 +316,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -826,13 +837,16 @@ dependencies = [ "ab_glyph", "arboard", "bytemuck", + "chrono", "cpal", + "flate2", "glam", "horizon-assets", "horizon-core", "horizon-protocol", "horizon-theme", "horizon-world", + "log", "miniz_oxide 0.8.9", "png", "pollster", @@ -884,6 +898,30 @@ dependencies = [ "xxhash-rust", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.62.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "indexmap" version = "2.14.2" diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 23cd4cafb..f602eac7b 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -23,6 +23,9 @@ cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } miniz_oxide = "0.8" ab_glyph = "0.2.32" +log = "0.4" +chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } +flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } horizon-theme = { path = "../horizon-theme" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index edfdcf0ea..4be39eac5 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -55,6 +55,7 @@ pub struct Assets { pub properties: Properties, pub material_states: [BlockStateId; 6], pub sprite_size: u32, + pub sprite_minimum_size: u32, pub pixels: Vec, pub texture_layers: u32, pub model_catalog: crate::models::StateModels, @@ -238,6 +239,7 @@ impl Assets { properties, material_states, sprite_size: sprites.size, + sprite_minimum_size: sprites.minimum_size, texture_layers: u32::try_from(sprites.layers.len())?, pixels: sprites.pixels, model_catalog: models.catalog, diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 034354ade..1e0d70d5a 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -461,7 +461,7 @@ fn build_stream>( *out = T::from_sample(*s); } }, - |e| eprintln!("Horizon: audio stream error: {e}"), + |e| log::warn!("Horizon: audio stream error: {e}"), None, )?; Ok(stream) @@ -486,7 +486,7 @@ impl Audio { Ok(v) => (Some(v), true), Err(e) => { if output { - eprintln!("Horizon: no sound: {e}"); + log::warn!("Horizon: no sound: {e}"); } (None, false) } @@ -533,7 +533,7 @@ impl Audio { tried.push(name.clone()); match open_device(&device, mixer.clone()) { Ok((stream, config)) => { - eprintln!( + log::info!( "Horizon: audio output {name} ({} Hz, {} channels, {})", config.sample_rate().0, config.channels(), diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index 91969d0c9..8683402a2 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -111,6 +111,11 @@ const BLOCK_XYZ: [Param; 3] = [ p("y", Ty::Int, "block Y"), p("z", Ty::Int, "block Z"), ]; +const OVER: Param = flag( + "over", + Ty::Num, + "turn with mouse motion spread over this many seconds (eased), as a player would", +); const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]); macro_rules! cmd { @@ -145,6 +150,11 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("wait-ready", Session, "wait-ready [SECONDS]", "wait until the player has spawned and no chunks are pending", "Polls status every 250 ms; replies with the status, or an error after SECONDS (default 120).", ["horizon-ctl wait-ready 300"], &[opt("seconds", Ty::Num, "how long to wait (default 120)")], mcp: true, local: true), + cmd!("logs", Session, "logs [--lines N] [--crash]", "the end of the game's log, or its newest crash report", + "Reads the game home ($HORIZON_HOME, else ~/.local/share/horizon): logs/latest.log (the last N lines, default 100) or, with --crash, the newest file in crash-reports. Read-only; works whether the game runs or not.", + ["horizon-ctl logs", "horizon-ctl logs --lines 300", "horizon-ctl logs --crash"], + &[flag("lines", Ty::Int, "how many lines of latest.log (default 100)"), flag("crash", Ty::Bool, "the newest crash report instead")], + mcp: true, local: true), cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)", "", ["horizon-ctl status"], &[], mcp: false, local: false), cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen", @@ -200,16 +210,22 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("look", Move, "look YAW PITCH", "set the view direction in degrees", "Yaw 0 faces south (+Z), 90 west (-X), 180 north, -90 east; pitch 90 looks straight down.", ["horizon-ctl look 90 10"], &[p("yaw", Ty::Num, "yaw in degrees"), p("pitch", Ty::Num, "pitch in degrees (-90 up .. 90 down)")], mcp: true, local: false), - cmd!("turn", Move, "turn DYAW DPITCH", "rotate the view by an amount", "", ["horizon-ctl turn 45 0"], - &[p("dyaw", Ty::Num, "yaw change"), p("dpitch", Ty::Num, "pitch change")], mcp: false, local: false), - cmd!("look-at", Move, "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID", "turn to face a point, a block (a visible face of it) or an entity", - "look-at block aims at a face the crosshair can reach and fails when none is visible.", - ["horizon-ctl look-at 10.5 65 3.5", "horizon-ctl look-at block 10 64 3 up", "horizon-ctl look-at entity 42"], - &XYZ, mcp: true, local: false), - cmd!("look-at-block", Move, "look-at-block X Y Z [FACE]", "aim the crosshair at a block (same as look-at block)", "", - ["horizon-ctl look-at-block 10 64 3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to aim at")], mcp: true, local: false, wire: "look-at block"), - cmd!("look-at-entity", Move, "look-at-entity ID", "face an entity (same as look-at entity)", "", - ["horizon-ctl look-at-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: false, wire: "look-at entity"), + cmd!("turn", Move, "turn DYAW DPITCH [--over S]", "rotate the view by an amount", + "Without --over the view jumps. With --over S the turn is mouse motion fed over S seconds with ease-in-out, through the same path as a real mouse (sensitivity, inverted axes, cinematic camera), and the reply comes once it is done.", + ["horizon-ctl turn 45 0", "horizon-ctl turn -90 10 --over 0.5"], + &[p("dyaw", Ty::Num, "yaw change in degrees"), p("dpitch", Ty::Num, "pitch change in degrees"), OVER], mcp: true, local: false), + cmd!("mouse-move", Move, "mouse-move DX DY", "move the mouse: relative motion that turns the view like a player's mouse", + "DX and DY are mouse units (pixels of relative motion) added to the frame's accumulated movement and turned by MouseHandler.turnPlayer: degrees = units x 0.15 x (sensitivity x 0.6 + 0.2)^3 x 8 (without the 8 while scoping), inverted axes and the cinematic camera included. Positive DX turns right, positive DY looks down. Works in the world with no screen open; replies with yaw and pitch after the frame that turned.", + ["horizon-ctl mouse-move 100 0", "horizon-ctl mouse-move -25 40"], + &[p("dx", Ty::Num, "horizontal motion (positive turns right)"), p("dy", Ty::Num, "vertical motion (positive looks down)")], mcp: true, local: false), + cmd!("look-at", Move, "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID [--over S]", "turn to face a point, a block (a visible face of it) or an entity", + "look-at block aims at a face the crosshair can reach and fails when none is visible. --over S turns there with mouse motion over S seconds (the shorter way round) instead of jumping.", + ["horizon-ctl look-at 10.5 65 3.5", "horizon-ctl look-at block 10 64 3 up", "horizon-ctl look-at entity 42 --over 0.4"], + &[XYZ[0], XYZ[1], XYZ[2], OVER], mcp: true, local: false), + cmd!("look-at-block", Move, "look-at-block X Y Z [FACE] [--over S]", "aim the crosshair at a block (same as look-at block)", "", + ["horizon-ctl look-at-block 10 64 3", "horizon-ctl look-at-block 10 64 3 up --over 0.3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to aim at"), OVER], mcp: true, local: false, wire: "look-at block"), + cmd!("look-at-entity", Move, "look-at-entity ID [--over S]", "face an entity (same as look-at entity)", "", + ["horizon-ctl look-at-entity 42"], &[p("id", Ty::Int, "entity id from entities"), OVER], mcp: true, local: false, wire: "look-at entity"), cmd!("tp", Move, "tp X Y Z", "teleport the player", "", ["horizon-ctl tp 0 80 0"], &XYZ, mcp: true, local: false), // Act cmd!("break", Act, "break X Y Z [--timeout S]", "mine a block, holding the attack button until it breaks", @@ -541,6 +557,21 @@ mod tests { ) .is_err() ); + let turn = find("turn").unwrap(); + assert_eq!( + line_for(turn, &json!({ "dyaw": -90, "dpitch": 10.5, "over": 0.5 })).unwrap(), + ["turn", "-90", "10.5", "--over", "0.5"] + ); + let mouse = find("mouse-move").unwrap(); + assert_eq!(tool_name(mouse), "mouse_move"); + assert_eq!( + line_for(mouse, &json!({ "dx": -25, "dy": 40 })).unwrap(), + ["mouse-move", "-25", "40"] + ); + assert_eq!( + line_for(block, &json!({ "x": 1, "y": 2, "z": 3, "over": 0.3 })).unwrap(), + ["look-at", "block", "1", "2", "3", "--over", "0.3"] + ); let button = find("click-button").unwrap(); assert_eq!( line_for(button, &json!({ "label": "Create New World" })).unwrap(), diff --git a/crates/horizon-client/src/bin/horizon-ctl/launch.rs b/crates/horizon-client/src/bin/horizon-ctl/launch.rs index 984b634af..b4f46634b 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/launch.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/launch.rs @@ -10,6 +10,7 @@ use std::{ time::{Duration, Instant}, }; +use horizon_client::logging::{data_dir, game_home}; use serde_json::{Value, json}; #[cfg(windows)] @@ -17,42 +18,12 @@ const CLIENT: &str = "horizon-client.exe"; #[cfg(not(windows))] const CLIENT: &str = "horizon-client"; -/// The platform data folder (what the `dirs` crate's data_dir gives). -fn data_dir() -> PathBuf { - let env = |k: &str| { - std::env::var_os(k) - .filter(|v| !v.is_empty()) - .map(PathBuf::from) - }; - let home = env("HOME").or_else(|| env("USERPROFILE")); - if cfg!(windows) { - if let Some(d) = env("APPDATA") { - return d; - } - } else if cfg!(target_os = "macos") { - if let Some(h) = &home { - return h.join("Library/Application Support"); - } - } else if let Some(d) = env("XDG_DATA_HOME") { - return d; - } else if let Some(h) = &home { - return h.join(".local/share"); - } - std::env::temp_dir() -} pub fn launcher_home() -> PathBuf { match std::env::var_os("HORIZON_LAUNCHER_HOME").filter(|h| !h.is_empty()) { Some(h) => PathBuf::from(h), None => data_dir().join("horizon-launcher"), } } -pub fn game_home() -> PathBuf { - match std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) { - Some(h) => PathBuf::from(h), - None => data_dir().join("horizon"), - } -} - /// `v2026.10.13.1` gives [2026, 10, 13, 1]; a pre-release suffix is ignored. pub fn version_parts(tag: &str) -> Vec { tag.trim_start_matches('v') diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 39bcc1d8e..2e1b1bb56 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -183,6 +183,7 @@ impl Session { thread::sleep(Duration::from_secs_f64(seconds.max(0.0))); self.game(&format!("key {key} up")) } + "logs" => logs(&horizon_client::logging::game_home(), &words[1..]), "wait-ready" => { let limit = if words.len() > 1 { number(1, "SECONDS")? @@ -228,6 +229,52 @@ impl Session { } } +/// `logs [--lines N] [--crash]` for the game in `home`: the reply's `text` is the log's last +/// lines or the report. +fn logs(home: &Path, words: &[String]) -> Result { + use horizon_client::logging; + let mut lines = 100; + let mut crash = false; + let mut it = words.iter(); + while let Some(word) = it.next() { + match word.as_str() { + "--crash" => crash = true, + "--lines" => { + lines = it + .next() + .and_then(|n| n.parse::().ok()) + .filter(|&n| n > 0) + .ok_or_else(|| Failure::usage("--lines takes a number above 0"))?; + } + other => { + return Err(Failure::usage(format!( + "unknown argument {other}; usage: {}", + usage("logs") + ))); + } + } + } + let missing = |what: String| Failure { + reply: json!({ "error": what }), + status: GAME_ERROR, + }; + if crash { + let path = logging::newest_crash_report(home).ok_or_else(|| { + missing(format!( + "no crash report in {}", + logging::crash_reports_dir(home).display() + )) + })?; + let text = std::fs::read_to_string(&path) + .map_err(|e| missing(format!("{}: {e}", path.display())))?; + return Ok(json!({ "path": path, "text": text })); + } + let path = logging::logs_dir(home).join("latest.log"); + let tail = + logging::tail(&path, lines).map_err(|e| missing(format!("{}: {e}", path.display())))?; + Ok(json!({ "path": path, "text": tail.join("\n") + "\n" })) +} + fn usage(name: &str) -> String { commands::find(name).map_or_else(|| name.to_owned(), |c| format!("horizon-ctl {}", c.usage)) } @@ -424,6 +471,17 @@ fn main() -> ExitCode { _ => script(&mut session, std::io::stdin().lock(), keep_going, pretty), } } + // Text for people; scripts and MCP get the JSON reply. + Some("logs") => match session.run(&args) { + Ok(reply) => { + print!("{}", reply["text"].as_str().unwrap_or_default()); + 0 + } + Err(f) => { + print(&f.reply, pretty); + f.status + } + }, Some(_) => match session.run(&args) { Ok(reply) => { print(&reply, pretty); @@ -442,6 +500,52 @@ fn main() -> ExitCode { mod tests { use super::*; + #[test] + fn logs_reads_the_end_of_latest_log_and_the_newest_crash_report() { + let home = std::env::temp_dir().join(format!("horizon-ctl-logs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&home); + let words = |s: &str| -> Vec { s.split_whitespace().map(String::from).collect() }; + let failure = logs(&home, &words("")).unwrap_err(); + assert!( + failure.reply["error"] + .as_str() + .unwrap() + .contains("latest.log") + ); + std::fs::create_dir_all(home.join("logs")).unwrap(); + let text: String = (1..=150) + .map(|i| format!("[10:00:00] [Render thread/INFO]: line {i}\n")) + .collect(); + std::fs::write(home.join("logs/latest.log"), text).unwrap(); + let reply = logs(&home, &words("")).unwrap(); + let tail = reply["text"].as_str().unwrap(); + assert_eq!(tail.lines().count(), 100); + assert!(tail.starts_with("[10:00:00] [Render thread/INFO]: line 51\n")); + assert!(tail.ends_with("line 150\n")); + let reply = logs(&home, &words("--lines 2")).unwrap(); + assert_eq!( + reply["text"], + "[10:00:00] [Render thread/INFO]: line 149\n[10:00:00] [Render thread/INFO]: line 150\n" + ); + assert_eq!(logs(&home, &words("--lines 0")).unwrap_err().status, USAGE); + assert_eq!(logs(&home, &words("--tail")).unwrap_err().status, USAGE); + assert!(logs(&home, &words("--crash")).is_err()); + std::fs::create_dir_all(home.join("crash-reports")).unwrap(); + std::fs::write( + home.join("crash-reports/crash-2026-10-13_10.00.00-client.txt"), + "old", + ) + .unwrap(); + std::fs::write( + home.join("crash-reports/crash-2026-10-14_10.00.00-client.txt"), + "new", + ) + .unwrap(); + let reply = logs(&home, &words("--crash")).unwrap(); + assert_eq!(reply["text"], "new"); + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn script_lines_split_like_a_shell() { assert_eq!( diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs index 492377fe7..fa60b38f9 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -91,6 +91,21 @@ impl Session { Err(f) => (vec![text(&f.reply)], true), }; } + if cmd.name == "logs" { + let words = match commands::line_for(cmd, args) { + Ok(w) => w, + Err(e) => return (vec![text(&json!({ "error": e, "kind": "usage" }))], true), + }; + return match self.run(&words) { + Ok(reply) => ( + vec![ + json!({ "type": "text", "text": format!("{}\n\n{}", reply["path"].as_str().unwrap_or_default(), reply["text"].as_str().unwrap_or_default()) }), + ], + false, + ), + Err(f) => (vec![text(&f.reply)], true), + }; + } let mut words = match commands::line_for(cmd, args) { Ok(w) => w, Err(e) => return (vec![text(&json!({ "error": e, "kind": "usage" }))], true), @@ -202,6 +217,7 @@ mod tests { "click_button", "screenshot", "inventory", + "logs", ] { let want = if want == "break_block" { "break" } else { want }; assert!(names.contains(want), "{want}"); diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 2a5dc53e0..74f4d4fcf 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -113,6 +113,8 @@ impl Chat { ticks: u64, focused: bool, ) { + // ChatComponent.logChatMessage: every message is in the log. + crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain())); if self.log { println!("[CHAT] {}", content.plain()); } diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs new file mode 100644 index 000000000..7e57355f2 --- /dev/null +++ b/crates/horizon-client/src/crash.rs @@ -0,0 +1,614 @@ +//! Crash reports, laid out like vanilla's CrashReport.getFriendlyReport: a comment, the time, +//! a description, the error with its stack, then the details of the game and the machine. +//! Written to `crash-reports/crash--client.txt` in the game folder when +//! the main thread panics or `main` gets an error back. Nothing is sent anywhere. +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; + +use chrono::{DateTime, Local}; + +/// What the game is doing, set as it goes: graphics adapter, settings, packs, world. +static DETAILS: Mutex> = Mutex::new(Vec::new()); +static REPORTED: AtomicBool = AtomicBool::new(false); + +/// Sets one line of the report's details (replacing the last value under `key`). +pub fn set_detail(key: &'static str, value: impl Into) { + let mut details = DETAILS.lock().unwrap_or_else(|e| e.into_inner()); + let value = value.into(); + match details.iter_mut().find(|(k, _)| *k == key) { + Some(entry) => entry.1 = value, + None => details.push((key, value)), + } +} + +pub fn clear_detail(key: &'static str) { + DETAILS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|(k, _)| *k != key); +} + +fn details() -> Vec<(&'static str, String)> { + DETAILS.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +/// Vanilla picks a line from a list of jokes; these only say what happened. +const COMMENTS: &[&str] = &[ + "Something went wrong.", + "The game stopped here.", + "This should not have happened.", + "Details below.", +]; + +/// One crash, ready to be written. +pub struct Report { + pub time: DateTime, + pub description: String, + /// The error's message, first line of the stack section. + pub error: String, + /// Where it happened and how it got there: one frame a line (`function (file:line:col)`). + pub stack: String, + pub thread: String, + /// `client` or `server`, the end of the file name. + pub side: &'static str, + pub details: Vec<(String, String)>, + pub log: Vec, +} + +/// `crash-2026-10-14_09.05.07-client.txt` +pub fn file_name(time: &DateTime, side: &str) -> String { + format!("crash-{}-{side}.txt", time.format("%Y-%m-%d_%H.%M.%S")) +} + +impl Report { + /// The report's text. + pub fn text(&self) -> String { + let comment = COMMENTS[self.time.timestamp().rem_euclid(COMMENTS.len() as i64) as usize]; + let mut out = String::new(); + let _ = writeln!(out, "---- Horizon Crash Report ----"); + let _ = writeln!(out, "// {comment}\n"); + let _ = writeln!(out, "Time: {}", self.time.format("%Y-%m-%d %H:%M:%S")); + let _ = writeln!(out, "Description: {}\n", self.description); + let _ = writeln!(out, "{}", self.error); + for line in self.stack.lines() { + let _ = writeln!(out, "\tat {line}"); + } + let _ = writeln!( + out, + "\n\nA detailed walkthrough of the error, its code path and all known details is as follows:" + ); + let _ = writeln!(out, "{}\n", "-".repeat(87)); + let _ = writeln!(out, "-- Head --"); + let _ = writeln!(out, "Thread: {}\n", self.thread); + let _ = writeln!(out, "-- System Details --"); + let _ = writeln!(out, "Details:"); + for (key, value) in &self.details { + let _ = writeln!(out, "\t{key}: {value}"); + } + let _ = writeln!(out, "\n-- Last {} log lines --", self.log.len()); + for line in &self.log { + let _ = writeln!(out, "{line}"); + } + out + } + + /// Writes the report in `home/crash-reports` and returns its path. + pub fn save(&self, home: &Path) -> std::io::Result { + let dir = crate::logging::crash_reports_dir(home); + std::fs::create_dir_all(&dir)?; + let path = dir.join(file_name(&self.time, self.side)); + std::fs::write(&path, self.text())?; + Ok(path) + } +} + +/// The release this binary came with: launcher installs live in a folder named after the tag. +fn release_tag() -> Option { + let exe = std::env::current_exe().ok()?; + let folder = exe.parent()?.file_name()?.to_str()?; + (folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit())) + .then(|| folder.to_owned()) +} + +fn command_output(program: &str, args: &[&str]) -> Option { + let out = std::process::Command::new(program) + .args(args) + .output() + .ok()?; + let text = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + (out.status.success() && !text.is_empty()).then_some(text) +} + +fn read(path: &str) -> Option { + std::fs::read_to_string(path).ok() +} + +/// `PRETTY_NAME` of /etc/os-release and the kernel, or the system's own version string. +fn operating_system() -> String { + let arch = std::env::consts::ARCH; + let version = if cfg!(target_os = "linux") { + let name = read("/etc/os-release").and_then(|t| { + t.lines() + .find_map(|l| l.strip_prefix("PRETTY_NAME=")) + .map(|v| v.trim_matches('"').to_owned()) + }); + let kernel = read("/proc/sys/kernel/osrelease").map(|k| k.trim().to_owned()); + match (name, kernel) { + (Some(n), Some(k)) => Some(format!("{n}, kernel {k}")), + (n, k) => n.or(k), + } + } else if cfg!(target_os = "macos") { + command_output("sw_vers", &["-productVersion"]).map(|v| format!("macOS {v}")) + } else if cfg!(windows) { + command_output("cmd", &["/C", "ver"]) + } else { + None + }; + format!( + "{} ({arch}) version {}", + std::env::consts::OS, + version.unwrap_or_else(|| "unknown".into()) + ) +} + +fn cpu() -> String { + let threads = std::thread::available_parallelism().map_or(0, |n| n.get()); + let name = if cfg!(target_os = "linux") { + read("/proc/cpuinfo").and_then(|t| { + t.lines() + .find(|l| l.starts_with("model name")) + .and_then(|l| l.split_once(':')) + .map(|(_, v)| v.trim().to_owned()) + }) + } else if cfg!(target_os = "macos") { + command_output("sysctl", &["-n", "machdep.cpu.brand_string"]) + } else { + std::env::var("PROCESSOR_IDENTIFIER").ok() + }; + format!( + "{threads}x {}", + name.unwrap_or_else(|| std::env::consts::ARCH.into()) + ) +} + +/// Total memory and what this process uses, in MiB where the system says. +fn memory() -> String { + const MIB: u64 = 1024 * 1024; + let kib = |text: &str, key: &str| -> Option { + text.lines() + .find(|l| l.starts_with(key))? + .split_whitespace() + .nth(1)? + .parse() + .ok() + }; + let (total, used) = if cfg!(target_os = "linux") { + ( + read("/proc/meminfo") + .and_then(|t| kib(&t, "MemTotal:")) + .map(|k| k * 1024), + read("/proc/self/status") + .and_then(|t| kib(&t, "VmRSS:")) + .map(|k| k * 1024), + ) + } else if cfg!(target_os = "macos") { + ( + command_output("sysctl", &["-n", "hw.memsize"]).and_then(|v| v.parse().ok()), + None, + ) + } else if cfg!(windows) { + ( + command_output( + "powershell", + &[ + "-NoProfile", + "-Command", + "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory", + ], + ) + .and_then(|v| v.parse().ok()), + None, + ) + } else { + (None, None) + }; + match (total, used) { + (Some(t), Some(u)) => format!( + "{} MiB used by the game, {} MiB installed", + u / MIB, + t / MIB + ), + (Some(t), None) => format!("{} MiB installed", t / MIB), + _ => "unknown".into(), + } +} + +/// The report's details: Horizon's and the machine's, then what the game set as it ran. +pub fn system_details() -> Vec<(String, String)> { + let mut version = env!("CARGO_PKG_VERSION").to_owned(); + if let Some(tag) = release_tag() { + version = format!("{tag} (client {version})"); + } + let mut out = vec![ + ("Horizon Version".to_owned(), version), + ("Minecraft Version".to_owned(), "26.3".to_owned()), + ("Operating System".to_owned(), operating_system()), + ("CPU".to_owned(), cpu()), + ("Memory".to_owned(), memory()), + ]; + out.extend(details().into_iter().map(|(k, v)| (k.to_owned(), v))); + out +} + +fn thread_name() -> String { + let current = std::thread::current(); + match current.name() { + Some("main") | None => "Render thread".into(), + Some(name) => name.into(), + } +} + +/// Writes the report and tells where it is; the log gets the error too. +fn deliver(home: &Path, report: Report) -> Option { + if REPORTED.swap(true, Ordering::SeqCst) { + return None; + } + // The panic is on stderr already: the stack goes to the log only. + crate::logging::write_only( + log::Level::Error, + &format!( + "Horizon crashed: {}\n{}", + report.error, + report + .stack + .lines() + .map(|l| format!("\tat {l}")) + .collect::>() + .join("\n") + ), + ); + crate::logging::flush(); + match report.save(home) { + Ok(path) => { + eprintln!("Horizon: crash report saved to {}", path.display()); + Some(path) + } + Err(e) => { + eprintln!("Horizon: could not save a crash report: {e}"); + eprintln!("{}", report.text()); + None + } + } +} + +fn panic_message(info: &std::panic::PanicHookInfo) -> String { + let payload = info.payload(); + let text = payload + .downcast_ref::<&str>() + .map(|s| s.to_string()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "Box".into()); + match info.location() { + Some(at) => format!("panicked at {at}:\n{text}"), + None => format!("panicked:\n{text}"), + } +} + +/// A `std::backtrace` as one line a frame, `function (file:line:col)`. Captured in a panic hook +/// (`from_panic`), it starts at the frame that panicked: the hook's and the panic machinery's +/// frames go. Paths inside the workspace lose the build machine's prefix. +pub fn stack_lines(backtrace: &str, from_panic: bool) -> String { + // The workspace as it was on the machine that built this binary (it need not exist here). + let manifest = env!("CARGO_MANIFEST_DIR"); + let root = manifest + .strip_suffix("crates/horizon-client") + .unwrap_or(manifest); + let mut frames: Vec<(String, Option)> = Vec::new(); + for line in backtrace.lines() { + let line = line.trim(); + if let Some(at) = line.strip_prefix("at ") { + if let Some(frame) = frames.last_mut() { + frame.1 = Some(short_path(at, root).to_owned()); + } + } else if let Some((n, name)) = line.split_once(": ") + && n.chars().all(|c| c.is_ascii_digit()) + { + frames.push((name.to_owned(), None)); + } + } + let machinery = |name: &str| { + [ + "std::panicking::", + "core::panicking::", + "std::sys::backtrace::", + "__rustc::", + ] + .iter() + .any(|p| name.starts_with(p)) + || name.contains("rust_begin_unwind") + }; + // The hook's frames, then the panic machinery's, then the code that panicked. + let top = frames.iter().take(30).position(|(name, _)| machinery(name)); + let first = match top.filter(|_| from_panic) { + Some(start) => { + start + + frames[start..] + .iter() + .take_while(|(name, _)| machinery(name)) + .count() + } + None => 0, + }; + // Some platforms keep std's own capture frames (`::create`). + let first = first + + frames[first..] + .iter() + .take_while(|(name, _)| name.trim_start_matches('<').starts_with("std::backtrace")) + .count(); + frames[first..] + .iter() + .map(|(name, at)| match at { + Some(at) => format!("{name} ({at})\n"), + None => format!("{name}\n"), + }) + .collect() +} + +/// A source path without the build machine's folders: relative to the workspace, or from the +/// crate's folder for dependencies (`winit-0.30.13/src/event_loop.rs:642:56`). +fn short_path<'a>(path: &'a str, root: &str) -> &'a str { + if let Some(rest) = path.strip_prefix(root) { + return rest; + } + if let Some(i) = path.find("/registry/src/") { + let rest = &path[i + "/registry/src/".len()..]; + if let Some((_index, krate)) = rest.split_once('/') { + return krate; + } + } + path +} + +/// A report for a panic, with the stack captured now (RUST_BACKTRACE or not). +pub fn panic_report(info: &std::panic::PanicHookInfo, side: &'static str) -> Report { + Report { + time: Local::now(), + description: "Unexpected error".into(), + error: panic_message(info), + stack: stack_lines( + &std::backtrace::Backtrace::force_capture().to_string(), + true, + ), + thread: thread_name(), + side, + details: system_details(), + log: crate::logging::recent_lines(), + } +} + +/// Reports panics: on the main thread a crash report (the panic then ends the game, exit code +/// 101); on other threads the error goes to the log, as vanilla's uncaught exception handler +/// does. The default hook still prints the panic. +pub fn install(home: PathBuf, side: &'static str) { + let default = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + default(info); + let main = std::thread::current().name() == Some("main"); + if main { + deliver(&home, panic_report(info, side)); + } else { + log::error!( + "Caught previously unhandled exception in thread {}: {}", + thread_name(), + panic_message(info) + ); + } + })); +} + +/// Vanilla's debug crash (`key.debug.crash` held for ten seconds): the error `main` gets back, +/// with the stack where it was raised. +#[derive(Debug)] +pub struct DebugCrash { + stack: String, +} + +impl DebugCrash { + pub const MESSAGE: &str = "Manually triggered debug crash"; + #[allow(clippy::new_without_default)] + pub fn new() -> Self { + Self { + stack: stack_lines( + &std::backtrace::Backtrace::force_capture().to_string(), + false, + ), + } + } +} + +impl std::fmt::Display for DebugCrash { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str(Self::MESSAGE) + } +} + +impl std::error::Error for DebugCrash {} + +/// A report for an error `main` got back: the game ends with it. +pub fn report_error( + home: &Path, + side: &'static str, + error: &(dyn std::error::Error + 'static), +) -> Option { + if let Some(debug) = error.downcast_ref::() { + return deliver( + home, + Report { + time: Local::now(), + description: DebugCrash::MESSAGE.into(), + error: DebugCrash::MESSAGE.into(), + stack: debug.stack.clone(), + thread: thread_name(), + side, + details: system_details(), + log: crate::logging::recent_lines(), + }, + ); + } + let mut message = error.to_string(); + let mut source = error.source(); + while let Some(e) = source { + let _ = write!(message, "\nCaused by: {e}"); + source = e.source(); + } + deliver( + home, + Report { + time: Local::now(), + description: "Fatal error".into(), + error: message, + stack: String::new(), + thread: thread_name(), + side, + details: system_details(), + log: crate::logging::recent_lines(), + }, + ) +} + +/// Called every frame: panics once `HORIZON_DEBUG_CRASH` asks (development builds only). +pub fn debug_crash_tick() { + static AT: std::sync::OnceLock> = + std::sync::OnceLock::new(); + if let Some((first, after)) = + AT.get_or_init(|| debug_crash_after().map(|d| (std::time::Instant::now(), d))) + && first.elapsed() >= *after + { + panic!("Manually triggered debug crash"); + } +} + +/// Development builds crash on purpose when `HORIZON_DEBUG_CRASH` is set (vanilla has F3+C held +/// for ten seconds): the number is seconds after the first frame (default 5). +pub fn debug_crash_after() -> Option { + if !cfg!(debug_assertions) { + return None; + } + let value = std::env::var("HORIZON_DEBUG_CRASH").ok()?; + let seconds = value.parse::().unwrap_or(5.0).max(0.0); + Some(std::time::Duration::from_secs_f64(seconds)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn report() -> Report { + Report { + time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(), + description: "Unexpected error".into(), + error: "panicked at src/game.rs:10:5:\nboom".into(), + stack: "horizon_client::game::frame (src/game.rs:10:5)\n".into(), + thread: "Render thread".into(), + side: "client", + details: vec![ + ("Horizon Version".into(), "0.1.0".into()), + ("Minecraft Version".into(), "26.3".into()), + ("Graphics".into(), "Test GPU (Vulkan), driver 1.0".into()), + ], + log: vec!["[09:05:06] [Render thread/INFO]: load assets: 1.20s".into()], + } + } + + #[test] + fn file_names_are_vanillas() { + assert_eq!( + file_name(&report().time, "client"), + "crash-2026-10-14_09.05.07-client.txt" + ); + } + + #[test] + fn the_report_reads_like_vanillas() { + let text = report().text(); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines[0], "---- Horizon Crash Report ----"); + assert!(lines[1].starts_with("// ")); + assert_eq!(lines[3], "Time: 2026-10-14 09:05:07"); + assert_eq!(lines[4], "Description: Unexpected error"); + assert_eq!(lines[6], "panicked at src/game.rs:10:5:"); + assert_eq!(lines[7], "boom"); + assert_eq!( + lines[8], + "\tat horizon_client::game::frame (src/game.rs:10:5)" + ); + assert!(text.contains("-- Head --\nThread: Render thread\n")); + assert!(text.contains( + "-- System Details --\nDetails:\n\tHorizon Version: 0.1.0\n\tMinecraft Version: 26.3\n\tGraphics: Test GPU (Vulkan), driver 1.0\n" + )); + assert!(text.ends_with( + "-- Last 1 log lines --\n[09:05:06] [Render thread/INFO]: load assets: 1.20s\n" + )); + } + + #[test] + fn stacks_start_at_the_panicking_frame() { + let bt = format!( + " 0: horizon_client::crash::panic_report\n at {root}/src/crash.rs:296:16\n 1: std::panicking::panic_with_hook\n at /rustc/abc/library/std/src/panicking.rs:823:13\n 2: core::panicking::panic_fmt\n at /rustc/abc/library/core/src/panicking.rs:80:14\n 3: horizon_client::crash::debug_crash_tick\n at {root}/src/crash.rs:359:9\n 4: winit::dispatch\n at /home/someone/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/winit-0.30.13/src/event_loop.rs:642:56\n 5: main\n", + root = env!("CARGO_MANIFEST_DIR") + ); + assert_eq!( + stack_lines(&bt, true), + "horizon_client::crash::debug_crash_tick (crates/horizon-client/src/crash.rs:359:9)\nwinit::dispatch (winit-0.30.13/src/event_loop.rs:642:56)\nmain\n" + ); + } + + #[test] + fn the_debug_crash_is_reported_as_vanillas() { + let error: Box = DebugCrash::new().into(); + assert_eq!(error.to_string(), "Manually triggered debug crash"); + let debug = error.downcast_ref::().unwrap(); + // The stack starts where the crash was raised (DebugCrash::new, in this file). + let first = debug.stack.lines().next().unwrap(); + assert!(first.contains("crash.rs"), "{}", debug.stack); + } + + #[test] + fn a_panic_becomes_a_report() { + // A real panic through a hook, as the game's would be. + let caught = std::sync::Arc::new(Mutex::new(None)); + let sink = caught.clone(); + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + if panic_message(info).contains("the test crash") { + *sink.lock().unwrap() = Some(panic_report(info, "client")); + } + })); + let _ = std::panic::catch_unwind(|| panic!("the test crash")); + std::panic::set_hook(previous); + let report = caught.lock().unwrap().take().expect("the hook ran"); + assert!(report.error.contains("the test crash")); + assert!(report.error.contains("crash.rs")); + // The first frame is the test's own code, not the panic machinery. + let first = report.stack.lines().next().unwrap(); + assert!(first.contains("crash.rs"), "{}", report.stack); + let text = report.text(); + assert!(text.contains("Description: Unexpected error")); + assert!(text.contains("\tMinecraft Version: 26.3\n")); + assert!(text.contains("\tOperating System: ")); + assert!(text.contains("\tCPU: ")); + let home = std::env::temp_dir().join(format!("horizon-crash-save-{}", std::process::id())); + let path = report.save(&home).unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), text); + assert!( + path.file_name() + .unwrap() + .to_str() + .unwrap() + .ends_with("-client.txt") + ); + let _ = std::fs::remove_dir_all(&home); + } +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 02fec0958..d56f81765 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -134,6 +134,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, on) in [ ("NoAI", m.no_ai), ("Silent", m.silent), + ("NoGravity", m.no_gravity), + ("Glowing", m.glowing), ("Invulnerable", m.invulnerable_flag), ] { if on { @@ -142,6 +144,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&horizon_world::nbt::JavaString::from(key)); } } + if m.ticks_frozen > 0 { + map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen)); + } else { + map.remove(&horizon_world::nbt::JavaString::from("TicksFrozen")); + } for (key, value) in [ ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), @@ -601,6 +608,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } m.name_visible = flag(tag, "CustomNameVisible"); m.no_ai = flag(tag, "NoAI"); + m.no_gravity = flag(tag, "NoGravity"); + m.glowing = flag(tag, "Glowing"); + m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32; m.silent = flag(tag, "Silent"); m.invulnerable_flag = flag(tag, "Invulnerable"); m.no_gravity = m.no_gravity || flag(tag, "NoGravity"); @@ -1557,39 +1567,91 @@ fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) { } } } +const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"]; pub fn bucket_data(m: &Mob) -> Tag { let mut data = Tag::compound([ ("Age", Tag::Int(m.extra.age)), - ("Variant", Tag::Int(i32::from(m.extra.variant))), + ("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))), ("Health", Tag::Float(m.health.to_bits())), ]); + for (key, on) in [ + ("NoAI", m.no_ai), + ("Silent", m.silent), + ("NoGravity", m.no_gravity), + ("Glowing", m.glowing || m.has_effect("glowing")), + ("Invulnerable", m.invulnerable_flag), + ("PersistenceRequired", m.persistent), + ] { + if on { + put(&mut data, key, Tag::Byte(1)); + } + } if let Some(ttl) = crate::mobs::animal_brain::hunting_cooldown(m) { put(&mut data, "HuntingCooldown", Tag::Long(ttl)); } data } -pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) { - let data = stack.data().and_then(|d| { - d.other - .iter() - .find(|(key, _)| key == "minecraft:bucket_entity_data") - .map(|(_, v)| v) - }); - let Some(data) = data else { return }; - if let Some(v) = number(data.get("Age")) { - m.extra.age = v as i32; - } - if let Some(v) = number(data.get("Variant")) { - m.extra.variant = v as u8; - } - if let Some(v) = float(data.get("Health")) { - m.health = v as f32; - } +pub fn bucket_components(m: &Mob) -> crate::item_data::StackData { + let mut data = crate::item_data::StackData { + custom_name: m.custom_name.clone(), + ..Default::default() + }; + data.set_other("minecraft:bucket_entity_data", Some(bucket_data(m))); if m.species() == crate::mobs::Species::Axolotl { - crate::mobs::animal_brain::set_hunting_cooldown( - m, - number(data.get("HuntingCooldown")).unwrap_or(0), - ); + let variant = AXOLOTL_VARIANTS + .get(usize::from(m.extra.variant)) + .unwrap_or(&"lucy"); + data.set_other("minecraft:axolotl/variant", Some(string(variant))); + } + data +} +pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) { + let Some(components) = stack.data() else { + return; + }; + if let Some(name) = &components.custom_name { + m.custom_name = Some(name.clone()); + } + if let Some(data) = components.other("minecraft:bucket_entity_data") { + if let Some(v) = number(data.get("Age")) { + m.extra.age = v as i32; + } + if let Some(v) = number(data.get("AgeLocked")) { + m.extra.age_locked = v != 0; + } + // Keep old Horizon buckets readable; the modern component below takes precedence. + if let Some(v) = number(data.get("Variant")) { + m.extra.variant = v as u8; + } + if let Some(v) = float(data.get("Health")) { + m.health = v as f32; + } + for (key, flag) in [ + ("NoAI", &mut m.no_ai), + ("Silent", &mut m.silent), + ("NoGravity", &mut m.no_gravity), + ("Glowing", &mut m.glowing), + ("Invulnerable", &mut m.invulnerable_flag), + ("PersistenceRequired", &mut m.persistent), + ] { + if let Some(v) = number(data.get(key)) { + *flag = v != 0; + } + } + if m.species() == crate::mobs::Species::Axolotl { + crate::mobs::animal_brain::set_hunting_cooldown( + m, + number(data.get("HuntingCooldown")).unwrap_or(0), + ); + } + } + if m.species() == crate::mobs::Species::Axolotl + && let Some(name) = text(components.other("minecraft:axolotl/variant")) + && let Some(id) = AXOLOTL_VARIANTS + .iter() + .position(|&v| v == name.trim_start_matches("minecraft:")) + { + m.extra.variant = id as u8; } } @@ -1607,6 +1669,18 @@ mod axolotl_nbt_tests { let kind = Arc::new(data.types.get("minecraft:axolotl").unwrap().clone()); let mut m = Mob::new(1, kind.clone(), Vec3::new(0.0, 4.0, 0.0), 0.0); crate::mobs::animal_brain::set_hunting_cooldown(&mut m, 123); + m.extra.variant = 4; + m.extra.age = -24000; + m.extra.age_locked = true; + m.no_ai = true; + m.silent = true; + m.no_gravity = true; + m.glowing = true; + m.invulnerable_flag = true; + m.persistent = true; + m.custom_name = Some("Bucket friend".into()); + m.health = 5.0; + { let mm = &mut m.extra.animal_brain.as_mut().unwrap().mem; mm.play_dead_ticks.set(78); @@ -1641,16 +1715,78 @@ mod axolotl_nbt_tests { Some(42) ); let mut stack = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1); - stack.extra = Some(Box::new(crate::item_data::StackData { - other: vec![("minecraft:bucket_entity_data".into(), bucket_data(&m))], - ..Default::default() - })); + stack.extra = Some(Box::new(bucket_components(&m))); + assert_eq!( + text(stack.data().unwrap().other("minecraft:axolotl/variant")), + Some("blue".into()) + ); + assert!(bucket_data(&m).get("Variant").is_none()); + let stack = item_from_nbt(&item_to_nbt(&stack)).unwrap(); let mut restored = Mob::new(2, kind, Vec3::new(0.0, 4.0, 0.0), 0.0); load_bucket_data(&mut restored, &stack); assert_eq!( crate::mobs::animal_brain::hunting_cooldown(&restored), Some(123) ); + assert_eq!( + ( + restored.extra.variant, + restored.extra.age, + restored.extra.age_locked + ), + (4, -24000, true) + ); + assert!( + restored.no_ai + && restored.silent + && restored.no_gravity + && restored.glowing + && restored.invulnerable_flag + && restored.persistent + ); + assert_eq!(restored.custom_name.as_deref(), Some("Bucket friend")); + assert_eq!(restored.health, 5.0); + restored.ticks_frozen = 140; + restored.ignite_for_ticks(160); + assert_eq!(restored.ticks_frozen, 0); + restored.ticks_frozen = 140; + restored.ignite_for_ticks(1); + assert_eq!( + restored.ticks_frozen, 0, + "even an ignition that does not extend burning clears freeze" + ); + for (id, name) in AXOLOTL_VARIANTS.iter().enumerate() { + let mut vanilla = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1); + vanilla.extra = Some(Box::new(crate::item_data::StackData { + other: vec![("minecraft:axolotl/variant".into(), string(name))], + ..Default::default() + })); + load_bucket_data(&mut restored, &vanilla); + assert_eq!( + usize::from(restored.extra.variant), + id, + "component-only vanilla buckets work" + ); + } + let mut legacy = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1); + legacy.extra = Some(Box::new(crate::item_data::StackData { + other: vec![( + "minecraft:bucket_entity_data".into(), + Tag::compound([("Variant", Tag::Int(3))]), + )], + ..Default::default() + })); + load_bucket_data(&mut restored, &legacy); + assert_eq!(restored.extra.variant, 3); + legacy + .data_mut() + .set_other("minecraft:axolotl/variant", Some(string("gold"))); + load_bucket_data(&mut restored, &legacy); + assert_eq!( + restored.extra.variant, 2, + "component wins over old Horizon data" + ); + crate::mobs::animal_brain::set_hunting_cooldown(&mut m, 0); assert!(bucket_data(&m).get("HuntingCooldown").is_none()); let saved = mob_to_nbt(&m, [1, 2, 3, 4], Some(&tag)); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 471e7cfae..3cdc5d3aa 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -633,6 +633,9 @@ struct Game<'a> { fullscreen: horizon_client::window::FullscreenState, /// MouseHandler's accumulated look and wheel state. mouse: MouseLook, + /// An agent moved the mouse (`mouse-move`) since the pointer was last + /// grabbed or released: its motion turns the view like a grabbed pointer. + agent_pointer: bool, /// `Options.smoothCamera` (cinematic camera), not persisted. smooth_camera: bool, /// Sneak, sprint, attack and use as ToggleKeyMappings. @@ -655,7 +658,8 @@ struct Game<'a> { fps_at: Instant, ticks: u64, health_hud: hud_layout::HealthHud, - error: Option, + /// What ends the game with an error; kept as it is, so main can tell a debug crash. + error: Option>, message: Option<(String, Instant)>, save: Arc, level: Level, @@ -3035,20 +3039,28 @@ impl Game<'_> { self.left = self.toggles.is_down(2); self.right = self.toggles.is_down(3); } - /// `MouseHandler.handleAccumulatedMovement` and `Entity.turn`, once per frame. - fn apply_mouse_look(&mut self) { - let look = LookOptions { + /// The options `MouseHandler.turnPlayer` reads. + fn look_options(&self) -> LookOptions { + LookOptions { sensitivity: f64::from(self.settings.sensitivity), smooth_camera: self.smooth_camera, scoping: self.scoping(), invert_x: self.settings.invert_x, invert_y: self.settings.invert_y, - }; + } + } + /// `MouseHandler.handleAccumulatedMovement` and `Entity.turn`, once per frame. + /// An agent moving the mouse (`mouse-move`) counts as a grabbed pointer in + /// an active window, as it cannot grab the real one. + fn apply_mouse_look(&mut self) { + let look = self.look_options(); let time = self.started.elapsed().as_secs_f64(); - let grabbed = self.captured && self.screen == Screen::Playing && self.player.is_some(); - if let Some((xo, yo)) = - self.mouse - .handle_accumulated_movement(time, self.focused, grabbed, look) + let pointer = self.captured || self.agent_pointer; + let grabbed = pointer && self.screen == Screen::Playing && self.player.is_some(); + let active = self.focused || self.agent_pointer; + if let Some((xo, yo)) = self + .mouse + .handle_accumulated_movement(time, active, grabbed, look) { let mut rotation = Rotation { x_rot: self.pitch, @@ -3071,6 +3083,8 @@ impl Game<'_> { ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { + // The real pointer takes over from an agent's. + self.agent_pointer = false; let Some(window) = &self.window else { return }; if capture { self.mouse.set_ignore_first_move(); @@ -5560,6 +5574,7 @@ impl Game<'_> { ..Level::default() }); let mut level = level; + horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name)); if let Some(d) = &self.options.dimension { level.dimension = d.clone(); level.position = None; @@ -6087,6 +6102,7 @@ impl Game<'_> { } self.stats.custom("leave_game", 1); self.save_game()?; + horizon_client::crash::clear_detail("World"); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; @@ -7088,6 +7104,7 @@ impl Game<'_> { self.options.offscreen, &assets.pixels, assets.sprite_size, + assets.sprite_minimum_size, assets.texture_layers, &assets.animations, ( @@ -8174,7 +8191,7 @@ impl Game<'_> { } fn update_world(&mut self) { if let Err(e) = self.poll_remote() { - eprintln!("Horizon: {e}"); + log::warn!("Horizon: {e}"); } if let Some(p) = &self.player { self.streaming.center = ( @@ -8209,7 +8226,7 @@ impl Game<'_> { .save_later(&modified, self.res.assets.registry, &self.res.biomes) }) { - eprintln!("Horizon: failed to save unloaded chunks: {e}"); + log::warn!("Horizon: failed to save unloaded chunks: {e}"); } if let Some(renderer) = self.renderer.as_mut() { let g = &self.settings.horizon; @@ -8280,7 +8297,7 @@ impl ApplicationHandler for Game<'_> { ) { Ok(w) => Arc::new(w), Err(e) => { - self.error = Some(e.to_string()); + self.error = Some(e.into()); event_loop.exit(); return; } @@ -8288,7 +8305,7 @@ impl ApplicationHandler for Game<'_> { match self.new_renderer(window.clone()) { Ok(r) => self.renderer = Some(r), Err(e) => { - self.error = Some(e.to_string()); + self.error = Some(e); event_loop.exit(); return; } @@ -8780,7 +8797,7 @@ impl ApplicationHandler for Game<'_> { .filter(|(_, ms)| *ms >= 0.5) .map(|(n, ms)| format!("{n} {ms:.1}")) .collect(); - eprintln!( + log::info!( "Horizon: slow frame {cpu:.1} ms ({} ticks): {}", steps, list.join(", ") @@ -8837,6 +8854,7 @@ impl ApplicationHandler for Game<'_> { self.frame_stats.record(elapsed.as_secs_f32() * 1000.0); self.frames += 1; self.fps_frames += 1; + horizon_client::crash::debug_crash_tick(); if self.fps_at.elapsed() >= Duration::from_secs(1) { self.fps = self.fps_frames as f32 / self.fps_at.elapsed().as_secs_f32(); self.fps_frames = 0; @@ -8853,7 +8871,7 @@ impl ApplicationHandler for Game<'_> { Ok(()) })(); if let Err(e) = result { - self.error = Some(e.to_string()); + self.error = Some(e); event_loop.exit(); } } @@ -8885,7 +8903,7 @@ impl ApplicationHandler for Game<'_> { /// window turns it into a window close, so Minecraft.stop saves the world. fn exiting(&mut self, _event_loop: &ActiveEventLoop) { if let Err(e) = self.save_for_exit() { - eprintln!("Horizon: failed to save the world on exit: {e}"); + log::warn!("Horizon: failed to save the world on exit: {e}"); } } } @@ -8925,7 +8943,7 @@ pub fn run() -> Result<()> { // Minecraft.rollbackResourcePacks: the packs break loading, start // with the game's own resources. Err(e) if options.resources != vanilla_root => { - eprintln!("Horizon: resource packs failed to load ({e}); using the default resources"); + log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); options.resources = vanilla_root.clone(); Assets::load(&vanilla_root)? } @@ -8938,29 +8956,29 @@ pub fn run() -> Result<()> { }; let root = options.resources.clone(); let assets = Arc::new(assets); - eprintln!("load assets: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); let facts = BlockFacts::load(&root, assets.registry)?; let mob_data = horizon_client::mobs::MobData::load(&root, &facts); - eprintln!("load facts: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32()); let items = Items::load(&root, assets.registry, &facts)?; - eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); let recipes = Recipes::load(&root, &items)?; let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; - eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); let visibility = models::load_visibility(&root, assets.registry)?; - eprintln!("load visibility: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load visibility: {:.2}s", started.elapsed().as_secs_f32()); let tables = Arc::new(MeshTables::new(&assets, &facts, visibility)?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], &early_settings.language, )); - eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); + log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); let layer_names = assets .sprite_layers .iter() @@ -8969,7 +8987,7 @@ pub fn run() -> Result<()> { let registry_owner = assets.clone(); let collision = collisions::load(&root, registry_owner.registry)?; let motion = MotionResources::load(&root, ®istry_owner)?; - eprintln!( + log::info!( "load collision+motion: {:.2}s", started.elapsed().as_secs_f32() ); @@ -8980,7 +8998,7 @@ pub fn run() -> Result<()> { light, }); let threads = early_settings.horizon.worker_threads(); - eprintln!( + log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", started.elapsed().as_secs_f32(), facts.states.len(), @@ -9115,6 +9133,7 @@ pub fn run() -> Result<()> { modifiers: winit::keyboard::ModifiersState::empty(), fullscreen: horizon_client::window::FullscreenState::new(false), mouse: MouseLook::default(), + agent_pointer: false, smooth_camera: false, toggles: Default::default(), was_playing: false, @@ -9310,7 +9329,7 @@ pub fn run() -> Result<()> { if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) .map_err(|e| format!("control socket {}: {e}", path.display()))?; - eprintln!("Horizon: control socket {}", server.path().display()); + log::info!("Horizon: control socket {}", server.path().display()); game.control = Some(server); } if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") { @@ -9363,12 +9382,12 @@ pub fn run() -> Result<()> { "generated": game.streaming.generated_total, "meshed_sections": game.streaming.meshed_total, "player": game.player.as_ref().map(|p| [p.position.x, p.position.y, p.position.z]), - "error": game.error, + "error": game.error.as_ref().map(|e| e.to_string()), }); std::fs::write(path, serde_json::to_vec_pretty(&report)?)?; } if let Some(e) = game.error { - return Err(e.into()); + return Err(e); } Ok(()) } diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index b2351a723..2de1f4c74 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -34,7 +34,9 @@ pub(super) const HELP: &[&str] = &[ "move DIR SECONDS [--sprint] [--sneak] [--jump] walk forward|back|left|right", "jump jump once", "goto X Y Z [--near R] [--sprint] [--direct] [--timeout S] walk to a position along a path", - "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID", + "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID [--over S]", + "turn DYAW DPITCH --over S rotate the view with mouse motion spread over S seconds", + "mouse-move DX DY relative mouse motion, turned like a player's mouse", "attack [ID] swing at the target (after looking at entity ID)", "break X Y Z [--timeout S] mine a block until it breaks; reports drops and pickups", "place X Y Z [--item ITEM] place the held (or given) item at a position", @@ -69,7 +71,7 @@ pub(super) struct Args<'a> { pub flags: HashMap<&'a str, Option<&'a str>>, } /// Options that take a value (`--timeout 10` or `--timeout=10`). -const VALUE_FLAGS: &[&str] = &["timeout", "near", "item", "radius", "hold", "face"]; +const VALUE_FLAGS: &[&str] = &["timeout", "near", "item", "radius", "hold", "face", "over"]; pub(super) fn parse_args<'a>(words: &[&'a str]) -> Args<'a> { let mut args = Args::default(); @@ -257,9 +259,27 @@ struct Task { name: &'static str, } +/// Mouse motion an agent feeds over frames (`mouse-move`, `turn --over`, +/// `look-at --over`): eased, through `MouseHandler`'s accumulated movement. +struct Glide { + /// The whole motion, in mouse units, and how much has been fed. + total: (f64, f64), + fed: (f64, f64), + started: Instant, + over: Duration, + /// The frame count when motion was last fed: the reply waits for the + /// frame that turns the view with it. + fed_frame: u64, + deadline: Instant, + reply: Sender, + /// What `look-at` aimed at, reported once the turn is done. + aim: Option<&'static str>, +} + #[derive(Default)] pub(super) struct Agent { task: Option, + glide: Option, } pub(super) enum Handled { @@ -975,14 +995,32 @@ impl Game<'_> { }; self.start_task("goto", TaskKind::Goto(Box::new(goto)), reply, timeout) } + "mouse-move" => { + self.turning()?; + let motion = (a.f64(0, "DX")?, a.f64(1, "DY")?); + self.start_glide(motion, 0.0, None, reply) + } + "turn" if a.has("over") => { + self.turning()?; + let (dyaw, dpitch) = (a.f64(0, "DYAW")?, a.f64(1, "DPITCH")?); + let motion = + horizon_client::mouse::motion_for_turn(dyaw, dpitch, self.look_options()); + self.start_glide(motion, a.num("over", 0.0)?, None, reply) + } "look-at" => { self.need_world()?; - match a.pos.first().copied() { + let over = a.has("over").then(|| a.num("over", 0.0)).transpose()?; + if over.is_some() { + self.turning()?; + } + let before = (self.yaw, self.pitch); + let (aim, value) = match a.pos.first().copied() { Some("block") => { let pos = a.block_pos(1)?; let face = a.pos.get(4).map(|f| face_dir(f)).transpose()?; let hit = self.aim_block(pos, face)?; - ok( + ( + "block", json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch, "face": face_name(hit) }), ) } @@ -995,16 +1033,31 @@ impl Game<'_> { .ok_or_else(|| format!("no entity {id}"))?; let c = m.center(); self.face_point(c)?; - ok( + ( + "entity", json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch, "target": self.looking_at() }), ) } _ => { let at = [a.f64(0, "X")?, a.f64(1, "Y")?, a.f64(2, "Z")?]; self.face_point(at)?; - ok(json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch })) + ( + "point", + json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch }), + ) } - } + }; + let Some(over) = over else { + return ok(value); + }; + // Turn there with the mouse instead: the shorter way round. + let target = (self.yaw, self.pitch); + (self.yaw, self.pitch) = before; + let dyaw = f64::from(target.0 - before.0 + 180.0).rem_euclid(360.0) - 180.0; + let dpitch = f64::from(target.1 - before.1); + let motion = + horizon_client::mouse::motion_for_turn(dyaw, dpitch, self.look_options()); + self.start_glide(motion, over, Some(aim), reply) } "attack" => { self.playing()?; @@ -1334,6 +1387,13 @@ impl Game<'_> { ); t.name }); + let turning = self.agent.glide.take().map(|g| { + let _ = g.reply.send( + json!({ "error": "cancelled by stop", "cancelled": true }).to_string(), + ); + "turn" + }); + let cancelled = cancelled.or(turning); self.release_agent_keys(); ok(json!({ "ok": true, "cancelled": cancelled })) } @@ -1358,8 +1418,106 @@ impl Game<'_> { Err(format!("no {item} in the inventory").into()) } + /// Mouse motion turns the view only in the world with no screen open + /// (`MouseHandler` turns the player while the mouse is grabbed). + fn turning(&self) -> Result<()> { + self.playing()?; + if self.agent.glide.is_some() { + return Err("already turning; wait for it or send stop".into()); + } + Ok(()) + } + + fn start_glide( + &mut self, + total: (f64, f64), + over: f64, + aim: Option<&'static str>, + reply: &Sender, + ) -> Result { + if !over.is_finite() || !(0.0..=60.0).contains(&over) { + return Err("--over takes 0 to 60 seconds".into()); + } + if !(total.0.is_finite() && total.1.is_finite()) { + return Err("the motion must be finite".into()); + } + let now = Instant::now(); + let over = Duration::from_secs_f64(over); + self.agent.glide = Some(Glide { + total, + fed: (0.0, 0.0), + started: now, + over, + fed_frame: self.frames, + deadline: now + over + Duration::from_secs(10), + reply: reply.clone(), + aim, + }); + self.advance_glide(); + Ok(Handled::Deferred) + } + + /// Feed the motion due by now (eased over the glide's time); reply once + /// all of it has been turned by a frame. + fn advance_glide(&mut self) { + let Some(mut g) = self.agent.glide.take() else { + return; + }; + let done = |game: &Self, extra: Value| { + let mut v = json!({ + "ok": true, + "yaw": game.yaw, + "pitch": game.pitch, + "motion": [g.total.0, g.total.1], + }); + if let (Value::Object(m), Value::Object(e)) = (&mut v, extra) { + m.extend(e); + } + v + }; + if let Err(e) = self.playing() { + let _ = g.reply.send( + json!({ "error": format!("stopped turning: {e}"), "yaw": self.yaw, "pitch": self.pitch }) + .to_string(), + ); + return; + } + let now = Instant::now(); + let t = if g.over.is_zero() { + 1.0 + } else { + now.duration_since(g.started).as_secs_f64() / g.over.as_secs_f64() + }; + let f = horizon_client::mouse::ease_in_out(t); + let due = (g.total.0 * f, g.total.1 * f); + let step = (due.0 - g.fed.0, due.1 - g.fed.1); + if step != (0.0, 0.0) { + self.mouse.add_motion(step.0, step.1); + self.agent_pointer = true; + g.fed = due; + g.fed_frame = self.frames; + } + if t >= 1.0 && self.frames > g.fed_frame { + let extra = match g.aim { + Some("block") | Some("entity") => json!({ "target": self.looking_at() }), + _ => json!({}), + }; + let _ = g.reply.send(done(self, extra).to_string()); + return; + } + if now >= g.deadline { + let _ = g.reply.send( + json!({ "error": "no frame was drawn to turn the view", "yaw": self.yaw, "pitch": self.pitch }) + .to_string(), + ); + return; + } + self.agent.glide = Some(g); + } + /// Advance the running agent task; reply when it ends. pub(super) fn advance_agent(&mut self) { + self.advance_glide(); let Some(mut task) = self.agent.task.take() else { return; }; diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index b328c3ed6..dfc6adfd8 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -378,15 +378,13 @@ impl Game<'_> { for i in dead.into_iter().rev() { let a = self.armor_stands.remove(i); let at = [a.position.x, a.position.y, a.position.z]; - for stack in a.equipment.into_iter().flatten() { - self.spawn_item(stack, at, [0.0; 3], 10); + let (pos, drops) = burnt_armor_stand_equipment(a); + for stack in drops { + self.pop_resource(pos, stack); } self.audio .play("minecraft:entity.armor_stand.break", Some(at), 1.0, 1.0); - self.world.modified.insert(( - a.position.x.floor() as i32 >> 4, - a.position.z.floor() as i32 >> 4, - )); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); } } /// ArmorStandRenderer: the stand with its default pose, then armor layers. @@ -704,3 +702,37 @@ fn skull_kind(item: &str) -> Option<&'static str> { _ => return None, }) } + +fn burnt_armor_stand_equipment(a: ArmorStand) -> ([i32; 3], Vec) { + let pos = [ + a.position.x.floor() as i32, + a.position.y.floor() as i32 + 1, + a.position.z.floor() as i32, + ]; + let drops = a + .equipment + .into_iter() + .flatten() + .filter(|stack| stack.enchantment_level("minecraft:vanishing_curse") == 0) + .collect(); + (pos, drops) +} +#[cfg(test)] +mod burn_drop_tests { + use super::*; + #[test] + fn burnt_equipment_drops_above_the_block_and_vanishing_items_do_not_drop() { + let mut stand = ArmorStand::new(1, Vec3::new(-0.1, 4.8, 0.0), 0.0); + let kept = ItemStack::new("minecraft:diamond_boots", 1); + let mut vanished = ItemStack::new("minecraft:diamond_helmet", 1); + vanished + .data_mut() + .enchantments + .push(("minecraft:vanishing_curse".into(), 1)); + stand.equipment[0] = Some(kept.clone()); + stand.equipment[1] = Some(vanished); + let (pos, drops) = burnt_armor_stand_equipment(stand); + assert_eq!(pos, [-1, 5, 0]); + assert_eq!(drops, vec![kept]); + } +} diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 8df4e8ac5..3fe6959bc 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -224,7 +224,7 @@ impl Game<'_> { max_y: 320, }; let found = inner.find_closest_biome(&search); - eprintln!("Horizon: title backdrop: {BIOME} at {found:?}"); + log::info!("Horizon: title backdrop: {BIOME} at {found:?}"); let (_, p) = found?; let _ = std::fs::write(&cache, format!("{} {}\n", p[0], p[2])); Some((p[0], p[2])) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d3a9e6a4f..5126a8982 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -782,7 +782,7 @@ impl Game<'_> { { self.audio.play( "minecraft:entity.axolotl.attack", - Some([m.position.x, m.eye_y(), m.position.z]), + Some([m.position.x, m.position.y, m.position.z]), 1.0, 1.0, ); @@ -1321,9 +1321,6 @@ impl Game<'_> { (player.velocity.y / 2.0 + 0.4).min(0.4), player.velocity.z / 2.0 + dz / l * 0.4, ); - let at = [player.position.x, player.position.y, player.position.z]; - self.audio - .play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); self.hurt_armor(amount); self.thorns(from); } @@ -1851,13 +1848,9 @@ impl Game<'_> { && self.mobs[index].alive() { let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1); - filled.extra = Some(Box::new(horizon_client::item_data::StackData { - other: vec![( - "minecraft:bucket_entity_data".into(), - horizon_client::entity_nbt::bucket_data(&self.mobs[index]), - )], - ..Default::default() - })); + filled.extra = Some(Box::new(horizon_client::entity_nbt::bucket_components( + &self.mobs[index], + ))); self.audio.play( "minecraft:item.bucket.fill_axolotl", Some(self.mobs[index].center()), diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index f695f3c3f..20d71ae85 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -151,12 +151,10 @@ impl Game<'_> { )), 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" - ); + // game stops; main writes the crash report. + let crash = horizon_client::crash::DebugCrash::new(); let _ = self.save_game(); - return Err("Manually triggered debug crash".into()); + return Err(crash.into()); } } Ok(()) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index e895eeeb0..f4e410e2f 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -58,6 +58,12 @@ static SETUP: OnceLock>> = OnceLock::new(); /// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`. pub(super) fn log(level: &str, message: &str) { + let file_level = match level { + "WARN" => ::log::Level::Warn, + "ERROR" => ::log::Level::Error, + _ => ::log::Level::Info, + }; + horizon_client::logging::write_only(file_level, message); let secs = now_millis().div_euclid(1000).rem_euclid(86_400); println!( "[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}", diff --git a/crates/horizon-client/src/game/functions.rs b/crates/horizon-client/src/game/functions.rs index e8d970ce5..b0c3aed9d 100644 --- a/crates/horizon-client/src/game/functions.rs +++ b/crates/horizon-client/src/game/functions.rs @@ -108,7 +108,7 @@ impl Game<'_> { .collect(); let store = DataStore::load(&packs); for (id, e) in &store.errors { - eprintln!("Horizon: failed to load function {id}: {e}"); + log::warn!("Horizon: failed to load function {id}: {e}"); } self.fns.store = store; self.sync_function_registries(); diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index c5a56e539..a53d0ac69 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -21,12 +21,12 @@ impl Game<'_> { match features { Ok(Some(features)) => { self.res.behaviours.set_live_features(Arc::new(features)); - eprintln!("Horizon: live features ready in {:?}", started.elapsed()); + log::info!("Horizon: live features ready in {:?}", started.elapsed()); } Ok(None) => { - eprintln!("Horizon: the worldgen bundle has no features; saplings will not grow") + log::warn!("Horizon: the worldgen bundle has no features; saplings will not grow") } - Err(e) => eprintln!("Horizon: live features unavailable: {e}"), + Err(e) => log::warn!("Horizon: live features unavailable: {e}"), } } /// `BoneMealItem.useOn` for the targeted block. diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 8697c02c9..25a8325a8 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -334,7 +334,7 @@ impl Game<'_> { if p.fire_ticks == 0 && let Err(error) = p.ignite_for_ticks(160) { - self.error = Some(error.to_string()); + self.error = Some(error); } } self.hurt_player_by("minecraft:lightning_bolt", 5.0); diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 3d4258362..f1e476f8d 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -31,7 +31,7 @@ pub fn open_folder(dir: &Path) { "xdg-open" }; if let Err(e) = std::process::Command::new(program).arg(dir).spawn() { - eprintln!("Horizon: could not open {}: {e}", dir.display()); + log::warn!("Horizon: could not open {}: {e}", dir.display()); } } /// The resource root to load from, given the vanilla root and the selection. @@ -106,7 +106,7 @@ impl Game<'_> { } let root = startup_root(&vanilla, &self.settings.resource_packs); if let Err(e) = self.reload_resources(&root) { - eprintln!("Horizon: resource reload failed: {e}"); + log::warn!("Horizon: resource reload failed: {e}"); } } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index b3117aeba..12cf69297 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -833,7 +833,7 @@ impl Game<'_> { let keys: HashSet<(i32, i32)> = unloaded.iter().map(|c| (c.x, c.z)).collect(); let chunks = self.entity_chunks(&keys, true); if let Err(e) = self.save.save_entities_later(chunks) { - eprintln!("Horizon: failed to save entities: {e}"); + log::warn!("Horizon: failed to save entities: {e}"); } } /// Leaving a dimension: its entities are saved with it. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f86b7a27f..63bd7e206 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -157,6 +157,7 @@ impl Game<'_> { .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; + horizon_client::crash::set_detail("Server", address.to_owned()); let session = Session::connect(address, name, view, lang.clone()); let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( @@ -259,6 +260,7 @@ impl Game<'_> { if let Some(mut r) = self.remote.take() { r.session.disconnect(); } + horizon_client::crash::clear_detail("Server"); self.tab_list.reset(); self.score.board = Default::default(); self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); @@ -342,7 +344,7 @@ impl Game<'_> { Some(stack) } fn chat_line(&mut self, text: String) { - eprintln!("[chat] {text}"); + log::info!("[chat] {text}"); if let Some(r) = self.remote.as_mut() { r.chat.push((text, Instant::now())); if r.chat.len() > 100 { @@ -380,12 +382,12 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.decode_errors += 1; if r.decode_errors <= 20 { - eprintln!("Horizon: skipped undecodable packet {e}"); + log::warn!("Horizon: skipped undecodable packet {e}"); } } } Event::Disconnected(reason) => { - eprintln!("Horizon: disconnected: {reason}"); + log::info!("Horizon: disconnected: {reason}"); return self.leave_server(Some(reason)); } Event::Packet(packet) => self.handle_packet(*packet)?, @@ -766,7 +768,7 @@ impl Game<'_> { self.sync_block_entity(pos, state); } } - Err(e) => eprintln!("Horizon: chunk {} {}: {e}", p.x, p.z), + Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z), }, C::ForgetLevelChunk(p) => { let [x, z] = p.pos; diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 6f51858ec..47227948c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -267,6 +267,7 @@ pub struct Renderer { animations: Vec<(SpriteAnimation, usize)>, /// Edge length of the block sprite array's layers. sprite_size: u32, + sprite_minimum_size: u32, indices: wgpu::Buffer, index_quads: u32, instances: wgpu::Buffer, @@ -375,6 +376,7 @@ impl Renderer { offscreen: bool, sprite_pixels: &[u8], sprite_size: u32, + sprite_minimum_size: u32, layers: u32, animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), @@ -399,9 +401,18 @@ impl Renderer { .await .map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?; let info = adapter.get_info(); - eprintln!( + log::info!( "Horizon renderer: {} ({:?}, {:?})", - info.name, info.backend, info.device_type + info.name, + info.backend, + info.device_type + ); + crate::crash::set_detail( + "Graphics Adapter", + format!( + "{} ({:?}, {:?}), driver {} {}", + info.name, info.backend, info.device_type, info.driver, info.driver_info + ), ); let limits = adapter.limits(); if limits.max_texture_array_layers < layers { @@ -1379,6 +1390,7 @@ impl Renderer { lightmap_sampler, animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(), sprite_size, + sprite_minimum_size, indices, index_quads, instances, @@ -1623,7 +1635,12 @@ impl Renderer { /// The Mipmap Levels option: block textures sample at most `levels` /// reduced copies (0: none). pub fn set_mipmap_levels(&mut self, levels: u32) { - let levels = sprite_mipmap_limit(levels, self.sprite_texture.width(), self.mip_levels); + let levels = sprite_mipmap_limit( + levels, + self.sprite_texture.width(), + self.sprite_minimum_size, + self.mip_levels, + ); if levels == self.mipmaps { return; } @@ -2619,9 +2636,9 @@ mod tests { } } -fn sprite_mipmap_limit(requested: u32, size: u32, available: u32) -> u32 { - // 16px textures are doubled in this atlas; mip1 retains their original texels. - let upscale = (size / 16).max(1).ilog2(); +pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, available: u32) -> u32 { + // Only the atlas native minimum determines how many resampling-only mips to skip. + let upscale = (size / minimum.max(1)).max(1).ilog2(); requested.saturating_add(upscale).min(available - 1) } fn animate_sprites( @@ -2653,8 +2670,8 @@ mod sprite_upload_tests { #[test] fn mipmap_option_keeps_real_16px_reductions() { for levels in 0..=4 { - assert_eq!(sprite_mipmap_limit(levels, 32, 6), levels + 1); - assert_eq!(sprite_mipmap_limit(levels, 16, 5), levels); + assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1); + assert_eq!(sprite_mipmap_limit(levels, 16, 16, 5), levels); } } #[test] diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index f7ef539ad..6811eb129 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -815,7 +815,7 @@ impl Hub { let mut g = self.guests.remove(i); g.left_reason = reason.to_owned(); if std::env::var_os("HORIZON_NET_DEBUG").is_some() { - eprintln!("[lan] {} left: {reason}", g.name); + log::info!("[lan] {} left: {reason}", g.name); } if !g.placed { return g; diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 5c3fc2eba..20a35cf8e 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -403,7 +403,7 @@ fn handle(stream: TcpStream, addr: SocketAddr, shared: Arc) { if let Err(e) = conn::serve(stream, addr, shared) && std::env::var_os("HORIZON_NET_DEBUG").is_some() { - eprintln!("[lan] {addr}: {e}"); + log::warn!("[lan] {addr}: {e}"); } } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6e0bd4d77..6d025c97e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -36,6 +36,7 @@ pub mod container_screen; pub mod containers; pub mod control; pub mod crafting; +pub mod crash; pub mod creative; pub mod data_cmd; pub mod datapack; @@ -79,6 +80,7 @@ pub mod lan; pub mod landing; pub mod lang; pub mod light; +pub mod logging; pub mod menu; pub mod merchant; pub mod mesher; diff --git a/crates/horizon-client/src/logging.rs b/crates/horizon-client/src/logging.rs new file mode 100644 index 000000000..c434c8efb --- /dev/null +++ b/crates/horizon-client/src/logging.rs @@ -0,0 +1,505 @@ +//! The game's log, as vanilla's log4j configuration writes it (client-1.21.2.xml, the one +//! 26.3's version manifest names): `logs/latest.log` in the game folder with the pattern +//! `[%d{HH:mm:ss}] [%t/%level]: %msg%n`, rolled over at start (OnStartupTriggeringPolicy, a +//! non-empty file only) and when the day changes (TimeBasedTriggeringPolicy) to +//! `logs/%d{yyyy-MM-dd}-%i.log.gz`, dated by the old file's last write. DefaultRolloverStrategy +//! keeps 7 archives a day, the newest with the highest index. +//! +//! Messages go through the `log` facade. Horizon's own still print their plain text on stderr, +//! as they did before the log existed; other crates' errors only reach the file (their +//! warnings are mostly the Vulkan loader's startup chatter). +use std::collections::VecDeque; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use chrono::{DateTime, Local, NaiveDate}; + +/// DefaultRolloverStrategy's default `max`: archives kept for one date. +pub const MAX_ARCHIVES_PER_DAY: u32 = 7; +/// Formatted lines kept in memory for crash reports. +const RECENT: usize = 50; + +/// The platform data folder (what the `dirs` crate's data_dir gives). +pub fn data_dir() -> PathBuf { + let env = |k: &str| { + std::env::var_os(k) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + let home = env("HOME").or_else(|| env("USERPROFILE")); + if cfg!(windows) { + if let Some(d) = env("APPDATA") { + return d; + } + } else if cfg!(target_os = "macos") { + if let Some(h) = &home { + return h.join("Library/Application Support"); + } + } else if let Some(d) = env("XDG_DATA_HOME") { + return d; + } else if let Some(h) = &home { + return h.join(".local/share"); + } + std::env::temp_dir() +} + +/// Where the launcher runs the game and keeps its saves: `HORIZON_HOME`, else `horizon` in the +/// platform data folder (launcher/src/backend.rs `game_home`). +pub fn game_home() -> PathBuf { + match std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) { + Some(h) => PathBuf::from(h), + None => data_dir().join("horizon"), + } +} + +/// `logs/` and `crash-reports/` of a game folder. +pub fn logs_dir(home: &Path) -> PathBuf { + home.join("logs") +} +pub fn crash_reports_dir(home: &Path) -> PathBuf { + home.join("crash-reports") +} + +/// `2026-10-14-3.log.gz` +pub fn archive_name(date: NaiveDate, index: u32) -> String { + format!("{}-{index}.log.gz", date.format("%Y-%m-%d")) +} + +/// The archive index of `name` if it is one of `date`'s archives. +fn archive_index(name: &str, date: NaiveDate) -> Option { + let prefix = format!("{}-", date.format("%Y-%m-%d")); + name.strip_prefix(&prefix)? + .strip_suffix(".log.gz")? + .parse() + .ok() + .filter(|&i| i > 0) +} + +/// What one rollover does to the archives already there. +#[derive(Debug, PartialEq, Eq)] +pub struct Rollover { + pub delete: Option, + /// In order: each target is free when its rename runs. + pub renames: Vec<(String, String)>, + pub archive: String, +} + +/// DefaultRolloverStrategy with fileIndex "max": the new archive takes the next index; once +/// `max` are there the lowest goes and the others move down one. +pub fn rollover(existing: &[String], date: NaiveDate, max: u32) -> Rollover { + let mut present: Vec = existing + .iter() + .filter_map(|n| archive_index(n, date)) + .collect(); + present.sort_unstable(); + present.dedup(); + let highest = present.last().copied().unwrap_or(0); + if highest < max { + return Rollover { + delete: None, + renames: Vec::new(), + archive: archive_name(date, highest + 1), + }; + } + let delete = Some(archive_name(date, present[0])); + let kept = &present[1..]; + let renames = kept + .iter() + .enumerate() + .map(|(i, &from)| (from, i as u32 + 1)) + .filter(|(from, to)| from != to) + .map(|(from, to)| (archive_name(date, from), archive_name(date, to))) + .collect(); + Rollover { + delete, + renames, + archive: archive_name(date, kept.len() as u32 + 1), + } +} + +/// `[12:04:31] [Render thread/INFO]: message` +pub fn format_line( + time: &DateTime, + thread: &str, + level: log::Level, + message: &str, +) -> String { + format!( + "[{}] [{thread}/{level}]: {message}", + time.format("%H:%M:%S") + ) +} + +/// Gzips `text` into the next archive for `date` in `dir`. +fn archive(dir: &Path, date: NaiveDate, text: &[u8]) -> io::Result<()> { + let names: Vec = fs::read_dir(dir)? + .flatten() + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); + let plan = rollover(&names, date, MAX_ARCHIVES_PER_DAY); + if let Some(name) = &plan.delete { + fs::remove_file(dir.join(name))?; + } + for (from, to) in &plan.renames { + fs::rename(dir.join(from), dir.join(to))?; + } + let mut gz = flate2::write::GzEncoder::new( + File::create(dir.join(&plan.archive))?, + flate2::Compression::default(), + ); + gz.write_all(text)?; + gz.finish()?.sync_all() +} + +/// Moves what `file` holds into an archive dated `date` and empties it. The file stays open +/// (and locked), so this works on Windows too. +fn roll(file: &mut File, dir: &Path, date: NaiveDate) -> io::Result<()> { + let mut text = Vec::new(); + file.seek(SeekFrom::Start(0))?; + file.read_to_end(&mut text)?; + if !text.is_empty() { + archive(dir, date, &text)?; + } + file.set_len(0)?; + file.seek(SeekFrom::Start(0))?; + Ok(()) +} + +/// The open `latest.log` and the lock that keeps it this game's. +pub struct Latest { + pub file: File, + _lock: File, +} + +/// Opens `dir/latest.log` for this run, archiving the last run's. None when another Horizon +/// using the same folder is writing it: that game keeps it, this one logs to stderr only. The +/// lock is a separate file (`.lock`): Windows locks are mandatory, and a locked latest.log could +/// not be read while the game runs. +pub fn open_latest(dir: &Path) -> io::Result> { + fs::create_dir_all(dir)?; + let lock = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(dir.join(".lock"))?; + match lock.try_lock() { + Ok(()) => {} + Err(fs::TryLockError::WouldBlock) => return Ok(None), + Err(fs::TryLockError::Error(e)) => return Err(e), + } + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(dir.join("latest.log"))?; + let modified = file.metadata()?.modified()?; + let date = DateTime::::from(modified).date_naive(); + roll(&mut file, dir, date)?; + Ok(Some(Latest { file, _lock: lock })) +} + +struct State { + file: Option, + dir: PathBuf, + /// The day the open file's lines belong to. + date: NaiveDate, + recent: VecDeque, +} + +struct Logger { + state: Mutex, + /// What the main thread is called in the log: "Render thread", or "Server thread" for the + /// dedicated server, as in vanilla. + main_thread: &'static str, +} + +static LOGGER: std::sync::OnceLock = std::sync::OnceLock::new(); + +fn ours(target: &str) -> bool { + target.starts_with("horizon") +} + +impl log::Log for Logger { + fn enabled(&self, meta: &log::Metadata) -> bool { + meta.level() <= log::Level::Info + && (ours(meta.target()) || meta.level() <= log::Level::Error) + } + + fn log(&self, record: &log::Record) { + if !self.enabled(record.metadata()) { + return; + } + let message = record.args().to_string(); + if ours(record.target()) { + eprintln!("{message}"); + } + let current = std::thread::current(); + let thread = match current.name() { + Some("main") => self.main_thread, + Some(name) => name, + None => "unnamed", + }; + self.write(thread, record.level(), &message); + } + + fn flush(&self) { + if let Some(latest) = &mut self.state.lock().unwrap_or_else(|e| e.into_inner()).file { + let _ = latest.file.flush(); + } + } +} + +impl Logger { + fn write(&self, thread: &str, level: log::Level, message: &str) { + let now = Local::now(); + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let state = &mut *state; + if now.date_naive() != state.date { + if let Some(latest) = &mut state.file + && let Err(e) = roll(&mut latest.file, &state.dir, state.date) + { + eprintln!("Horizon: could not roll over the log: {e}"); + } + state.date = now.date_naive(); + } + // As log4j writes a multi-line message: the pattern once, the rest as it is. + for (i, line) in message.lines().enumerate() { + let line = if i == 0 { + format_line(&now, thread, level, line) + } else { + line.to_owned() + }; + if let Some(latest) = &mut state.file { + let _ = writeln!(latest.file, "{line}"); + } + state.recent.push_back(line); + if state.recent.len() > RECENT { + state.recent.pop_front(); + } + } + } +} + +/// Starts the log in `home/logs`. The main thread shows as `main_thread` in it. Messages are +/// still printed when the file cannot be opened. +pub fn init(home: &Path, main_thread: &'static str) { + let dir = logs_dir(home); + let file = match open_latest(&dir) { + Ok(Some(latest)) => Some(latest), + Ok(None) => { + eprintln!( + "Horizon: another game is writing {}; this one logs to the terminal only", + dir.join("latest.log").display() + ); + None + } + Err(e) => { + eprintln!( + "Horizon: could not open {}: {e}", + dir.join("latest.log").display() + ); + None + } + }; + let logger = LOGGER.get_or_init(|| Logger { + state: Mutex::new(State { + file, + dir, + date: Local::now().date_naive(), + recent: VecDeque::new(), + }), + main_thread, + }); + if log::set_logger(logger).is_ok() { + log::set_max_level(log::LevelFilter::Info); + } +} + +/// A line in the log from code that prints it elsewhere itself (the dedicated server console). +pub fn write_only(level: log::Level, message: &str) { + if let Some(logger) = LOGGER.get() { + let current = std::thread::current(); + let thread = match current.name() { + Some("main") | None => logger.main_thread, + Some(name) => name, + }; + logger.write(thread, level, message); + } +} + +/// The last lines written, oldest first (for crash reports). +pub fn recent_lines() -> Vec { + LOGGER.get().map_or_else(Vec::new, |l| { + l.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .recent + .iter() + .cloned() + .collect() + }) +} + +/// Flushes the log file (before the process exits). +pub fn flush() { + if let Some(logger) = LOGGER.get() { + log::Log::flush(logger); + } +} + +/// The last `lines` lines of a text file. +pub fn tail(path: &Path, lines: usize) -> io::Result> { + let text = fs::read(path)?; + let text = String::from_utf8_lossy(&text); + let all: Vec<&str> = text.lines().collect(); + Ok(all[all.len().saturating_sub(lines)..] + .iter() + .map(|l| l.to_string()) + .collect()) +} + +/// The newest `crash-*.txt` in a game folder's crash-reports (names sort by time). +pub fn newest_crash_report(home: &Path) -> Option { + fs::read_dir(crash_reports_dir(home)) + .ok()? + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("crash-") && n.ends_with(".txt")) + }) + .max_by_key(|p| p.file_name().map(|n| n.to_owned())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn day(d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 10, d).unwrap() + } + + #[test] + fn archives_are_named_like_vanillas() { + assert_eq!(archive_name(day(4), 1), "2026-10-04-1.log.gz"); + let none: Vec = Vec::new(); + assert_eq!( + rollover(&none, day(14), 7), + Rollover { + delete: None, + renames: vec![], + archive: "2026-10-14-1.log.gz".into() + } + ); + // Another day's archives and unrelated files do not count. + let names: Vec = [ + "2026-10-13-1.log.gz", + "2026-10-13-2.log.gz", + "2026-10-14-1.log.gz", + "2026-10-14-2.log.gz", + "latest.log", + "debug-1.log.gz", + ] + .map(String::from) + .to_vec(); + assert_eq!(rollover(&names, day(14), 7).archive, "2026-10-14-3.log.gz"); + assert_eq!(rollover(&names, day(13), 7).archive, "2026-10-13-3.log.gz"); + assert_eq!(rollover(&names, day(15), 7).archive, "2026-10-15-1.log.gz"); + } + + #[test] + fn the_eighth_archive_of_a_day_drops_the_oldest() { + let names: Vec = (1..=7).map(|i| archive_name(day(14), i)).collect(); + let plan = rollover(&names, day(14), 7); + assert_eq!(plan.delete.as_deref(), Some("2026-10-14-1.log.gz")); + assert_eq!(plan.renames.len(), 6); + assert_eq!( + plan.renames[0], + ("2026-10-14-2.log.gz".into(), "2026-10-14-1.log.gz".into()) + ); + assert_eq!( + plan.renames[5], + ("2026-10-14-7.log.gz".into(), "2026-10-14-6.log.gz".into()) + ); + assert_eq!(plan.archive, "2026-10-14-7.log.gz"); + } + + #[test] + fn lines_look_like_log4js_pattern() { + let time = chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(); + assert_eq!( + format_line( + &time, + "Render thread", + log::Level::Info, + "load assets: 1.20s" + ), + "[09:05:07] [Render thread/INFO]: load assets: 1.20s" + ); + assert_eq!( + format_line(&time, "Worker-1", log::Level::Warn, "x"), + "[09:05:07] [Worker-1/WARN]: x" + ); + } + + #[test] + fn startup_archives_the_last_runs_log() { + let dir = std::env::temp_dir().join(format!("horizon-logs-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + // Empty: nothing is archived (OnStartupTriggeringPolicy's minSize is 1 byte). + drop(open_latest(&dir).unwrap().unwrap()); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 2); + fs::write( + dir.join("latest.log"), + "[10:00:00] [Render thread/INFO]: first run\n", + ) + .unwrap(); + let mut latest = open_latest(&dir).unwrap().unwrap(); + // A second game in the same folder leaves the file alone. + assert!(open_latest(&dir).unwrap().is_none()); + writeln!(latest.file, "second run").unwrap(); + drop(latest); + let today = Local::now().date_naive(); + let archive = dir.join(archive_name(today, 1)); + let mut text = String::new(); + flate2::read::GzDecoder::new(File::open(&archive).unwrap()) + .read_to_string(&mut text) + .unwrap(); + assert_eq!(text, "[10:00:00] [Render thread/INFO]: first run\n"); + assert_eq!( + fs::read_to_string(dir.join("latest.log")).unwrap(), + "second run\n" + ); + assert_eq!( + tail(&dir.join("latest.log"), 100).unwrap(), + vec!["second run"] + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn the_newest_crash_report_is_found_by_name() { + let home = std::env::temp_dir().join(format!("horizon-crash-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&home); + assert!(newest_crash_report(&home).is_none()); + let dir = crash_reports_dir(&home); + fs::create_dir_all(&dir).unwrap(); + for name in [ + "crash-2026-10-13_23.59.59-client.txt", + "crash-2026-10-14_08.00.01-client.txt", + "notes.txt", + ] { + fs::write(dir.join(name), "x").unwrap(); + } + assert_eq!( + newest_crash_report(&home).unwrap(), + dir.join("crash-2026-10-14_08.00.01-client.txt") + ); + let _ = fs::remove_dir_all(&home); + } +} diff --git a/crates/horizon-client/src/main.rs b/crates/horizon-client/src/main.rs index febc160c3..30ccd26a4 100644 --- a/crates/horizon-client/src/main.rs +++ b/crates/horizon-client/src/main.rs @@ -2,9 +2,27 @@ #![forbid(unsafe_code)] mod game; +use horizon_client::{crash, logging}; + fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let game_args = args.iter().take_while(|a| *a != "--dedicated"); + let help = game_args.clone().any(|a| a == "--help" || a == "-h"); + // The dedicated server logs in its own folder, as vanilla's does; the game in its home. + let (home, side, thread) = if args.iter().any(|a| a == "--dedicated") { + (std::path::PathBuf::from("."), "server", "Server thread") + } else { + (logging::game_home(), "client", "Render thread") + }; + if !help { + logging::init(&home, thread); + crash::install(home.clone(), side); + } if let Err(error) = game::run() { - eprintln!("Horizon: {error}"); + log::error!("Horizon: {error}"); + if !help { + crash::report_error(&home, side, &*error); + } // Started from Explorer, the console window closes with the game: // keep the message on screen until it is read. #[cfg(windows)] @@ -14,4 +32,5 @@ fn main() { } std::process::exit(1); } + logging::flush(); } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index c72342faa..71bbdd109 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -794,6 +794,8 @@ pub struct Mob { pub invulnerable_flag: bool, pub climbing: bool, pub fire_ticks: i32, + pub ticks_frozen: i32, + pub glowing: bool, pub air: i32, pub last_hurt: f32, pub last_damage: Option<(Damage, i64)>, @@ -1183,6 +1185,7 @@ impl Mob { self.fire_ticks = self .fire_ticks .max((f64::from(ticks) * self.burning_time()).ceil() as i32); + self.ticks_frozen = 0; } /// What other mobs see of this one this tick (`player`: the player's @@ -1445,6 +1448,8 @@ impl Mob { invulnerable_flag: false, climbing: false, fire_ticks: 0, + ticks_frozen: 0, + glowing: false, air: 300, last_hurt: 0.0, last_damage: None, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index dcd466053..a99d09ddc 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -408,6 +408,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { &mut m.random, multiplier, ); + if m.fire_ticks >= 0 { + m.ticks_frozen = 0; + } m.damage(fire, Damage::of(DamageKind::InFire)); } // Fire: water extinguishes, lava ignites, burning hurts every second. diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index ac314c730..1d26333f3 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -1431,20 +1431,21 @@ impl B { } else { 2 }; + let eyes = m.species() != Species::Axolotl; let mm = mem(m); mm.walk_target.set(WalkTarget { target: Tracker::Entity { who: adult, - eye: true, - block_eye: true, + eye: eyes, + block_eye: eyes, }, speed, close, }); mm.look_target.set(Tracker::Entity { who: adult, - eye: true, - block_eye: true, + eye: eyes, + block_eye: eyes, }); true } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 896439f32..ead166ffc 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -248,9 +248,17 @@ impl PlayerMotion { .unwrap_or(300) as i32; } } + pub fn set_remaining_fire_ticks(&mut self, ticks: i32) { + self.fire_ticks = if self.invulnerable { + ticks.min(1) + } else { + ticks + }; + } pub fn ignite_for_ticks(&mut self, ticks: i32) -> Result<()> { let scaled = (f64::from(ticks) * self.attribute("minecraft:burning_time")?).ceil() as i32; - self.fire_ticks = self.fire_ticks.max(scaled); + self.set_remaining_fire_ticks(self.fire_ticks.max(scaled)); + self.ticks_frozen = 0; Ok(()) } @@ -809,7 +817,8 @@ impl MotionWorld<'_, '_, '_> { self.player.no_jump_delay = 0; } if self.player.swimming { - let look_y = f64::from(-self.player.pitch.to_radians().sin()); + let look_y = + horizon_world::view_direction::view_vector(self.player.pitch, self.player.yaw).y; let near_surface = BlockPos::containing(Vec3::new( self.player.position.x, self.player.position.y + 0.9, @@ -1940,6 +1949,22 @@ mod tests { .any(|e| matches!(e, MotionEvent::HurtSound(_))) ); } + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let source = resources.health.damage.id("minecraft:mob_attack").unwrap(); + assert!( + player + .hurt_blocking(&resources.health, Default::default(), source, 2.0, None) + .unwrap() + .hurt + ); + assert_eq!( + player + .events + .iter() + .filter(|e| matches!(e, MotionEvent::HurtSound("minecraft:entity.player.hurt"))) + .count(), + 1 + ); } /// Footsteps on the prepared vanilla resources, when they are present: @@ -2056,9 +2081,22 @@ mod tests { w.player.fire_ticks = -20; w.controlled_simulation_tick(Default::default()).unwrap(); assert_eq!( - w.player.fire_ticks, 1, - "creative fire contact must remain visible" + w.player.fire_ticks, -19, + "creative preserves the fire-contact delay" ); + for _ in 0..18 { + w.apply_fire_contact().unwrap(); + } + assert_eq!(w.player.fire_ticks, -1); + w.apply_fire_contact().unwrap(); + assert_eq!( + w.player.fire_ticks, 1, + "creative clamps only after ignition" + ); + w.player.ticks_frozen = 140; + w.player.ignite_for_ticks(160).unwrap(); + assert_eq!(w.player.ticks_frozen, 0); + assert_eq!(w.player.fire_ticks, 1); w.player.invulnerable = false; // Sprint swimming must keep full input, not the dry crawl/sneak multiplier. for x in 19..=21 { diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index 9d5044b6f..5af3cc98f 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -97,11 +97,7 @@ impl MotionWorld<'_, '_, '_> { self.player.air = (self.player.air + 4).min(300); } if self.player.in_lava { - if self.player.invulnerable { - self.player.fire_ticks = 1; - } else { - self.player.ignite_for_ticks(300)?; - } + self.player.ignite_for_ticks(300)?; self.environment_hurt("minecraft:lava", 4.0)?; self.player.fall_distance *= 0.5; } @@ -115,16 +111,16 @@ impl MotionWorld<'_, '_, '_> { let damage = fire_contact(self.scene, self.assets.registry, self.player.bounds()); if damage > 0.0 { if !self.player.in_water { - if self.player.invulnerable { - self.player.fire_ticks = 1; - } else { - let multiplier = self.player.attribute("minecraft:burning_time")?; - self.player.fire_ticks = ignite_contact( - self.player.fire_ticks, - true, - &mut self.scene.random, - multiplier, - ); + let multiplier = self.player.attribute("minecraft:burning_time")?; + let ticks = ignite_contact( + self.player.fire_ticks, + true, + &mut self.scene.random, + multiplier, + ); + self.player.set_remaining_fire_ticks(ticks); + if ticks >= 0 { + self.player.ticks_frozen = 0; } } self.environment_hurt("minecraft:in_fire", damage)?; diff --git a/crates/horizon-client/src/mouse.rs b/crates/horizon-client/src/mouse.rs index 08d3fe0e9..d2794d790 100644 --- a/crates/horizon-client/src/mouse.rs +++ b/crates/horizon-client/src/mouse.rs @@ -202,6 +202,13 @@ impl MouseLook { } } + /// `onMove` with the pointer grabbed, for relative motion an agent makes + /// (`horizon-ctl mouse-move`): added to the frame's accumulated movement. + pub fn add_motion(&mut self, dx: f64, dy: f64) { + self.accumulated_dx += dx; + self.accumulated_dy += dy; + } + /// Movement accumulated since the last frame (for screens' mouse-moved events). pub fn accumulated(&self) -> (f64, f64) { (self.accumulated_dx, self.accumulated_dy) @@ -226,9 +233,7 @@ impl MouseLook { } fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) { - let ss = look.sensitivity * f64::from(0.6f32) + f64::from(0.2f32); - let sensitivity_mod = ss * ss * ss; - let sens = sensitivity_mod * 8.0; + let (sensitivity_mod, sens) = sensitivity_scales(look.sensitivity); let (xo, yo) = if look.smooth_camera { ( self.smooth_turn_x @@ -274,9 +279,172 @@ impl MouseLook { } } +/// `MouseHandler.turnPlayer`'s scales: `sensitivityMod = (s*0.6F+0.2F)^3` +/// and `sens = sensitivityMod * 8`. +fn sensitivity_scales(sensitivity: f64) -> (f64, f64) { + let ss = sensitivity * f64::from(0.6f32) + f64::from(0.2f32); + let sensitivity_mod = ss * ss * ss; + (sensitivity_mod, sensitivity_mod * 8.0) +} + +/// Degrees `Entity.turn` turns per unit of mouse motion: 0.15 x `sens` +/// (`sensitivityMod` while scoping). With the cinematic camera the same total +/// is reached, spread over the following frames. +pub fn degrees_per_count(look: LookOptions) -> f64 { + let (sensitivity_mod, sens) = sensitivity_scales(look.sensitivity); + let scale = if look.scoping && !look.smooth_camera { + sensitivity_mod + } else { + sens + }; + 0.15 * scale +} + +/// The mouse motion that turns the view by `dyaw` and `dpitch` degrees with +/// these options, the inverted axes included. +pub fn motion_for_turn(dyaw: f64, dpitch: f64, look: LookOptions) -> (f64, f64) { + let per_count = degrees_per_count(look); + let flip = |inverted: bool| if inverted { -1.0 } else { 1.0 }; + ( + dyaw / per_count * flip(look.invert_x), + dpitch / per_count * flip(look.invert_y), + ) +} + +/// Ease-in-out (a half cosine) over `t` in 0..=1: how much of a spread-out +/// turn is done at that point of its time. +pub fn ease_in_out(t: f64) -> f64 { + let t = t.clamp(0.0, 1.0); + 0.5 - 0.5 * (std::f64::consts::PI * t).cos() +} + #[cfg(test)] mod tests { use super::*; + + const PLAIN: LookOptions = LookOptions { + sensitivity: 0.5, + smooth_camera: false, + scoping: false, + invert_x: false, + invert_y: false, + }; + + /// One frame of motion `(dx, dy)` through `onMove`'s grabbed path, + /// `handleAccumulatedMovement` and `Entity.turn`. + fn frame(look: &mut MouseLook, rot: &mut Rotation, time: f64, d: (f64, f64), o: LookOptions) { + look.add_motion(d.0, d.1); + if let Some((xo, yo)) = look.handle_accumulated_movement(time, true, true, o) { + rot.turn(xo, yo); + } + } + + fn rotation() -> Rotation { + Rotation { + x_rot: 0.0, + y_rot: 0.0, + x_rot_o: 0.0, + y_rot_o: 0.0, + } + } + + #[test] + fn turn_player_matches_the_vanilla_formula() { + // MouseHandler.turnPlayer: ss = sensitivity*0.6F + 0.2F, sens = ss^3 * 8, + // then Entity.turn: yRot += (float)xo * 0.15F, xRot += (float)yo * 0.15F. + for sensitivity in [0.0, 0.25, 0.5, 0.75, 1.0] { + for (dx, dy) in [(1.0, 0.0), (37.0, -12.5), (-400.0, 250.0)] { + let o = LookOptions { + sensitivity, + ..PLAIN + }; + let ss = sensitivity * f64::from(0.6f32) + f64::from(0.2f32); + let sens = ss * ss * ss * 8.0; + let mut look = MouseLook::default(); + let mut rot = rotation(); + frame(&mut look, &mut rot, 1.0, (dx, dy), o); + let yaw = (dx * sens) as f32 * 0.15; + let pitch = ((dy * sens) as f32 * 0.15).clamp(-90.0, 90.0); + assert_eq!( + (rot.y_rot, rot.x_rot), + (yaw, pitch), + "s {sensitivity} d {dx},{dy}" + ); + } + } + } + + #[test] + fn inverted_and_scoping_turns() { + let mut look = MouseLook::default(); + let mut rot = rotation(); + let o = LookOptions { + invert_y: true, + ..PLAIN + }; + frame(&mut look, &mut rot, 1.0, (0.0, 10.0), o); + assert!(rot.x_rot < 0.0, "inverted Y looks up: {}", rot.x_rot); + // Scoping drops the factor 8. + let scoped = LookOptions { + scoping: true, + ..PLAIN + }; + assert!((degrees_per_count(PLAIN) / degrees_per_count(scoped) - 8.0).abs() < 1e-12); + } + + #[test] + fn motion_for_turn_round_trips_through_turn_player() { + for o in [ + PLAIN, + LookOptions { + sensitivity: 0.9, + invert_x: true, + invert_y: true, + ..PLAIN + }, + LookOptions { + scoping: true, + ..PLAIN + }, + ] { + let (dx, dy) = motion_for_turn(73.5, -21.25, o); + let mut look = MouseLook::default(); + let mut rot = rotation(); + frame(&mut look, &mut rot, 1.0, (dx, dy), o); + assert!((rot.y_rot - 73.5).abs() < 1e-3, "{o:?}: {}", rot.y_rot); + assert!((rot.x_rot + 21.25).abs() < 1e-3, "{o:?}: {}", rot.x_rot); + } + } + + #[test] + fn cinematic_camera_spreads_the_same_motion_over_frames() { + // SmoothDouble: the first frame turns part of the way, later frames + // without new motion carry on towards the same total. + let o = LookOptions { + smooth_camera: true, + ..PLAIN + }; + let (dx, _) = motion_for_turn(30.0, 0.0, o); + let mut look = MouseLook::default(); + let mut rot = rotation(); + frame(&mut look, &mut rot, 0.0, (0.0, 0.0), o); + frame(&mut look, &mut rot, 1.0 / 60.0, (dx, 0.0), o); + let first = rot.y_rot; + assert!(first > 0.0 && first < 30.0, "{first}"); + for i in 2..600 { + frame(&mut look, &mut rot, f64::from(i) / 60.0, (0.0, 0.0), o); + } + assert!((rot.y_rot - 30.0).abs() < 0.05, "{}", rot.y_rot); + } + + #[test] + fn ease_in_out_starts_and_ends_slowly() { + assert_eq!(ease_in_out(0.0), 0.0); + assert!((ease_in_out(0.5) - 0.5).abs() < 1e-12); + assert!((ease_in_out(1.0) - 1.0).abs() < 1e-12); + assert!(ease_in_out(0.1) < 0.1 && ease_in_out(0.9) > 0.9); + assert_eq!(ease_in_out(2.0), 1.0); + } #[test] fn default_sensitivity_turns_point_fifteen_degrees_per_count_at_one() { let mut look = MouseLook::default(); diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index c5bd7c341..2dee3206e 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -623,7 +623,7 @@ pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf { match build_overlay(vanilla, packs, &out) { Ok(()) => out, Err(e) => { - eprintln!("Horizon: resource packs not applied: {e}"); + log::warn!("Horizon: resource packs not applied: {e}"); vanilla.to_path_buf() } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0b03efa24..970432080 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1394,7 +1394,7 @@ impl SaveDir { }; let records = batch.iter().map(|(k, r, _)| (*k, r.tag())).collect(); if let Err(e) = write_region_records(&root, cache, folder, records) { - eprintln!("Horizon: failed to write {folder} files: {e}"); + log::warn!("Horizon: failed to write {folder} files: {e}"); } // Readers find the files (and a fresh region cache) from here on. if let Ok(mut pending) = pending.lock() { diff --git a/crates/horizon-client/src/server/user_lists.rs b/crates/horizon-client/src/server/user_lists.rs index 5e4643e1c..3d35aa62f 100644 --- a/crates/horizon-client/src/server/user_lists.rs +++ b/crates/horizon-client/src/server/user_lists.rs @@ -356,7 +356,7 @@ impl UserList { } self.map.put(key, entry); if let Err(e) = self.save() { - eprintln!("Could not save the list after adding a user. {e}"); + log::warn!("Could not save the list after adding a user. {e}"); } true } @@ -365,7 +365,7 @@ impl UserList { return false; } if let Err(e) = self.save() { - eprintln!("Could not save the list after removing a user. {e}"); + log::warn!("Could not save the list after removing a user. {e}"); } true } diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index fabf7194a..064337668 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -280,16 +280,55 @@ impl Settings { .parent() .map(crate::graphics::Graphics::load) .unwrap_or_default(); - let Ok(bytes) = fs::read(path) else { - return Self { + let settings = match fs::read(path) { + Ok(bytes) => Self { + horizon, + ..Self::parse(&String::from_utf8_lossy(&bytes)) + }, + Err(_) => Self { horizon, ..Self::default() - }; + }, }; - Self { - horizon, - ..Self::parse(&String::from_utf8_lossy(&bytes)) - } + settings.describe_for_crashes(); + settings + } + /// The render settings and resource packs a crash report lists. + fn describe_for_crashes(&self) { + let on = |b: bool| if b { "on" } else { "off" }; + let scale = match self.gui_scale { + 0 => "auto".to_owned(), + n => n.to_string(), + }; + crate::crash::set_detail( + "Render Settings", + format!( + "render distance {}, simulation distance {}, graphics {}, FOV {:.0}, max FPS {}, VSync {}, fullscreen {}, GUI scale {scale}, smooth lighting {}, clouds {}, biome blend {}, mipmap levels {}", + self.render_distance, + self.simulation_distance, + self.graphics_preset, + self.fov, + if self.max_fps >= 260 { + "unlimited".to_owned() + } else { + self.max_fps.to_string() + }, + on(self.vsync), + on(self.fullscreen), + on(self.smooth_lighting), + self.clouds, + self.biome_blend, + self.mipmap_levels, + ), + ); + crate::crash::set_detail( + "Resource Packs", + if self.resource_packs.is_empty() { + "vanilla".to_owned() + } else { + self.resource_packs.join(", ") + }, + ); } pub fn parse(text: &str) -> Self { Self::from_file(OptionsFile::parse(text)) @@ -474,6 +513,7 @@ impl Settings { self.to_file().serialize() } pub fn save(&self, path: &Path) { + self.describe_for_crashes(); let _ = fs::write(path, self.serialize()); if let Some(dir) = path.parent() { self.horizon.save(dir); diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index 7744e7b43..5c325e684 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -41,6 +41,8 @@ pub struct Sprites { /// Edge length of every array layer and the layers' current frames, set /// by [`Sprites::finish`]. pub size: u32, + /// Smallest native layer before array-size resampling. + pub minimum_size: u32, pub pixels: Vec, pub layers: BTreeMap, pub animations: Vec, @@ -78,6 +80,7 @@ impl Sprites { pub fn finish(&mut self) { let layers = self.native.len().max(1) as u64; let largest = self.native.iter().map(|n| n.0).max().unwrap_or(SPRITE_SIZE); + self.minimum_size = self.native.iter().map(|n| n.0).min().unwrap_or(SPRITE_SIZE); let mut size = largest.max(SPRITE_SIZE).next_power_of_two(); while size > SPRITE_SIZE && layers * u64::from(size * size) * 4 > MAX_ARRAY_BYTES { size /= 2; @@ -105,7 +108,7 @@ impl Sprites { match self.load(root, name) { Ok(layer) => Ok(layer), Err(e) => { - eprintln!("Horizon: using the missing texture for {name}: {e}"); + log::warn!("Horizon: using the missing texture for {name}: {e}"); // MissingTextureAtlasSprite.generateMissingImage: 16x16, // magenta and black quarters. let frame: Vec = (0..SPRITE_SIZE * SPRITE_SIZE) @@ -243,6 +246,34 @@ pub(crate) fn test_animation(size: u32, layer: u32) -> SpriteAnimation { #[cfg(test)] mod tests { use super::*; + #[test] + fn a_32px_only_atlas_does_not_add_an_extra_mipmap() { + let mut sprites = Sprites { + native: vec![ + (32, Arc::new(vec![vec![255; 32 * 32 * 4]]), 0), + (32, Arc::new(vec![vec![128; 32 * 32 * 4]]), 0), + ], + ..Default::default() + }; + sprites.finish(); + assert_eq!((sprites.size, sprites.minimum_size), (32, 32)); + for level in 0..=4 { + assert_eq!( + crate::gfx::sprite_mipmap_limit(level, sprites.size, sprites.minimum_size, 6), + level + ); + } + sprites + .native + .push((16, Arc::new(vec![vec![255; 16 * 16 * 4]]), 0)); + sprites.finish(); + assert_eq!((sprites.size, sprites.minimum_size), (32, 16)); + assert_eq!( + crate::gfx::sprite_mipmap_limit(0, sprites.size, sprites.minimum_size, 6), + 1 + ); + } + #[test] fn hud_animation_resampling_uses_the_actual_frame_size() { for size in [16, 32, 64] { diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 63b835f3d..09288359b 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -18,7 +18,7 @@ pub fn loot_data(root: &Path) -> Option> { LOOT.get_or_init(|| match LootData::load(root) { Ok(data) => Some(Arc::new(data)), Err(e) => { - eprintln!("Horizon: loot tables unavailable, structure containers stay empty: {e}"); + log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}"); None } }) diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 86d2a3922..ac242c588 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -55,12 +55,12 @@ impl VanillaTerrain { OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?; let unsupported = generator.unsupported_features(); if !unsupported.is_empty() { - eprintln!( + log::warn!( "Horizon: {} placed features cannot run and will be skipped", unsupported.len() ); if !dir.join("blocks/block-properties.nbt").exists() { - eprintln!( + log::warn!( "Horizon: the worldgen bundle lacks the block behavior exports (worldgen/blocks/*.nbt); \ prepare again (the launcher, or horizon-prepare --prepare) to add them" ); @@ -156,7 +156,7 @@ impl ChunkGenerator for VanillaTerrain { match worker.generate_proto(ChunkPos::new(x, z)) { Ok(chunk) => Box::new(VanillaProto::Ready(Box::new(chunk))), Err(e) => { - eprintln!("Horizon: generating chunk {x} {z} failed: {e}"); + log::warn!("Horizon: generating chunk {x} {z} failed: {e}"); Box::new(VanillaProto::Failed(x, z)) } } @@ -187,7 +187,7 @@ impl ChunkGenerator for VanillaTerrain { Err(_) => unreachable!(), }; if let Err(e) = worker.decorate(&mut array) { - eprintln!("Horizon: decorating chunk failed: {e}"); + log::warn!("Horizon: decorating chunk failed: {e}"); } for (slot, chunk) in region.iter_mut().zip(array) { *slot = Box::new(VanillaProto::Ready(Box::new(chunk))); diff --git a/docs/native-client.md b/docs/native-client.md index f25067d64..4522966ec 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -136,6 +136,21 @@ the launcher, `horizon-ctl launch --world X --wait` is all an agent needs. Other arguments go to the game; its output goes to a `.log` file beside the socket. +**Logs and crash reports.** Like vanilla, the game writes `logs/latest.log` +in the game home (`$HORIZON_HOME`, else `~/.local/share/horizon`; the +dedicated server in its own folder) with lines like +`[12:04:31] [Render thread/INFO]: message`, and at start archives the last +run's as `logs/-.log.gz` (seven a day). Messages still print on +stderr as before. A panic on the main thread or a fatal error writes +`crash-reports/crash--client.txt` (the error, its stack, +the machine, the GPU, render settings, resource packs, the open world and the +last 50 log lines) and the game exits with a non-zero code. `horizon-ctl logs +[--lines N]` prints the end of latest.log and `horizon-ctl logs --crash` the +newest report (the `logs` MCP tool returns the same). F3 + C held for ten +seconds crashes the game on purpose, as in vanilla (the world is saved first); +development builds also crash with `HORIZON_DEBUG_CRASH=SECONDS`, that long +after the first frame. + **MCP.** `horizon-ctl mcp` serves the Model Context Protocol over stdin and stdout (JSON-RPC 2.0, one message per line), with one tool per command and a JSON schema for each; `screenshot` returns the frame as an image. Register it diff --git a/launcher/README.md b/launcher/README.md index 828903ab3..11c25d056 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -67,9 +67,10 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher links the Discord, sponsor and website links horizon-launcher menu-style [horizon|classic] show or set the game's menu style horizon-launcher update [--check] Horizon and the launcher + horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `menu-style`, `update --check`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `menu-style`, `update --check`, `logs`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). @@ -81,12 +82,23 @@ scripts and tests). (with the full path to the binary if it is not on your `PATH`). Its tools: `list_versions`, `install_version`, `remove_version`, `prepare_resources`, `launch_client`, `start_server`, -`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style` and `check_updates`. +`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style`, `logs` and +`check_updates`. A server started through MCP stops (cleanly, with `stop`) when the session ends. Starting one needs `accept_eula`, which an agent should only pass with the player's consent. The window, the command line and the MCP server all call the same core, `src/backend.rs`. +## Logs and crash reports + +The game writes its log to `logs/latest.log` in the game folder (`HORIZON_HOME`, else +`~/.local/share/horizon`, `~/Library/Application Support/horizon` or `%APPDATA%\horizon`), and +archives the previous one at start as `logs/-.log.gz`, as Minecraft does. When it +crashes it writes `crash-reports/crash-_