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/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 0c54ed309..8683402a2 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -150,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", 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/game.rs b/crates/horizon-client/src/game.rs index 4d506b7f5..483646a90 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -658,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, @@ -5437,6 +5438,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; @@ -5962,6 +5964,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; @@ -7970,7 +7973,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 = ( @@ -8005,7 +8008,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; @@ -8076,7 +8079,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; } @@ -8084,7 +8087,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; } @@ -8576,7 +8579,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(", ") @@ -8633,6 +8636,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; @@ -8648,7 +8652,7 @@ impl ApplicationHandler for Game<'_> { Ok(()) })(); if let Err(e) = result { - self.error = Some(e.to_string()); + self.error = Some(e); event_loop.exit(); } } @@ -8680,7 +8684,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}"); } } } @@ -8720,7 +8724,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)? } @@ -8733,29 +8737,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() @@ -8764,7 +8768,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() ); @@ -8775,7 +8779,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(), @@ -9104,7 +9108,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") { @@ -9157,12 +9161,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/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/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/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 f7288bb80..e847e1b9b 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 c1f1e69da..4c539156e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -399,9 +399,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 { 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 ea3e268e0..8ae91ae29 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; @@ -78,6 +79,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/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 39707ef1d..c9d7616ae 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -93,7 +93,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) 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-_